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,
71 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */
72 #define MIN_SEND_BUF_LENGTH 4000
74 /* This list of SSL3 cipher suites is sorted in descending order of
75 * precedence (desirability). It only includes cipher suites we implement.
76 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
77 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
79 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
80 /* cipher_suite policy enabled is_present*/
82 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
83 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
84 #endif /* NSS_ENABLE_ECC */
85 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
86 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
87 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
88 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
89 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
91 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
92 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
93 #endif /* NSS_ENABLE_ECC */
94 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
95 { TLS_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
96 { TLS_RSA_WITH_AES_256_CBC_SHA256, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
99 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
100 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
101 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
102 { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
103 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
104 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
105 #endif /* NSS_ENABLE_ECC */
106 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
107 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
108 { TLS_DHE_DSS_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
109 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
110 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
111 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
112 #ifdef NSS_ENABLE_ECC
113 { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
114 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
115 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
116 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
117 #endif /* NSS_ENABLE_ECC */
118 { TLS_RSA_WITH_SEED_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
119 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
120 { SSL_RSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
121 { SSL_RSA_WITH_RC4_128_MD5, SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
122 { TLS_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
123 { TLS_RSA_WITH_AES_128_CBC_SHA256, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
125 #ifdef NSS_ENABLE_ECC
126 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
127 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
128 #endif /* NSS_ENABLE_ECC */
129 { SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
130 { SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
131 #ifdef NSS_ENABLE_ECC
132 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
133 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
134 #endif /* NSS_ENABLE_ECC */
135 { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
136 { SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
139 { SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
140 { SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
141 { SSL_RSA_FIPS_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
142 { SSL_RSA_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
143 { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
144 { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
146 { SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
147 { SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
149 #ifdef NSS_ENABLE_ECC
150 { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
151 { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
152 { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
153 { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
154 #endif /* NSS_ENABLE_ECC */
155 { SSL_RSA_WITH_NULL_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
156 { TLS_RSA_WITH_NULL_SHA256, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
157 { SSL_RSA_WITH_NULL_MD5, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
161 /* This list of SSL3 compression methods is sorted in descending order of
162 * precedence (desirability). It only includes compression methods we
165 static const /*SSLCompressionMethod*/ PRUint8 compressions [] = {
166 #ifdef NSS_ENABLE_ZLIB
167 ssl_compression_deflate,
172 static const int compressionMethodsCount =
173 sizeof(compressions) / sizeof(compressions[0]);
175 /* compressionEnabled returns true iff the compression algorithm is enabled
176 * for the given SSL socket. */
178 compressionEnabled(sslSocket *ss, SSLCompressionMethod compression)
180 switch (compression) {
181 case ssl_compression_null:
182 return PR_TRUE; /* Always enabled */
183 #ifdef NSS_ENABLE_ZLIB
184 case ssl_compression_deflate:
185 return ss->opt.enableDeflate;
192 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = {
194 #ifdef NSS_ENABLE_ECC
196 #endif /* NSS_ENABLE_ECC */
200 /* This block is the contents of the supported_signature_algorithms field of
201 * our TLS 1.2 CertificateRequest message, in wire format. See
202 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
204 * This block contains only sha256 entries because we only support TLS 1.2
205 * CertificateVerify messages that use the handshake hash. */
206 static const PRUint8 supported_signature_algorithms[] = {
207 tls_hash_sha256, tls_sig_rsa,
208 #ifdef NSS_ENABLE_ECC
209 tls_hash_sha256, tls_sig_ecdsa,
211 tls_hash_sha256, tls_sig_dsa,
214 #define EXPORT_RSA_KEY_LENGTH 64 /* bytes */
217 /* This global item is used only in servers. It is is initialized by
218 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
220 CERTDistNames *ssl3_server_ca_list = NULL;
221 static SSL3Statistics ssl3stats;
223 /* indexed by SSL3BulkCipher */
224 static const ssl3BulkCipherDef bulk_cipher_defs[] = {
225 /* cipher calg keySz secretSz type ivSz BlkSz keygen */
226 {cipher_null, calg_null, 0, 0, type_stream, 0, 0, kg_null},
227 {cipher_rc4, calg_rc4, 16, 16, type_stream, 0, 0, kg_strong},
228 {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, kg_export},
229 {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, kg_export},
230 {cipher_rc2, calg_rc2, 16, 16, type_block, 8, 8, kg_strong},
231 {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, kg_export},
232 {cipher_des, calg_des, 8, 8, type_block, 8, 8, kg_strong},
233 {cipher_3des, calg_3des, 24, 24, type_block, 8, 8, kg_strong},
234 {cipher_des40, calg_des, 8, 5, type_block, 8, 8, kg_export},
235 {cipher_idea, calg_idea, 16, 16, type_block, 8, 8, kg_strong},
236 {cipher_aes_128, calg_aes, 16, 16, type_block, 16,16, kg_strong},
237 {cipher_aes_256, calg_aes, 32, 32, type_block, 16,16, kg_strong},
238 {cipher_camellia_128, calg_camellia,16, 16, type_block, 16,16, kg_strong},
239 {cipher_camellia_256, calg_camellia,32, 32, type_block, 16,16, kg_strong},
240 {cipher_seed, calg_seed, 16, 16, type_block, 16,16, kg_strong},
241 {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, kg_null},
244 static const ssl3KEADef kea_defs[] =
245 { /* indexed by SSL3KeyExchangeAlgorithm */
246 /* kea exchKeyType signKeyType is_limited limit tls_keygen */
247 {kea_null, kt_null, sign_null, PR_FALSE, 0, PR_FALSE},
248 {kea_rsa, kt_rsa, sign_rsa, PR_FALSE, 0, PR_FALSE},
249 {kea_rsa_export, kt_rsa, sign_rsa, PR_TRUE, 512, PR_FALSE},
250 {kea_rsa_export_1024,kt_rsa, sign_rsa, PR_TRUE, 1024, PR_FALSE},
251 {kea_dh_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE},
252 {kea_dh_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE},
253 {kea_dh_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE},
254 {kea_dh_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE},
255 {kea_dhe_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE},
256 {kea_dhe_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE},
257 {kea_dhe_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE},
258 {kea_dhe_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE},
259 {kea_dh_anon, kt_dh, sign_null, PR_FALSE, 0, PR_FALSE},
260 {kea_dh_anon_export, kt_dh, sign_null, PR_TRUE, 512, PR_FALSE},
261 {kea_rsa_fips, kt_rsa, sign_rsa, PR_FALSE, 0, PR_TRUE },
262 #ifdef NSS_ENABLE_ECC
263 {kea_ecdh_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE},
264 {kea_ecdhe_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE},
265 {kea_ecdh_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE},
266 {kea_ecdhe_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE},
267 {kea_ecdh_anon, kt_ecdh, sign_null, PR_FALSE, 0, PR_FALSE},
268 #endif /* NSS_ENABLE_ECC */
271 /* must use ssl_LookupCipherSuiteDef to access */
272 static const ssl3CipherSuiteDef cipher_suite_defs[] =
274 /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg */
276 {SSL_NULL_WITH_NULL_NULL, cipher_null, mac_null, kea_null},
277 {SSL_RSA_WITH_NULL_MD5, cipher_null, mac_md5, kea_rsa},
278 {SSL_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_rsa},
279 {TLS_RSA_WITH_NULL_SHA256, cipher_null, hmac_sha256, kea_rsa},
280 {SSL_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export},
281 {SSL_RSA_WITH_RC4_128_MD5, cipher_rc4, mac_md5, kea_rsa},
282 {SSL_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_rsa},
283 {SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
284 cipher_rc2_40, mac_md5, kea_rsa_export},
285 #if 0 /* not implemented */
286 {SSL_RSA_WITH_IDEA_CBC_SHA, cipher_idea, mac_sha, kea_rsa},
287 {SSL_RSA_EXPORT_WITH_DES40_CBC_SHA,
288 cipher_des40, mac_sha, kea_rsa_export},
290 {SSL_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa},
291 {SSL_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa},
292 {SSL_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_dss},
293 {SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
294 cipher_3des, mac_sha, kea_dhe_dss},
295 {TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_dhe_dss},
296 #if 0 /* not implemented */
297 {SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
298 cipher_des40, mac_sha, kea_dh_dss_export},
299 {SSL_DH_DSS_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_dss},
300 {SSL_DH_DSS_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_dss},
301 {SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
302 cipher_des40, mac_sha, kea_dh_rsa_export},
303 {SSL_DH_RSA_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_rsa},
304 {SSL_DH_RSA_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_rsa},
305 {SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
306 cipher_des40, mac_sha, kea_dh_dss_export},
307 {SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
308 cipher_des40, mac_sha, kea_dh_rsa_export},
310 {SSL_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_rsa},
311 {SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
312 cipher_3des, mac_sha, kea_dhe_rsa},
314 {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export},
315 {SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA,
316 cipher_des40, mac_sha, kea_dh_anon_export},
317 {SSL_DH_ANON_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_anon},
318 {SSL_DH_ANON_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_anon},
322 /* New TLS cipher suites */
323 {TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_rsa},
324 {TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_rsa},
325 {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_dss},
326 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_rsa},
327 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_rsa},
328 {TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_rsa},
329 {TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_rsa},
330 {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_dss},
331 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_rsa},
332 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_rsa},
334 {TLS_DH_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_dss},
335 {TLS_DH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_rsa},
336 {TLS_DH_ANON_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_anon},
337 {TLS_DH_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_dss},
338 {TLS_DH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_rsa},
339 {TLS_DH_ANON_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_anon},
342 {TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, mac_sha, kea_rsa},
344 {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa},
345 {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
346 cipher_camellia_128, mac_sha, kea_dhe_dss},
347 {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
348 cipher_camellia_128, mac_sha, kea_dhe_rsa},
349 {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa},
350 {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
351 cipher_camellia_256, mac_sha, kea_dhe_dss},
352 {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
353 cipher_camellia_256, mac_sha, kea_dhe_rsa},
355 {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,
356 cipher_des, mac_sha,kea_rsa_export_1024},
357 {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,
358 cipher_rc4_56, mac_sha,kea_rsa_export_1024},
360 {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips},
361 {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa_fips},
363 #ifdef NSS_ENABLE_ECC
364 {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa},
365 {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa},
366 {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa},
367 {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecdsa},
368 {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecdsa},
370 {TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_ecdsa},
371 {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_ecdsa},
372 {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecdsa},
373 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ecdsa},
374 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_ecdsa},
375 {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ecdsa},
377 {TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_rsa},
378 {TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_rsa},
379 {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_rsa},
380 {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_rsa},
381 {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_rsa},
383 {TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_rsa},
384 {TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_rsa},
385 {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_rsa},
386 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_rsa},
387 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_rsa},
388 {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_rsa},
391 {TLS_ECDH_anon_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_anon},
392 {TLS_ECDH_anon_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_anon},
393 {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_anon},
394 {TLS_ECDH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_anon},
395 {TLS_ECDH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_anon},
397 #endif /* NSS_ENABLE_ECC */
400 static const CK_MECHANISM_TYPE kea_alg_defs[] = {
408 typedef struct SSLCipher2MechStr {
409 SSLCipherAlgorithm calg;
410 CK_MECHANISM_TYPE cmech;
413 /* indexed by type SSLCipherAlgorithm */
414 static const SSLCipher2Mech alg2Mech[] = {
416 { calg_null , (CK_MECHANISM_TYPE)0x80000000L },
417 { calg_rc4 , CKM_RC4 },
418 { calg_rc2 , CKM_RC2_CBC },
419 { calg_des , CKM_DES_CBC },
420 { calg_3des , CKM_DES3_CBC },
421 { calg_idea , CKM_IDEA_CBC },
422 { calg_fortezza , CKM_SKIPJACK_CBC64 },
423 { calg_aes , CKM_AES_CBC },
424 { calg_camellia , CKM_CAMELLIA_CBC },
425 { calg_seed , CKM_SEED_CBC },
426 /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */
429 #define mmech_null (CK_MECHANISM_TYPE)0x80000000L
430 #define mmech_md5 CKM_SSL3_MD5_MAC
431 #define mmech_sha CKM_SSL3_SHA1_MAC
432 #define mmech_md5_hmac CKM_MD5_HMAC
433 #define mmech_sha_hmac CKM_SHA_1_HMAC
434 #define mmech_sha256_hmac CKM_SHA256_HMAC
436 static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */
437 /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */
438 /* mac mmech pad_size mac_size */
439 { mac_null, mmech_null, 0, 0 },
440 { mac_md5, mmech_md5, 48, MD5_LENGTH },
441 { mac_sha, mmech_sha, 40, SHA1_LENGTH},
442 {hmac_md5, mmech_md5_hmac, 0, MD5_LENGTH },
443 {hmac_sha, mmech_sha_hmac, 0, SHA1_LENGTH},
444 {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH},
447 /* indexed by SSL3BulkCipher */
448 const char * const ssl3_cipherName[] = {
467 #ifdef NSS_ENABLE_ECC
468 /* The ECCWrappedKeyInfo structure defines how various pieces of
469 * information are laid out within wrappedSymmetricWrappingkey
470 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
471 * a 512-byte buffer (see sslimpl.h), the variable length field
472 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
474 * XXX For now, NSS only supports named elliptic curves of size 571 bits
475 * or smaller. The public value will fit within 145 bytes and EC params
476 * will fit within 12 bytes. We'll need to revisit this when NSS
477 * supports arbitrary curves.
479 #define MAX_EC_WRAPPED_KEY_BUFLEN 504
481 typedef struct ECCWrappedKeyInfoStr {
482 PRUint16 size; /* EC public key size in bits */
483 PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */
484 PRUint16 pubValueLen; /* length (in bytes) of EC public value */
485 PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */
486 PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
487 /* EC public-key params, the EC public value and the wrapped key */
489 #endif /* NSS_ENABLE_ECC */
494 ssl3_DecodeHandshakeType(int msgType)
497 static char line[40];
500 case hello_request: rv = "hello_request (0)"; break;
501 case client_hello: rv = "client_hello (1)"; break;
502 case server_hello: rv = "server_hello (2)"; break;
503 case hello_verify_request: rv = "hello_verify_request (3)"; break;
504 case certificate: rv = "certificate (11)"; break;
505 case server_key_exchange: rv = "server_key_exchange (12)"; break;
506 case certificate_request: rv = "certificate_request (13)"; break;
507 case server_hello_done: rv = "server_hello_done (14)"; break;
508 case certificate_verify: rv = "certificate_verify (15)"; break;
509 case client_key_exchange: rv = "client_key_exchange (16)"; break;
510 case finished: rv = "finished (20)"; break;
512 sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType);
519 ssl3_DecodeContentType(int msgType)
522 static char line[40];
525 case content_change_cipher_spec:
526 rv = "change_cipher_spec (20)"; break;
527 case content_alert: rv = "alert (21)"; break;
528 case content_handshake: rv = "handshake (22)"; break;
529 case content_application_data:
530 rv = "application_data (23)"; break;
532 sprintf(line, "*UNKNOWN* record type! (%d)", msgType);
541 SSL_GetStatistics(void)
546 typedef struct tooLongStr {
547 #if defined(IS_LITTLE_ENDIAN)
556 void SSL_AtomicIncrementLong(long * x)
558 if ((sizeof *x) == sizeof(PRInt32)) {
559 PR_ATOMIC_INCREMENT((PRInt32 *)x);
561 tooLong * tl = (tooLong *)x;
562 if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
563 PR_ATOMIC_INCREMENT(&tl->high);
568 ssl3_CipherSuiteAllowedForVersion(ssl3CipherSuite cipherSuite,
569 SSL3ProtocolVersion version)
571 switch (cipherSuite) {
572 /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or
573 * later. This set of cipher suites is similar to, but different from, the
574 * set of cipher suites considered exportable by SSL_IsExportCipherSuite.
576 case SSL_RSA_EXPORT_WITH_RC4_40_MD5:
577 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5:
578 /* SSL_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
579 * SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented
580 * SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
581 * SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented
582 * SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
583 * SSL_DH_ANON_EXPORT_WITH_RC4_40_MD5: never implemented
584 * SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA: never implemented
586 return version <= SSL_LIBRARY_VERSION_TLS_1_0;
587 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
588 case TLS_RSA_WITH_AES_256_CBC_SHA256:
589 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
590 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
591 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
592 case TLS_RSA_WITH_AES_128_CBC_SHA256:
593 case TLS_RSA_WITH_NULL_SHA256:
594 return version >= SSL_LIBRARY_VERSION_TLS_1_2;
600 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */
601 /* XXX This does a linear search. A binary search would be better. */
602 static const ssl3CipherSuiteDef *
603 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
605 int cipher_suite_def_len =
606 sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
609 for (i = 0; i < cipher_suite_def_len; i++) {
610 if (cipher_suite_defs[i].cipher_suite == suite)
611 return &cipher_suite_defs[i];
613 PORT_Assert(PR_FALSE); /* We should never get here. */
614 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
618 /* Find the cipher configuration struct associate with suite */
619 /* XXX This does a linear search. A binary search would be better. */
620 static ssl3CipherSuiteCfg *
621 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites)
625 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
626 if (suites[i].cipher_suite == suite)
629 /* return NULL and let the caller handle it. */
630 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
635 /* Initialize the suite->isPresent value for config_match
636 * Returns count of enabled ciphers supported by extant tokens,
637 * regardless of policy or user preference.
638 * If this returns zero, the user cannot do SSL v3.
641 ssl3_config_match_init(sslSocket *ss)
643 ssl3CipherSuiteCfg * suite;
644 const ssl3CipherSuiteDef *cipher_def;
645 SSLCipherAlgorithm cipher_alg;
646 CK_MECHANISM_TYPE cipher_mech;
647 SSL3KEAType exchKeyType;
652 sslServerCerts *svrAuth;
656 PORT_SetError(SEC_ERROR_INVALID_ARGS);
659 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
662 isServer = (PRBool)(ss->sec.isServer != 0);
664 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
665 suite = &ss->cipherSuites[i];
666 if (suite->enabled) {
668 /* We need the cipher defs to see if we have a token that can handle
669 * this cipher. It isn't part of the static definition.
671 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
673 suite->isPresent = PR_FALSE;
676 cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg;
677 PORT_Assert( alg2Mech[cipher_alg].calg == cipher_alg);
678 cipher_mech = alg2Mech[cipher_alg].cmech;
680 kea_defs[cipher_def->key_exchange_alg].exchKeyType;
681 #ifndef NSS_ENABLE_ECC
682 svrAuth = ss->serverCerts + exchKeyType;
684 /* XXX SSLKEAType isn't really a good choice for
685 * indexing certificates. It doesn't work for
686 * (EC)DHE-* ciphers. Here we use a hack to ensure
687 * that the server uses an RSA cert for (EC)DHE-RSA.
689 switch (cipher_def->key_exchange_alg) {
691 #if NSS_SERVER_DHE_IMPLEMENTED
692 /* XXX NSS does not yet implement the server side of _DHE_
693 * cipher suites. Correcting the computation for svrAuth,
694 * as the case below does, causes NSS SSL servers to begin to
695 * negotiate cipher suites they do not implement. So, until
696 * server side _DHE_ is implemented, keep this disabled.
700 svrAuth = ss->serverCerts + kt_rsa;
705 * XXX We ought to have different indices for
706 * ECDSA- and RSA-signed EC certificates so
707 * we could support both key exchange mechanisms
708 * simultaneously. For now, both of them use
709 * whatever is in the certificate slot for kt_ecdh
712 svrAuth = ss->serverCerts + exchKeyType;
715 #endif /* NSS_ENABLE_ECC */
717 /* Mark the suites that are backed by real tokens, certs and keys */
718 suite->isPresent = (PRBool)
719 (((exchKeyType == kt_null) ||
720 ((!isServer || (svrAuth->serverKeyPair &&
721 svrAuth->SERVERKEY &&
722 svrAuth->serverCertChain)) &&
723 PK11_TokenExists(kea_alg_defs[exchKeyType]))) &&
724 ((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech)));
725 if (suite->isPresent)
729 PORT_Assert(numPresent > 0 || numEnabled == 0);
730 if (numPresent <= 0) {
731 PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
737 /* return PR_TRUE if suite matches policy and enabled state */
738 /* It would be a REALLY BAD THING (tm) if we ever permitted the use
739 ** of a cipher that was NOT_ALLOWED. So, if this is ever called with
740 ** policy == SSL_NOT_ALLOWED, report no match.
742 /* adjust suite enabled to the availability of a token that can do the
745 config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled)
747 PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE);
748 if (policy == SSL_NOT_ALLOWED || !enabled)
750 return (PRBool)(suite->enabled &&
752 suite->policy != SSL_NOT_ALLOWED &&
753 suite->policy <= policy);
756 /* return number of cipher suites that match policy and enabled state */
757 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */
759 count_cipher_suites(sslSocket *ss, int policy, PRBool enabled)
763 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
766 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
767 if (config_match(&ss->cipherSuites[i], policy, enabled))
771 PORT_SetError(SSL_ERROR_SSL_DISABLED);
777 * Null compression, mac and encryption functions
781 Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen,
782 const unsigned char *input, int inputLen)
784 *outputLen = inputLen;
786 PORT_Memcpy(output, input, inputLen);
791 * SSL3 Utility functions
794 /* allowLargerPeerVersion controls whether the function will select the
795 * highest enabled SSL version or fail when peerVersion is greater than the
796 * highest enabled version.
798 * If allowLargerPeerVersion is true, peerVersion is the peer's highest
799 * enabled version rather than the peer's selected version.
802 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
803 PRBool allowLargerPeerVersion)
805 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
806 PORT_SetError(SSL_ERROR_SSL_DISABLED);
810 if (peerVersion < ss->vrange.min ||
811 (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
812 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
816 ss->version = PR_MIN(peerVersion, ss->vrange.max);
817 PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, ss->version));
823 ssl3_GetNewRandom(SSL3Random *random)
825 PRUint32 gmt = ssl_Time();
828 random->rand[0] = (unsigned char)(gmt >> 24);
829 random->rand[1] = (unsigned char)(gmt >> 16);
830 random->rand[2] = (unsigned char)(gmt >> 8);
831 random->rand[3] = (unsigned char)(gmt);
833 /* first 4 bytes are reserverd for time */
834 rv = PK11_GenerateRandom(&random->rand[4], SSL3_RANDOM_LENGTH - 4);
835 if (rv != SECSuccess) {
836 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
841 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
843 ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf,
846 SECStatus rv = SECFailure;
847 PRBool doDerEncode = PR_FALSE;
853 switch (key->keyType) {
855 hashItem.data = hash->u.raw;
856 hashItem.len = hash->len;
860 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
861 * In that case, we use just the SHA1 part. */
862 if (hash->hashAlg == SEC_OID_UNKNOWN) {
863 hashItem.data = hash->u.s.sha;
864 hashItem.len = sizeof(hash->u.s.sha);
866 hashItem.data = hash->u.raw;
867 hashItem.len = hash->len;
870 #ifdef NSS_ENABLE_ECC
872 doDerEncode = PR_TRUE;
873 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
874 * In that case, we use just the SHA1 part. */
875 if (hash->hashAlg == SEC_OID_UNKNOWN) {
876 hashItem.data = hash->u.s.sha;
877 hashItem.len = sizeof(hash->u.s.sha);
879 hashItem.data = hash->u.raw;
880 hashItem.len = hash->len;
883 #endif /* NSS_ENABLE_ECC */
885 PORT_SetError(SEC_ERROR_INVALID_KEY);
888 PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
890 if (hash->hashAlg == SEC_OID_UNKNOWN) {
891 signatureLen = PK11_SignatureLen(key);
892 if (signatureLen <= 0) {
893 PORT_SetError(SEC_ERROR_INVALID_KEY);
897 buf->len = (unsigned)signatureLen;
898 buf->data = (unsigned char *)PORT_Alloc(signatureLen);
900 goto done; /* error code was set. */
902 rv = PK11_Sign(key, buf, &hashItem);
904 rv = SGN_Digest(key, hash->hashAlg, buf, &hashItem);
906 if (rv != SECSuccess) {
907 ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
908 } else if (doDerEncode) {
909 SECItem derSig = {siBuffer, NULL, 0};
911 /* This also works for an ECDSA signature */
912 rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
913 if (rv == SECSuccess) {
914 PORT_Free(buf->data); /* discard unencoded signature. */
915 *buf = derSig; /* give caller encoded signature. */
916 } else if (derSig.data) {
917 PORT_Free(derSig.data);
921 PRINT_BUF(60, (NULL, "signed hashes", (unsigned char*)buf->data, buf->len));
923 if (rv != SECSuccess && buf->data) {
924 PORT_Free(buf->data);
930 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
932 ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert,
933 SECItem *buf, PRBool isTLS, void *pwArg)
935 SECKEYPublicKey * key;
936 SECItem * signature = NULL;
943 PRINT_BUF(60, (NULL, "check signed hashes",
944 buf->data, buf->len));
946 key = CERT_ExtractPublicKey(cert);
948 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
952 hashAlg = hash->hashAlg;
953 switch (key->keyType) {
955 encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
956 hashItem.data = hash->u.raw;
957 hashItem.len = hash->len;
960 encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
961 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
962 * In that case, we use just the SHA1 part. */
963 if (hash->hashAlg == SEC_OID_UNKNOWN) {
964 hashItem.data = hash->u.s.sha;
965 hashItem.len = sizeof(hash->u.s.sha);
967 hashItem.data = hash->u.raw;
968 hashItem.len = hash->len;
970 /* Allow DER encoded DSA signatures in SSL 3.0 */
971 if (isTLS || buf->len != SECKEY_SignatureLen(key)) {
972 signature = DSAU_DecodeDerSig(buf);
974 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
981 #ifdef NSS_ENABLE_ECC
983 encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
984 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
985 * In that case, we use just the SHA1 part.
986 * ECDSA signatures always encode the integers r and s using ASN.1
987 * (unlike DSA where ASN.1 encoding is used with TLS but not with
988 * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
990 if (hash->hashAlg == SEC_OID_UNKNOWN) {
991 hashAlg = SEC_OID_SHA1;
992 hashItem.data = hash->u.s.sha;
993 hashItem.len = sizeof(hash->u.s.sha);
995 hashItem.data = hash->u.raw;
996 hashItem.len = hash->len;
999 #endif /* NSS_ENABLE_ECC */
1002 SECKEY_DestroyPublicKey(key);
1003 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
1007 PRINT_BUF(60, (NULL, "hash(es) to be verified",
1008 hashItem.data, hashItem.len));
1010 if (hashAlg == SEC_OID_UNKNOWN || key->keyType == dsaKey) {
1011 /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1012 * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1013 * above always removes the DER encoding of DSA signatures when
1014 * present. Thus DSA signatures are always verified with PK11_Verify.
1016 rv = PK11_Verify(key, buf, &hashItem, pwArg);
1018 rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
1021 SECKEY_DestroyPublicKey(key);
1023 SECITEM_FreeItem(signature, PR_TRUE);
1025 if (rv != SECSuccess) {
1026 ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1032 /* Caller must set hiLevel error code. */
1033 /* Called from ssl3_ComputeExportRSAKeyHash
1034 * ssl3_ComputeDHKeyHash
1035 * which are called from ssl3_HandleServerKeyExchange.
1037 * hashAlg: either the OID for a hash algorithm or SEC_OID_UNKNOWN to specify
1038 * the pre-1.2, MD5/SHA1 combination hash.
1041 ssl3_ComputeCommonKeyHash(SECOidTag hashAlg,
1042 PRUint8 * hashBuf, unsigned int bufLen,
1043 SSL3Hashes *hashes, PRBool bypassPKCS11)
1045 SECStatus rv = SECSuccess;
1047 #ifndef NO_PKCS11_BYPASS
1049 if (hashAlg == SEC_OID_UNKNOWN) {
1050 MD5_HashBuf (hashes->u.s.md5, hashBuf, bufLen);
1051 SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen);
1052 hashes->len = MD5_LENGTH + SHA1_LENGTH;
1053 } else if (hashAlg == SEC_OID_SHA1) {
1054 SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen);
1055 hashes->len = SHA1_LENGTH;
1056 } else if (hashAlg == SEC_OID_SHA256) {
1057 SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen);
1058 hashes->len = SHA256_LENGTH;
1059 } else if (hashAlg == SEC_OID_SHA384) {
1060 SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen);
1061 hashes->len = SHA384_LENGTH;
1062 } else if (hashAlg == SEC_OID_SHA512) {
1063 SHA512_HashBuf(hashes->u.raw, hashBuf, bufLen);
1064 hashes->len = SHA512_LENGTH;
1066 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1072 if (hashAlg == SEC_OID_UNKNOWN) {
1073 rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen);
1074 if (rv != SECSuccess) {
1075 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
1080 rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen);
1081 if (rv != SECSuccess) {
1082 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
1085 hashes->len = MD5_LENGTH + SHA1_LENGTH;
1087 hashes->len = HASH_ResultLenByOidTag(hashAlg);
1088 if (hashes->len > sizeof(hashes->u.raw)) {
1089 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1093 rv = PK11_HashBuf(hashAlg, hashes->u.raw, hashBuf, bufLen);
1094 if (rv != SECSuccess) {
1095 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
1100 hashes->hashAlg = hashAlg;
1106 /* Caller must set hiLevel error code.
1107 ** Called from ssl3_SendServerKeyExchange and
1108 ** ssl3_HandleServerKeyExchange.
1111 ssl3_ComputeExportRSAKeyHash(SECOidTag hashAlg,
1112 SECItem modulus, SECItem publicExponent,
1113 SSL3Random *client_rand, SSL3Random *server_rand,
1114 SSL3Hashes *hashes, PRBool bypassPKCS11)
1118 SECStatus rv = SECSuccess;
1119 unsigned int bufLen;
1120 PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
1122 bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len;
1123 if (bufLen <= sizeof buf) {
1126 hashBuf = PORT_Alloc(bufLen);
1132 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
1133 pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1134 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1135 pBuf += SSL3_RANDOM_LENGTH;
1136 pBuf[0] = (PRUint8)(modulus.len >> 8);
1137 pBuf[1] = (PRUint8)(modulus.len);
1139 memcpy(pBuf, modulus.data, modulus.len);
1140 pBuf += modulus.len;
1141 pBuf[0] = (PRUint8)(publicExponent.len >> 8);
1142 pBuf[1] = (PRUint8)(publicExponent.len);
1144 memcpy(pBuf, publicExponent.data, publicExponent.len);
1145 pBuf += publicExponent.len;
1146 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1148 rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
1151 PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen));
1152 if (hashAlg == SEC_OID_UNKNOWN) {
1153 PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result",
1154 hashes->u.s.md5, MD5_LENGTH));
1155 PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result",
1156 hashes->u.s.sha, SHA1_LENGTH));
1158 PRINT_BUF(95, (NULL, "RSAkey hash: result",
1159 hashes->u.raw, hashes->len));
1162 if (hashBuf != buf && hashBuf != NULL)
1167 /* Caller must set hiLevel error code. */
1168 /* Called from ssl3_HandleServerKeyExchange. */
1170 ssl3_ComputeDHKeyHash(SECOidTag hashAlg,
1171 SECItem dh_p, SECItem dh_g, SECItem dh_Ys,
1172 SSL3Random *client_rand, SSL3Random *server_rand,
1173 SSL3Hashes *hashes, PRBool bypassPKCS11)
1177 SECStatus rv = SECSuccess;
1178 unsigned int bufLen;
1179 PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
1181 bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len;
1182 if (bufLen <= sizeof buf) {
1185 hashBuf = PORT_Alloc(bufLen);
1191 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
1192 pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1193 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1194 pBuf += SSL3_RANDOM_LENGTH;
1195 pBuf[0] = (PRUint8)(dh_p.len >> 8);
1196 pBuf[1] = (PRUint8)(dh_p.len);
1198 memcpy(pBuf, dh_p.data, dh_p.len);
1200 pBuf[0] = (PRUint8)(dh_g.len >> 8);
1201 pBuf[1] = (PRUint8)(dh_g.len);
1203 memcpy(pBuf, dh_g.data, dh_g.len);
1205 pBuf[0] = (PRUint8)(dh_Ys.len >> 8);
1206 pBuf[1] = (PRUint8)(dh_Ys.len);
1208 memcpy(pBuf, dh_Ys.data, dh_Ys.len);
1210 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1212 rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
1215 PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen));
1216 if (hashAlg == SEC_OID_UNKNOWN) {
1217 PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",
1218 hashes->u.s.md5, MD5_LENGTH));
1219 PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",
1220 hashes->u.s.sha, SHA1_LENGTH));
1222 PRINT_BUF(95, (NULL, "DHkey hash: result",
1223 hashes->u.raw, hashes->len));
1226 if (hashBuf != buf && hashBuf != NULL)
1232 ssl3_BumpSequenceNumber(SSL3SequenceNumber *num)
1239 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */
1241 ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat)
1243 if (mat->write_key != NULL) {
1244 PK11_FreeSymKey(mat->write_key);
1245 mat->write_key = NULL;
1247 if (mat->write_mac_key != NULL) {
1248 PK11_FreeSymKey(mat->write_mac_key);
1249 mat->write_mac_key = NULL;
1251 if (mat->write_mac_context != NULL) {
1252 PK11_DestroyContext(mat->write_mac_context, PR_TRUE);
1253 mat->write_mac_context = NULL;
1257 /* Called from ssl3_SendChangeCipherSpecs() and
1258 ** ssl3_HandleChangeCipherSpecs()
1259 ** ssl3_DestroySSL3Info
1260 ** Caller must hold SpecWriteLock.
1263 ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName)
1265 PRBool freeit = (PRBool)(!spec->bypassCiphers);
1266 /* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */
1267 if (spec->destroy) {
1268 spec->destroy(spec->encodeContext, freeit);
1269 spec->destroy(spec->decodeContext, freeit);
1270 spec->encodeContext = NULL; /* paranoia */
1271 spec->decodeContext = NULL;
1273 if (spec->destroyCompressContext && spec->compressContext) {
1274 spec->destroyCompressContext(spec->compressContext, 1);
1275 spec->compressContext = NULL;
1277 if (spec->destroyDecompressContext && spec->decompressContext) {
1278 spec->destroyDecompressContext(spec->decompressContext, 1);
1279 spec->decompressContext = NULL;
1281 if (freeSrvName && spec->srvVirtName.data) {
1282 SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE);
1284 if (spec->master_secret != NULL) {
1285 PK11_FreeSymKey(spec->master_secret);
1286 spec->master_secret = NULL;
1288 spec->msItem.data = NULL;
1289 spec->msItem.len = 0;
1290 ssl3_CleanupKeyMaterial(&spec->client);
1291 ssl3_CleanupKeyMaterial(&spec->server);
1292 spec->bypassCiphers = PR_FALSE;
1294 spec->destroyCompressContext = NULL;
1295 spec->destroyDecompressContext = NULL;
1298 /* Fill in the pending cipher spec with info from the selected ciphersuite.
1299 ** This is as much initialization as we can do without having key material.
1300 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1301 ** Caller must hold the ssl3 handshake lock.
1302 ** Acquires & releases SpecWriteLock.
1305 ssl3_SetupPendingCipherSpec(sslSocket *ss)
1307 ssl3CipherSpec * pwSpec;
1308 ssl3CipherSpec * cwSpec;
1309 ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
1310 SSL3MACAlgorithm mac;
1311 SSL3BulkCipher cipher;
1312 SSL3KeyExchangeAlgorithm kea;
1313 const ssl3CipherSuiteDef *suite_def;
1316 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1318 ssl_GetSpecWriteLock(ss); /*******************************/
1320 pwSpec = ss->ssl3.pwSpec;
1321 PORT_Assert(pwSpec == ss->ssl3.prSpec);
1323 /* This hack provides maximal interoperability with SSL 3 servers. */
1324 cwSpec = ss->ssl3.cwSpec;
1325 if (cwSpec->mac_def->mac == mac_null) {
1326 /* SSL records are not being MACed. */
1327 cwSpec->version = ss->version;
1330 pwSpec->version = ss->version;
1331 isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0);
1333 SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1334 SSL_GETPID(), ss->fd, suite));
1336 suite_def = ssl_LookupCipherSuiteDef(suite);
1337 if (suite_def == NULL) {
1338 ssl_ReleaseSpecWriteLock(ss);
1339 return SECFailure; /* error code set by ssl_LookupCipherSuiteDef */
1343 /* Double-check that we did not pick an RC4 suite */
1344 PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) &&
1345 (suite_def->bulk_cipher_alg != cipher_rc4_40) &&
1346 (suite_def->bulk_cipher_alg != cipher_rc4_56));
1349 cipher = suite_def->bulk_cipher_alg;
1350 kea = suite_def->key_exchange_alg;
1351 mac = suite_def->mac_alg;
1352 if (mac <= ssl_mac_sha && isTLS)
1355 ss->ssl3.hs.suite_def = suite_def;
1356 ss->ssl3.hs.kea_def = &kea_defs[kea];
1357 PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
1359 pwSpec->cipher_def = &bulk_cipher_defs[cipher];
1360 PORT_Assert(pwSpec->cipher_def->cipher == cipher);
1362 pwSpec->mac_def = &mac_defs[mac];
1363 PORT_Assert(pwSpec->mac_def->mac == mac);
1365 ss->sec.keyBits = pwSpec->cipher_def->key_size * BPB;
1366 ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB;
1367 ss->sec.cipherType = cipher;
1369 pwSpec->encodeContext = NULL;
1370 pwSpec->decodeContext = NULL;
1372 pwSpec->mac_size = pwSpec->mac_def->mac_size;
1374 pwSpec->compression_method = ss->ssl3.hs.compression;
1375 pwSpec->compressContext = NULL;
1376 pwSpec->decompressContext = NULL;
1378 ssl_ReleaseSpecWriteLock(ss); /*******************************/
1382 #ifdef NSS_ENABLE_ZLIB
1383 #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream)
1386 ssl3_MapZlibError(int zlib_error)
1388 switch (zlib_error) {
1397 ssl3_DeflateInit(void *void_context)
1399 z_stream *context = void_context;
1400 context->zalloc = NULL;
1401 context->zfree = NULL;
1402 context->opaque = NULL;
1404 return ssl3_MapZlibError(deflateInit(context, Z_DEFAULT_COMPRESSION));
1408 ssl3_InflateInit(void *void_context)
1410 z_stream *context = void_context;
1411 context->zalloc = NULL;
1412 context->zfree = NULL;
1413 context->opaque = NULL;
1414 context->next_in = NULL;
1415 context->avail_in = 0;
1417 return ssl3_MapZlibError(inflateInit(context));
1421 ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len,
1422 int maxout, const unsigned char *in, int inlen)
1424 z_stream *context = void_context;
1431 context->next_in = (unsigned char*) in;
1432 context->avail_in = inlen;
1433 context->next_out = out;
1434 context->avail_out = maxout;
1435 if (deflate(context, Z_SYNC_FLUSH) != Z_OK) {
1438 if (context->avail_out == 0) {
1439 /* We ran out of space! */
1440 SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing",
1445 *out_len = maxout - context->avail_out;
1450 ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len,
1451 int maxout, const unsigned char *in, int inlen)
1453 z_stream *context = void_context;
1460 context->next_in = (unsigned char*) in;
1461 context->avail_in = inlen;
1462 context->next_out = out;
1463 context->avail_out = maxout;
1464 if (inflate(context, Z_SYNC_FLUSH) != Z_OK) {
1465 PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE);
1469 *out_len = maxout - context->avail_out;
1474 ssl3_DestroyCompressContext(void *void_context, PRBool unused)
1476 deflateEnd(void_context);
1477 PORT_Free(void_context);
1482 ssl3_DestroyDecompressContext(void *void_context, PRBool unused)
1484 inflateEnd(void_context);
1485 PORT_Free(void_context);
1489 #endif /* NSS_ENABLE_ZLIB */
1491 /* Initialize the compression functions and contexts for the given
1494 ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec)
1496 /* Setup the compression functions */
1497 switch (pwSpec->compression_method) {
1498 case ssl_compression_null:
1499 pwSpec->compressor = NULL;
1500 pwSpec->decompressor = NULL;
1501 pwSpec->compressContext = NULL;
1502 pwSpec->decompressContext = NULL;
1503 pwSpec->destroyCompressContext = NULL;
1504 pwSpec->destroyDecompressContext = NULL;
1506 #ifdef NSS_ENABLE_ZLIB
1507 case ssl_compression_deflate:
1508 pwSpec->compressor = ssl3_DeflateCompress;
1509 pwSpec->decompressor = ssl3_DeflateDecompress;
1510 pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1511 pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1512 pwSpec->destroyCompressContext = ssl3_DestroyCompressContext;
1513 pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext;
1514 ssl3_DeflateInit(pwSpec->compressContext);
1515 ssl3_InflateInit(pwSpec->decompressContext);
1517 #endif /* NSS_ENABLE_ZLIB */
1520 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1527 #ifndef NO_PKCS11_BYPASS
1528 /* Initialize encryption contexts for pending spec.
1529 * MAC contexts are set up when computing the mac, not here.
1530 * Master Secret already is derived in spec->msItem
1531 * Caller holds Spec write lock.
1534 ssl3_InitPendingContextsBypass(sslSocket *ss)
1536 ssl3CipherSpec * pwSpec;
1537 const ssl3BulkCipherDef *cipher_def;
1538 void * serverContext = NULL;
1539 void * clientContext = NULL;
1540 BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL;
1542 unsigned int optArg1 = 0;
1543 unsigned int optArg2 = 0;
1544 PRBool server_encrypts = ss->sec.isServer;
1545 SSLCipherAlgorithm calg;
1546 SSLCompressionMethod compression_method;
1549 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1550 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1551 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1553 pwSpec = ss->ssl3.pwSpec;
1554 cipher_def = pwSpec->cipher_def;
1556 calg = cipher_def->calg;
1557 compression_method = pwSpec->compression_method;
1559 serverContext = pwSpec->server.cipher_context;
1560 clientContext = pwSpec->client.cipher_context;
1564 pwSpec->encode = Null_Cipher;
1565 pwSpec->decode = Null_Cipher;
1566 pwSpec->destroy = NULL;
1570 initFn = (BLapiInitContextFunc)RC4_InitContext;
1571 pwSpec->encode = (SSLCipher) RC4_Encrypt;
1572 pwSpec->decode = (SSLCipher) RC4_Decrypt;
1573 pwSpec->destroy = (SSLDestroy) RC4_DestroyContext;
1576 initFn = (BLapiInitContextFunc)RC2_InitContext;
1578 optArg1 = cipher_def->key_size;
1579 pwSpec->encode = (SSLCipher) RC2_Encrypt;
1580 pwSpec->decode = (SSLCipher) RC2_Decrypt;
1581 pwSpec->destroy = (SSLDestroy) RC2_DestroyContext;
1584 initFn = (BLapiInitContextFunc)DES_InitContext;
1586 optArg1 = server_encrypts;
1587 pwSpec->encode = (SSLCipher) DES_Encrypt;
1588 pwSpec->decode = (SSLCipher) DES_Decrypt;
1589 pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
1592 initFn = (BLapiInitContextFunc)DES_InitContext;
1593 mode = NSS_DES_EDE3_CBC;
1594 optArg1 = server_encrypts;
1595 pwSpec->encode = (SSLCipher) DES_Encrypt;
1596 pwSpec->decode = (SSLCipher) DES_Decrypt;
1597 pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
1600 initFn = (BLapiInitContextFunc)AES_InitContext;
1602 optArg1 = server_encrypts;
1603 optArg2 = AES_BLOCK_SIZE;
1604 pwSpec->encode = (SSLCipher) AES_Encrypt;
1605 pwSpec->decode = (SSLCipher) AES_Decrypt;
1606 pwSpec->destroy = (SSLDestroy) AES_DestroyContext;
1609 case ssl_calg_camellia:
1610 initFn = (BLapiInitContextFunc)Camellia_InitContext;
1611 mode = NSS_CAMELLIA_CBC;
1612 optArg1 = server_encrypts;
1613 optArg2 = CAMELLIA_BLOCK_SIZE;
1614 pwSpec->encode = (SSLCipher) Camellia_Encrypt;
1615 pwSpec->decode = (SSLCipher) Camellia_Decrypt;
1616 pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext;
1620 initFn = (BLapiInitContextFunc)SEED_InitContext;
1621 mode = NSS_SEED_CBC;
1622 optArg1 = server_encrypts;
1623 optArg2 = SEED_BLOCK_SIZE;
1624 pwSpec->encode = (SSLCipher) SEED_Encrypt;
1625 pwSpec->decode = (SSLCipher) SEED_Decrypt;
1626 pwSpec->destroy = (SSLDestroy) SEED_DestroyContext;
1630 case ssl_calg_fortezza :
1633 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1636 rv = (*initFn)(serverContext,
1637 pwSpec->server.write_key_item.data,
1638 pwSpec->server.write_key_item.len,
1639 pwSpec->server.write_iv_item.data,
1640 mode, optArg1, optArg2);
1641 if (rv != SECSuccess) {
1643 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1651 case ssl_calg_camellia:
1653 /* For block ciphers, if the server is encrypting, then the client
1654 * is decrypting, and vice versa.
1658 /* kill warnings. */
1663 case ssl_calg_fortezza:
1667 rv = (*initFn)(clientContext,
1668 pwSpec->client.write_key_item.data,
1669 pwSpec->client.write_key_item.len,
1670 pwSpec->client.write_iv_item.data,
1671 mode, optArg1, optArg2);
1672 if (rv != SECSuccess) {
1674 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1678 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
1679 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
1681 ssl3_InitCompressionContext(pwSpec);
1691 /* This function should probably be moved to pk11wrap and be named
1692 * PK11_ParamFromIVAndEffectiveKeyBits
1695 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits)
1697 SECItem * param = PK11_ParamFromIV(mtype, iv);
1698 if (param && param->data && param->len >= sizeof(CK_RC2_PARAMS)) {
1700 case CKM_RC2_KEY_GEN:
1704 case CKM_RC2_MAC_GENERAL:
1705 case CKM_RC2_CBC_PAD:
1706 *(CK_RC2_PARAMS *)param->data = ulEffectiveBits;
1713 /* Initialize encryption and MAC contexts for pending spec.
1714 * Master Secret already is derived.
1715 * Caller holds Spec write lock.
1718 ssl3_InitPendingContextsPKCS11(sslSocket *ss)
1720 ssl3CipherSpec * pwSpec;
1721 const ssl3BulkCipherDef *cipher_def;
1722 PK11Context * serverContext = NULL;
1723 PK11Context * clientContext = NULL;
1725 CK_MECHANISM_TYPE mechanism;
1726 CK_MECHANISM_TYPE mac_mech;
1728 CK_ULONG effKeyBits;
1731 SSLCipherAlgorithm calg;
1733 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1734 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1735 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1737 pwSpec = ss->ssl3.pwSpec;
1738 cipher_def = pwSpec->cipher_def;
1739 macLength = pwSpec->mac_size;
1742 ** Now setup the MAC contexts,
1743 ** crypto contexts are setup below.
1746 pwSpec->client.write_mac_context = NULL;
1747 pwSpec->server.write_mac_context = NULL;
1748 mac_mech = pwSpec->mac_def->mmech;
1749 mac_param.data = (unsigned char *)&macLength;
1750 mac_param.len = sizeof(macLength);
1753 pwSpec->client.write_mac_context = PK11_CreateContextBySymKey(
1754 mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param);
1755 if (pwSpec->client.write_mac_context == NULL) {
1756 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1759 pwSpec->server.write_mac_context = PK11_CreateContextBySymKey(
1760 mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param);
1761 if (pwSpec->server.write_mac_context == NULL) {
1762 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1767 ** Now setup the crypto contexts.
1770 calg = cipher_def->calg;
1771 PORT_Assert(alg2Mech[calg].calg == calg);
1773 if (calg == calg_null) {
1774 pwSpec->encode = Null_Cipher;
1775 pwSpec->decode = Null_Cipher;
1776 pwSpec->destroy = NULL;
1779 mechanism = alg2Mech[calg].cmech;
1780 effKeyBits = cipher_def->key_size * BPB;
1783 * build the server context
1785 iv.data = pwSpec->server.write_iv;
1786 iv.len = cipher_def->iv_size;
1787 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
1788 if (param == NULL) {
1789 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
1792 serverContext = PK11_CreateContextBySymKey(mechanism,
1793 (ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT),
1794 pwSpec->server.write_key, param);
1795 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
1797 PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len);
1798 SECITEM_FreeItem(param, PR_TRUE);
1799 if (serverContext == NULL) {
1800 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1805 * build the client context
1807 iv.data = pwSpec->client.write_iv;
1808 iv.len = cipher_def->iv_size;
1810 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
1811 if (param == NULL) {
1812 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
1815 clientContext = PK11_CreateContextBySymKey(mechanism,
1816 (ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT),
1817 pwSpec->client.write_key, param);
1818 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
1820 PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len);
1821 SECITEM_FreeItem(param,PR_TRUE);
1822 if (clientContext == NULL) {
1823 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1826 pwSpec->encode = (SSLCipher) PK11_CipherOp;
1827 pwSpec->decode = (SSLCipher) PK11_CipherOp;
1828 pwSpec->destroy = (SSLDestroy) PK11_DestroyContext;
1830 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
1831 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
1833 serverContext = NULL;
1834 clientContext = NULL;
1836 ssl3_InitCompressionContext(pwSpec);
1841 if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE);
1842 if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE);
1843 if (pwSpec->client.write_mac_context != NULL) {
1844 PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE);
1845 pwSpec->client.write_mac_context = NULL;
1847 if (pwSpec->server.write_mac_context != NULL) {
1848 PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE);
1849 pwSpec->server.write_mac_context = NULL;
1855 /* Complete the initialization of all keys, ciphers, MACs and their contexts
1856 * for the pending Cipher Spec.
1857 * Called from: ssl3_SendClientKeyExchange (for Full handshake)
1858 * ssl3_HandleRSAClientKeyExchange (for Full handshake)
1859 * ssl3_HandleServerHello (for session restart)
1860 * ssl3_HandleClientHello (for session restart)
1861 * Sets error code, but caller probably should override to disambiguate.
1862 * NULL pms means re-use old master_secret.
1864 * This code is common to the bypass and PKCS11 execution paths.
1865 * For the bypass case, pms is NULL.
1868 ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms)
1870 ssl3CipherSpec * pwSpec;
1871 ssl3CipherSpec * cwSpec;
1874 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1876 ssl_GetSpecWriteLock(ss); /**************************************/
1878 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1880 pwSpec = ss->ssl3.pwSpec;
1881 cwSpec = ss->ssl3.cwSpec;
1883 if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) {
1884 rv = ssl3_DeriveMasterSecret(ss, pms);
1885 if (rv != SECSuccess) {
1886 goto done; /* err code set by ssl3_DeriveMasterSecret */
1889 #ifndef NO_PKCS11_BYPASS
1890 if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) {
1891 /* Double Bypass succeeded in extracting the master_secret */
1892 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
1893 PRBool isTLS = (PRBool)(kea_def->tls_keygen ||
1894 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
1895 pwSpec->bypassCiphers = PR_TRUE;
1896 rv = ssl3_KeyAndMacDeriveBypass( pwSpec,
1897 (const unsigned char *)&ss->ssl3.hs.client_random,
1898 (const unsigned char *)&ss->ssl3.hs.server_random,
1900 (PRBool)(kea_def->is_limited));
1901 if (rv == SECSuccess) {
1902 rv = ssl3_InitPendingContextsBypass(ss);
1906 if (pwSpec->master_secret) {
1907 rv = ssl3_DeriveConnectionKeysPKCS11(ss);
1908 if (rv == SECSuccess) {
1909 rv = ssl3_InitPendingContextsPKCS11(ss);
1912 PORT_Assert(pwSpec->master_secret);
1913 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1916 if (rv != SECSuccess) {
1920 /* Generic behaviors -- common to all crypto methods */
1922 pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0;
1924 if (cwSpec->epoch == PR_UINT16_MAX) {
1925 /* The problem here is that we have rehandshaked too many
1926 * times (you are not allowed to wrap the epoch). The
1927 * spec says you should be discarding the connection
1928 * and start over, so not much we can do here. */
1929 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1933 /* The sequence number has the high 16 bits as the epoch. */
1934 pwSpec->epoch = cwSpec->epoch + 1;
1935 pwSpec->read_seq_num.high = pwSpec->write_seq_num.high =
1936 pwSpec->epoch << 16;
1938 dtls_InitRecvdRecords(&pwSpec->recvdRecords);
1940 pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0;
1943 ssl_ReleaseSpecWriteLock(ss); /******************************/
1944 if (rv != SECSuccess)
1945 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
1950 * 60 bytes is 3 times the maximum length MAC size that is supported.
1952 static const unsigned char mac_pad_1 [60] = {
1953 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1954 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1955 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1956 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1957 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1958 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1959 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1960 0x36, 0x36, 0x36, 0x36
1962 static const unsigned char mac_pad_2 [60] = {
1963 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1964 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1965 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1966 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1967 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1968 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1969 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1970 0x5c, 0x5c, 0x5c, 0x5c
1973 /* Called from: ssl3_SendRecord()
1974 ** Caller must already hold the SpecReadLock. (wish we could assert that!)
1977 ssl3_ComputeRecordMAC(
1978 ssl3CipherSpec * spec,
1979 PRBool useServerMacKey,
1981 SSL3ContentType type,
1982 SSL3ProtocolVersion version,
1983 SSL3SequenceNumber seq_num,
1984 const SSL3Opaque * input,
1986 unsigned char * outbuf,
1987 unsigned int * outLength)
1989 const ssl3MACDef * mac_def;
1991 #ifndef NO_PKCS11_BYPASS
1994 unsigned int tempLen;
1995 unsigned char temp[MAX_MAC_LENGTH];
1997 temp[0] = (unsigned char)(seq_num.high >> 24);
1998 temp[1] = (unsigned char)(seq_num.high >> 16);
1999 temp[2] = (unsigned char)(seq_num.high >> 8);
2000 temp[3] = (unsigned char)(seq_num.high >> 0);
2001 temp[4] = (unsigned char)(seq_num.low >> 24);
2002 temp[5] = (unsigned char)(seq_num.low >> 16);
2003 temp[6] = (unsigned char)(seq_num.low >> 8);
2004 temp[7] = (unsigned char)(seq_num.low >> 0);
2007 /* TLS MAC includes the record's version field, SSL's doesn't.
2008 ** We decide which MAC defintiion to use based on the version of
2009 ** the protocol that was negotiated when the spec became current,
2010 ** NOT based on the version value in the record itself.
2011 ** But, we use the record'v version value in the computation.
2013 if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
2014 temp[9] = MSB(inputLength);
2015 temp[10] = LSB(inputLength);
2017 #ifndef NO_PKCS11_BYPASS
2021 /* New TLS hash includes version. */
2023 SSL3ProtocolVersion dtls_version;
2025 dtls_version = dtls_TLSVersionToDTLSVersion(version);
2026 temp[9] = MSB(dtls_version);
2027 temp[10] = LSB(dtls_version);
2029 temp[9] = MSB(version);
2030 temp[10] = LSB(version);
2032 temp[11] = MSB(inputLength);
2033 temp[12] = LSB(inputLength);
2035 #ifndef NO_PKCS11_BYPASS
2040 PRINT_BUF(95, (NULL, "frag hash1: temp", temp, tempLen));
2041 PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength));
2043 mac_def = spec->mac_def;
2044 if (mac_def->mac == mac_null) {
2048 #ifndef NO_PKCS11_BYPASS
2049 if (spec->bypassCiphers) {
2050 /* bypass version */
2051 const SECHashObject *hashObj = NULL;
2052 unsigned int pad_bytes = 0;
2053 PRUint64 write_mac_context[MAX_MAC_CONTEXT_LLONGS];
2055 switch (mac_def->mac) {
2061 hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
2065 hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
2067 case ssl_hmac_md5: /* used with TLS */
2068 hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
2070 case ssl_hmac_sha: /* used with TLS */
2071 hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
2073 case ssl_hmac_sha256: /* used with TLS */
2074 hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
2081 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2086 /* compute "inner" part of SSL3 MAC */
2087 hashObj->begin(write_mac_context);
2088 if (useServerMacKey)
2089 hashObj->update(write_mac_context,
2090 spec->server.write_mac_key_item.data,
2091 spec->server.write_mac_key_item.len);
2093 hashObj->update(write_mac_context,
2094 spec->client.write_mac_key_item.data,
2095 spec->client.write_mac_key_item.len);
2096 hashObj->update(write_mac_context, mac_pad_1, pad_bytes);
2097 hashObj->update(write_mac_context, temp, tempLen);
2098 hashObj->update(write_mac_context, input, inputLength);
2099 hashObj->end(write_mac_context, temp, &tempLen, sizeof temp);
2101 /* compute "outer" part of SSL3 MAC */
2102 hashObj->begin(write_mac_context);
2103 if (useServerMacKey)
2104 hashObj->update(write_mac_context,
2105 spec->server.write_mac_key_item.data,
2106 spec->server.write_mac_key_item.len);
2108 hashObj->update(write_mac_context,
2109 spec->client.write_mac_key_item.data,
2110 spec->client.write_mac_key_item.len);
2111 hashObj->update(write_mac_context, mac_pad_2, pad_bytes);
2112 hashObj->update(write_mac_context, temp, tempLen);
2113 hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size);
2115 } else { /* is TLS */
2116 #define cx ((HMACContext *)write_mac_context)
2117 if (useServerMacKey) {
2118 rv = HMAC_Init(cx, hashObj,
2119 spec->server.write_mac_key_item.data,
2120 spec->server.write_mac_key_item.len, PR_FALSE);
2122 rv = HMAC_Init(cx, hashObj,
2123 spec->client.write_mac_key_item.data,
2124 spec->client.write_mac_key_item.len, PR_FALSE);
2126 if (rv == SECSuccess) {
2128 HMAC_Update(cx, temp, tempLen);
2129 HMAC_Update(cx, input, inputLength);
2130 rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size);
2131 HMAC_Destroy(cx, PR_FALSE);
2138 PK11Context *mac_context =
2139 (useServerMacKey ? spec->server.write_mac_context
2140 : spec->client.write_mac_context);
2141 rv = PK11_DigestBegin(mac_context);
2142 rv |= PK11_DigestOp(mac_context, temp, tempLen);
2143 rv |= PK11_DigestOp(mac_context, input, inputLength);
2144 rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size);
2147 PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size);
2149 PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength));
2151 if (rv != SECSuccess) {
2153 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2158 /* Called from: ssl3_HandleRecord()
2159 * Caller must already hold the SpecReadLock. (wish we could assert that!)
2162 * originalLen >= inputLen >= MAC size
2165 ssl3_ComputeRecordMACConstantTime(
2166 ssl3CipherSpec * spec,
2167 PRBool useServerMacKey,
2169 SSL3ContentType type,
2170 SSL3ProtocolVersion version,
2171 SSL3SequenceNumber seq_num,
2172 const SSL3Opaque * input,
2175 unsigned char * outbuf,
2176 unsigned int * outLen)
2178 CK_MECHANISM_TYPE macType;
2179 CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
2180 SECItem param, inputItem, outputItem;
2182 unsigned char header[13];
2186 PORT_Assert(inputLen >= spec->mac_size);
2187 PORT_Assert(originalLen >= inputLen);
2189 if (spec->bypassCiphers) {
2190 /* This function doesn't support PKCS#11 bypass. We fallback on the
2191 * non-constant time version. */
2195 if (spec->mac_def->mac == mac_null) {
2200 header[0] = (unsigned char)(seq_num.high >> 24);
2201 header[1] = (unsigned char)(seq_num.high >> 16);
2202 header[2] = (unsigned char)(seq_num.high >> 8);
2203 header[3] = (unsigned char)(seq_num.high >> 0);
2204 header[4] = (unsigned char)(seq_num.low >> 24);
2205 header[5] = (unsigned char)(seq_num.low >> 16);
2206 header[6] = (unsigned char)(seq_num.low >> 8);
2207 header[7] = (unsigned char)(seq_num.low >> 0);
2210 macType = CKM_NSS_HMAC_CONSTANT_TIME;
2211 recordLength = inputLen - spec->mac_size;
2212 if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
2213 macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME;
2214 header[9] = recordLength >> 8;
2215 header[10] = recordLength;
2216 params.ulHeaderLen = 11;
2219 SSL3ProtocolVersion dtls_version;
2221 dtls_version = dtls_TLSVersionToDTLSVersion(version);
2222 header[9] = dtls_version >> 8;
2223 header[10] = dtls_version;
2225 header[9] = version >> 8;
2226 header[10] = version;
2228 header[11] = recordLength >> 8;
2229 header[12] = recordLength;
2230 params.ulHeaderLen = 13;
2233 params.macAlg = spec->mac_def->mmech;
2234 params.ulBodyTotalLen = originalLen;
2235 params.pHeader = header;
2237 param.data = (unsigned char*) ¶ms;
2238 param.len = sizeof(params);
2241 inputItem.data = (unsigned char *) input;
2242 inputItem.len = inputLen;
2245 outputItem.data = outbuf;
2246 outputItem.len = *outLen;
2247 outputItem.type = 0;
2249 key = spec->server.write_mac_key;
2250 if (!useServerMacKey) {
2251 key = spec->client.write_mac_key;
2254 rv = PK11_SignWithSymKey(key, macType, ¶m, &outputItem, &inputItem);
2255 if (rv != SECSuccess) {
2256 if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) {
2262 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2266 PORT_Assert(outputItem.len == (unsigned)spec->mac_size);
2267 *outLen = outputItem.len;
2272 /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the
2273 * length already. */
2274 inputLen -= spec->mac_size;
2275 return ssl3_ComputeRecordMAC(spec, useServerMacKey, isDTLS, type,
2276 version, seq_num, input, inputLen,
2281 ssl3_ClientAuthTokenPresent(sslSessionID *sid) {
2282 PK11SlotInfo *slot = NULL;
2283 PRBool isPresent = PR_TRUE;
2285 /* we only care if we are doing client auth */
2286 if (!sid || !sid->u.ssl3.clAuthValid) {
2291 slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
2292 sid->u.ssl3.clAuthSlotID);
2294 !PK11_IsPresent(slot) ||
2295 sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) ||
2296 sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) ||
2297 sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) ||
2298 (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
2299 isPresent = PR_FALSE;
2302 PK11_FreeSlot(slot);
2307 /* Caller must hold the spec read lock. */
2309 ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec,
2312 PRBool capRecordVersion,
2313 SSL3ContentType type,
2314 const SSL3Opaque * pIn,
2315 PRUint32 contentLen,
2318 const ssl3BulkCipherDef * cipher_def;
2320 PRUint32 macLen = 0;
2322 PRUint32 p1Len, p2Len, oddLen = 0;
2325 int cipherBytes = 0;
2327 cipher_def = cwSpec->cipher_def;
2328 headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH;
2330 if (cipher_def->type == type_block &&
2331 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
2332 /* Prepend the per-record explicit IV using technique 2b from
2333 * RFC 4346 section 6.2.3.2: The IV is a cryptographically
2334 * strong random number XORed with the CBC residue from the previous
2337 ivLen = cipher_def->iv_size;
2338 if (ivLen > wrBuf->space - headerLen) {
2339 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2342 rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen);
2343 if (rv != SECSuccess) {
2344 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
2347 rv = cwSpec->encode( cwSpec->encodeContext,
2348 wrBuf->buf + headerLen,
2349 &cipherBytes, /* output and actual outLen */
2350 ivLen, /* max outlen */
2351 wrBuf->buf + headerLen,
2352 ivLen); /* input and inputLen*/
2353 if (rv != SECSuccess || cipherBytes != ivLen) {
2354 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2359 if (cwSpec->compressor) {
2361 rv = cwSpec->compressor(
2362 cwSpec->compressContext,
2363 wrBuf->buf + headerLen + ivLen, &outlen,
2364 wrBuf->space - headerLen - ivLen, pIn, contentLen);
2365 if (rv != SECSuccess)
2367 pIn = wrBuf->buf + headerLen + ivLen;
2368 contentLen = outlen;
2374 rv = ssl3_ComputeRecordMAC( cwSpec, isServer, isDTLS,
2375 type, cwSpec->version, cwSpec->write_seq_num, pIn, contentLen,
2376 wrBuf->buf + headerLen + ivLen + contentLen, &macLen);
2377 if (rv != SECSuccess) {
2378 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2383 fragLen = contentLen + macLen; /* needs to be encrypted */
2384 PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
2387 * Pad the text (if we're doing a block cipher)
2390 if (cipher_def->type == type_block) {
2391 unsigned char * pBuf;
2395 oddLen = contentLen % cipher_def->block_size;
2396 /* Assume blockSize is a power of two */
2397 padding_length = cipher_def->block_size - 1 -
2398 ((fragLen) & (cipher_def->block_size - 1));
2399 fragLen += padding_length + 1;
2400 PORT_Assert((fragLen % cipher_def->block_size) == 0);
2402 /* Pad according to TLS rules (also acceptable to SSL3). */
2403 pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1];
2404 for (i = padding_length + 1; i > 0; --i) {
2405 *pBuf-- = padding_length;
2407 /* now, if contentLen is not a multiple of block size, fix it */
2408 p2Len = fragLen - p1Len;
2418 PORT_Assert( (cipher_def->block_size < 2) || \
2419 (p2Len % cipher_def->block_size) == 0);
2420 memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, oddLen);
2423 int cipherBytesPart1 = -1;
2424 rv = cwSpec->encode( cwSpec->encodeContext,
2425 wrBuf->buf + headerLen + ivLen, /* output */
2426 &cipherBytesPart1, /* actual outlen */
2427 p1Len, /* max outlen */
2428 pIn, p1Len); /* input, and inputlen */
2429 PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len);
2430 if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) {
2431 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2434 cipherBytes += cipherBytesPart1;
2437 int cipherBytesPart2 = -1;
2438 rv = cwSpec->encode( cwSpec->encodeContext,
2439 wrBuf->buf + headerLen + ivLen + p1Len,
2440 &cipherBytesPart2, /* output and actual outLen */
2441 p2Len, /* max outlen */
2442 wrBuf->buf + headerLen + ivLen + p1Len,
2443 p2Len); /* input and inputLen*/
2444 PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len);
2445 if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) {
2446 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2449 cipherBytes += cipherBytesPart2;
2451 PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024);
2453 wrBuf->len = cipherBytes + headerLen;
2454 wrBuf->buf[0] = type;
2456 SSL3ProtocolVersion version;
2458 version = dtls_TLSVersionToDTLSVersion(cwSpec->version);
2459 wrBuf->buf[1] = MSB(version);
2460 wrBuf->buf[2] = LSB(version);
2461 wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24);
2462 wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16);
2463 wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >> 8);
2464 wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >> 0);
2465 wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low >> 24);
2466 wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low >> 16);
2467 wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low >> 8);
2468 wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >> 0);
2469 wrBuf->buf[11] = MSB(cipherBytes);
2470 wrBuf->buf[12] = LSB(cipherBytes);
2472 SSL3ProtocolVersion version = cwSpec->version;
2474 if (capRecordVersion) {
2475 version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version);
2477 wrBuf->buf[1] = MSB(version);
2478 wrBuf->buf[2] = LSB(version);
2479 wrBuf->buf[3] = MSB(cipherBytes);
2480 wrBuf->buf[4] = LSB(cipherBytes);
2483 ssl3_BumpSequenceNumber(&cwSpec->write_seq_num);
2488 /* Process the plain text before sending it.
2489 * Returns the number of bytes of plaintext that were successfully sent
2490 * plus the number of bytes of plaintext that were copied into the
2491 * output (write) buffer.
2492 * Returns SECFailure on a hard IO error, memory error, or crypto error.
2493 * Does NOT return SECWouldBlock.
2495 * Notes on the use of the private ssl flags:
2496 * (no private SSL flags)
2497 * Attempt to make and send SSL records for all plaintext
2498 * If non-blocking and a send gets WOULD_BLOCK,
2499 * or if the pending (ciphertext) buffer is not empty,
2500 * then buffer remaining bytes of ciphertext into pending buf,
2501 * and continue to do that for all succssive records until all
2503 * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2504 * As above, except this suppresses all write attempts, and forces
2505 * all ciphertext into the pending ciphertext buffer.
2506 * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
2507 * Forces the use of the provided epoch
2508 * ssl_SEND_FLAG_CAP_RECORD_VERSION
2509 * Caps the record layer version number of TLS ClientHello to { 3, 1 }
2510 * (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore
2511 * ClientHello.client_version and use the record layer version number
2512 * (TLSPlaintext.version) instead when negotiating protocol versions. In
2513 * addition, if the record layer version number of ClientHello is { 3, 2 }
2514 * (TLS 1.1) or higher, these servers reset the TCP connections. Set this
2515 * flag to work around such servers.
2518 ssl3_SendRecord( sslSocket * ss,
2519 DTLSEpoch epoch, /* DTLS only */
2520 SSL3ContentType type,
2521 const SSL3Opaque * pIn, /* input buffer */
2522 PRInt32 nIn, /* bytes of input */
2525 sslBuffer * wrBuf = &ss->sec.writeBuf;
2527 PRInt32 totalSent = 0;
2528 PRBool capRecordVersion;
2530 SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
2531 SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type),
2533 PRINT_BUF(3, (ss, "Send record (plain text)", pIn, nIn));
2535 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2537 capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0);
2539 if (capRecordVersion) {
2540 /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the
2541 * TLS initial ClientHello. */
2542 PORT_Assert(!IS_DTLS(ss));
2543 PORT_Assert(!ss->firstHsDone);
2544 PORT_Assert(type == content_handshake);
2545 PORT_Assert(ss->ssl3.hs.ws == wait_server_hello);
2548 if (ss->ssl3.initialized == PR_FALSE) {
2549 /* This can happen on a server if the very first incoming record
2550 ** looks like a defective ssl3 record (e.g. too long), and we're
2551 ** trying to send an alert.
2553 PR_ASSERT(type == content_alert);
2554 rv = ssl3_InitState(ss);
2555 if (rv != SECSuccess) {
2556 return SECFailure; /* ssl3_InitState has set the error code. */
2560 /* check for Token Presence */
2561 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
2562 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
2567 PRUint32 contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH);
2568 unsigned int spaceNeeded;
2569 unsigned int numRecords;
2571 ssl_GetSpecReadLock(ss); /********************************/
2573 if (nIn > 1 && ss->opt.cbcRandomIV &&
2574 ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
2575 type == content_application_data &&
2576 ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) {
2577 /* We will split the first byte of the record into its own record,
2578 * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h
2585 spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE);
2586 if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
2587 ss->ssl3.cwSpec->cipher_def->type == type_block) {
2588 spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size;
2590 if (spaceNeeded > wrBuf->space) {
2591 rv = sslBuffer_Grow(wrBuf, spaceNeeded);
2592 if (rv != SECSuccess) {
2593 SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes",
2594 SSL_GETPID(), ss->fd, spaceNeeded));
2595 goto spec_locked_loser; /* sslBuffer_Grow set error code. */
2599 if (numRecords == 2) {
2600 sslBuffer secondRecord;
2602 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2603 ss->sec.isServer, IS_DTLS(ss),
2604 capRecordVersion, type, pIn,
2606 if (rv != SECSuccess)
2607 goto spec_locked_loser;
2609 PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:",
2610 wrBuf->buf, wrBuf->len));
2612 secondRecord.buf = wrBuf->buf + wrBuf->len;
2613 secondRecord.len = 0;
2614 secondRecord.space = wrBuf->space - wrBuf->len;
2616 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2617 ss->sec.isServer, IS_DTLS(ss),
2618 capRecordVersion, type,
2619 pIn + 1, contentLen - 1,
2621 if (rv == SECSuccess) {
2622 PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:",
2623 secondRecord.buf, secondRecord.len));
2624 wrBuf->len += secondRecord.len;
2628 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
2635 rv = dtls_CompressMACEncryptRecord(ss, epoch,
2636 !!(flags & ssl_SEND_FLAG_USE_EPOCH),
2641 if (rv == SECSuccess) {
2642 PRINT_BUF(50, (ss, "send (encrypted) record data:",
2643 wrBuf->buf, wrBuf->len));
2648 ssl_ReleaseSpecReadLock(ss); /************************************/
2650 if (rv != SECSuccess)
2655 PORT_Assert( nIn >= 0 );
2657 /* If there's still some previously saved ciphertext,
2658 * or the caller doesn't want us to send the data yet,
2659 * then add all our new ciphertext to the amount previously saved.
2661 if ((ss->pendingBuf.len > 0) ||
2662 (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2664 rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len);
2665 if (rv != SECSuccess) {
2666 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2669 wrBuf->len = 0; /* All cipher text is saved away. */
2671 if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2673 ss->handshakeBegun = 1;
2674 sent = ssl_SendSavedWriteData(ss);
2675 if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2676 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2679 if (ss->pendingBuf.len) {
2680 flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2683 } else if (wrBuf->len > 0) {
2685 ss->handshakeBegun = 1;
2686 sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len,
2687 flags & ~ssl_SEND_FLAG_MASK);
2689 if (PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2690 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2693 /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
2699 /* DTLS just says no in this case. No buffering */
2700 PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
2703 /* now take all the remaining unsent new ciphertext and
2704 * append it to the buffer of previously unsent ciphertext.
2706 rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len);
2707 if (rv != SECSuccess) {
2708 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2713 totalSent += contentLen;
2718 #define SSL3_PENDING_HIGH_WATER 1024
2720 /* Attempt to send the content of "in" in an SSL application_data record.
2721 * Returns "len" or SECFailure, never SECWouldBlock, nor SECSuccess.
2724 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
2725 PRInt32 len, PRInt32 flags)
2727 PRInt32 totalSent = 0;
2728 PRInt32 discarded = 0;
2730 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2731 /* These flags for internal use only */
2732 PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH |
2733 ssl_SEND_FLAG_NO_RETRANSMIT)));
2734 if (len < 0 || !in) {
2735 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2739 if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
2740 !ssl_SocketIsBlocking(ss)) {
2741 PORT_Assert(!ssl_SocketIsBlocking(ss));
2742 PORT_SetError(PR_WOULD_BLOCK_ERROR);
2746 if (ss->appDataBuffered && len) {
2747 PORT_Assert (in[0] == (unsigned char)(ss->appDataBuffered));
2748 if (in[0] != (unsigned char)(ss->appDataBuffered)) {
2749 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2756 while (len > totalSent) {
2757 PRInt32 sent, toSend;
2759 if (totalSent > 0) {
2761 * The thread yield is intended to give the reader thread a
2762 * chance to get some cycles while the writer thread is in
2763 * the middle of a large application data write. (See
2764 * Bugzilla bug 127740, comment #1.)
2766 ssl_ReleaseXmitBufLock(ss);
2767 PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */
2768 ssl_GetXmitBufLock(ss);
2770 toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
2772 * Note that the 0 epoch is OK because flags will never require
2773 * its use, as guaranteed by the PORT_Assert above.
2775 sent = ssl3_SendRecord(ss, 0, content_application_data,
2776 in + totalSent, toSend, flags);
2778 if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
2779 PORT_Assert(ss->lastWriteBlocked);
2782 return SECFailure; /* error code set by ssl3_SendRecord */
2785 if (ss->pendingBuf.len) {
2786 /* must be a non-blocking socket */
2787 PORT_Assert(!ssl_SocketIsBlocking(ss));
2788 PORT_Assert(ss->lastWriteBlocked);
2792 if (ss->pendingBuf.len) {
2793 /* Must be non-blocking. */
2794 PORT_Assert(!ssl_SocketIsBlocking(ss));
2795 if (totalSent > 0) {
2796 ss->appDataBuffered = 0x100 | in[totalSent - 1];
2799 totalSent = totalSent + discarded - 1;
2800 if (totalSent <= 0) {
2801 PORT_SetError(PR_WOULD_BLOCK_ERROR);
2802 totalSent = SECFailure;
2806 ss->appDataBuffered = 0;
2807 return totalSent + discarded;
2810 /* Attempt to send buffered handshake messages.
2811 * This function returns SECSuccess or SECFailure, never SECWouldBlock.
2812 * Always set sendBuf.len to 0, even when returning SECFailure.
2814 * Depending on whether we are doing DTLS or not, this either calls
2816 * - ssl3_FlushHandshakeMessages if non-DTLS
2817 * - dtls_FlushHandshakeMessages if DTLS
2819 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
2820 * ssl3_AppendHandshake(), ssl3_SendClientHello(),
2821 * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
2822 * ssl3_SendFinished(),
2825 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
2828 return dtls_FlushHandshakeMessages(ss, flags);
2830 return ssl3_FlushHandshakeMessages(ss, flags);
2834 /* Attempt to send the content of sendBuf buffer in an SSL handshake record.
2835 * This function returns SECSuccess or SECFailure, never SECWouldBlock.
2836 * Always set sendBuf.len to 0, even when returning SECFailure.
2838 * Called from ssl3_FlushHandshake
2841 ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
2843 static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER |
2844 ssl_SEND_FLAG_CAP_RECORD_VERSION;
2845 PRInt32 rv = SECSuccess;
2847 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2848 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
2850 if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
2853 /* only these flags are allowed */
2854 PORT_Assert(!(flags & ~allowedFlags));
2855 if ((flags & ~allowedFlags) != 0) {
2856 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2859 rv = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf,
2860 ss->sec.ci.sendBuf.len, flags);
2863 int err = PORT_GetError();
2864 PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
2865 if (err == PR_WOULD_BLOCK_ERROR) {
2866 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2868 } else if (rv < ss->sec.ci.sendBuf.len) {
2869 /* short write should never happen */
2870 PORT_Assert(rv >= ss->sec.ci.sendBuf.len);
2871 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2877 /* Whether we succeeded or failed, toss the old handshake data. */
2878 ss->sec.ci.sendBuf.len = 0;
2883 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
2884 * the remote client sends a negative response to our certificate request.
2885 * Returns SECFailure if the application has required client auth.
2886 * SECSuccess otherwise.
2889 ssl3_HandleNoCertificate(sslSocket *ss)
2891 if (ss->sec.peerCert != NULL) {
2892 if (ss->sec.peerKey != NULL) {
2893 SECKEY_DestroyPublicKey(ss->sec.peerKey);
2894 ss->sec.peerKey = NULL;
2896 CERT_DestroyCertificate(ss->sec.peerCert);
2897 ss->sec.peerCert = NULL;
2899 ssl3_CleanupPeerCerts(ss);
2901 /* If the server has required client-auth blindly but doesn't
2902 * actually look at the certificate it won't know that no
2903 * certificate was presented so we shutdown the socket to ensure
2904 * an error. We only do this if we haven't already completed the
2905 * first handshake because if we're redoing the handshake we
2906 * know the server is paying attention to the certificate.
2908 if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
2909 (!ss->firstHsDone &&
2910 (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
2913 if (ss->sec.uncache)
2914 ss->sec.uncache(ss->sec.ci.sid);
2915 SSL3_SendAlert(ss, alert_fatal, bad_certificate);
2917 lower = ss->fd->lower;
2919 lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
2921 lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
2923 PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
2929 /************************************************************************
2934 ** Acquires both handshake and XmitBuf locks.
2935 ** Called from: ssl3_IllegalParameter <-
2936 ** ssl3_HandshakeFailure <-
2937 ** ssl3_HandleAlert <- ssl3_HandleRecord.
2938 ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
2939 ** ssl3_ConsumeHandshakeVariable <-
2940 ** ssl3_HandleHelloRequest <-
2941 ** ssl3_HandleServerHello <-
2942 ** ssl3_HandleServerKeyExchange <-
2943 ** ssl3_HandleCertificateRequest <-
2944 ** ssl3_HandleServerHelloDone <-
2945 ** ssl3_HandleClientHello <-
2946 ** ssl3_HandleV2ClientHello <-
2947 ** ssl3_HandleCertificateVerify <-
2948 ** ssl3_HandleClientKeyExchange <-
2949 ** ssl3_HandleCertificate <-
2950 ** ssl3_HandleFinished <-
2951 ** ssl3_HandleHandshakeMessage <-
2952 ** ssl3_HandleRecord <-
2956 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
2961 SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
2962 SSL_GETPID(), ss->fd, level, desc));
2967 ssl_GetSSL3HandshakeLock(ss);
2968 if (level == alert_fatal) {
2969 if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) {
2970 ss->sec.uncache(ss->sec.ci.sid);
2973 ssl_GetXmitBufLock(ss);
2974 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
2975 if (rv == SECSuccess) {
2977 sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2,
2978 desc == no_certificate
2979 ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
2980 rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
2982 ssl_ReleaseXmitBufLock(ss);
2983 ssl_ReleaseSSL3HandshakeLock(ss);
2984 return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
2988 * Send illegal_parameter alert. Set generic error number.
2991 ssl3_IllegalParameter(sslSocket *ss)
2995 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
2996 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
2997 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2998 : SSL_ERROR_BAD_SERVER );
3003 * Send handshake_Failure alert. Set generic error number.
3006 ssl3_HandshakeFailure(sslSocket *ss)
3008 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
3009 PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3010 : SSL_ERROR_BAD_SERVER );
3015 ssl3_SendAlertForCertError(sslSocket * ss, PRErrorCode errCode)
3017 SSL3AlertDescription desc = bad_certificate;
3018 PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
3021 case SEC_ERROR_LIBRARY_FAILURE: desc = unsupported_certificate; break;
3022 case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired; break;
3023 case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked; break;
3024 case SEC_ERROR_INADEQUATE_KEY_USAGE:
3025 case SEC_ERROR_INADEQUATE_CERT_TYPE:
3026 desc = certificate_unknown; break;
3027 case SEC_ERROR_UNTRUSTED_CERT:
3028 desc = isTLS ? access_denied : certificate_unknown; break;
3029 case SEC_ERROR_UNKNOWN_ISSUER:
3030 case SEC_ERROR_UNTRUSTED_ISSUER:
3031 desc = isTLS ? unknown_ca : certificate_unknown; break;
3032 case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
3033 desc = isTLS ? unknown_ca : certificate_expired; break;
3035 case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
3036 case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
3037 case SEC_ERROR_CA_CERT_INVALID:
3038 case SEC_ERROR_BAD_SIGNATURE:
3039 default: desc = bad_certificate; break;
3041 SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
3042 SSL_GETPID(), ss->fd, errCode));
3044 (void) SSL3_SendAlert(ss, alert_fatal, desc);
3049 * Send decode_error alert. Set generic error number.
3052 ssl3_DecodeError(sslSocket *ss)
3054 (void)SSL3_SendAlert(ss, alert_fatal,
3055 ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error
3056 : illegal_parameter);
3057 PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3058 : SSL_ERROR_BAD_SERVER );
3062 /* Called from ssl3_HandleRecord.
3063 ** Caller must hold both RecvBuf and Handshake locks.
3066 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
3068 SSL3AlertLevel level;
3069 SSL3AlertDescription desc;
3072 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3073 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3075 SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
3077 if (buf->len != 2) {
3078 (void)ssl3_DecodeError(ss);
3079 PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
3082 level = (SSL3AlertLevel)buf->buf[0];
3083 desc = (SSL3AlertDescription)buf->buf[1];
3085 SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
3086 SSL_GETPID(), ss->fd, level, desc));
3089 case close_notify: ss->recvdCloseNotify = 1;
3090 error = SSL_ERROR_CLOSE_NOTIFY_ALERT; break;
3091 case unexpected_message: error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
3093 case bad_record_mac: error = SSL_ERROR_BAD_MAC_ALERT; break;
3094 case decryption_failed_RESERVED:
3095 error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
3097 case record_overflow: error = SSL_ERROR_RECORD_OVERFLOW_ALERT; break;
3098 case decompression_failure: error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
3100 case handshake_failure: error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
3102 case no_certificate: error = SSL_ERROR_NO_CERTIFICATE; break;
3103 case bad_certificate: error = SSL_ERROR_BAD_CERT_ALERT; break;
3104 case unsupported_certificate:error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;break;
3105 case certificate_revoked: error = SSL_ERROR_REVOKED_CERT_ALERT; break;
3106 case certificate_expired: error = SSL_ERROR_EXPIRED_CERT_ALERT; break;
3107 case certificate_unknown: error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
3109 case illegal_parameter: error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;break;
3111 /* All alerts below are TLS only. */
3112 case unknown_ca: error = SSL_ERROR_UNKNOWN_CA_ALERT; break;
3113 case access_denied: error = SSL_ERROR_ACCESS_DENIED_ALERT; break;
3114 case decode_error: error = SSL_ERROR_DECODE_ERROR_ALERT; break;
3115 case decrypt_error: error = SSL_ERROR_DECRYPT_ERROR_ALERT; break;
3116 case export_restriction: error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
3118 case protocol_version: error = SSL_ERROR_PROTOCOL_VERSION_ALERT; break;
3119 case insufficient_security: error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
3121 case internal_error: error = SSL_ERROR_INTERNAL_ERROR_ALERT; break;
3122 case user_canceled: error = SSL_ERROR_USER_CANCELED_ALERT; break;
3123 case no_renegotiation: error = SSL_ERROR_NO_RENEGOTIATION_ALERT; break;
3125 /* Alerts for TLS client hello extensions */
3126 case unsupported_extension:
3127 error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT; break;
3128 case certificate_unobtainable:
3129 error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; break;
3130 case unrecognized_name:
3131 error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; break;
3132 case bad_certificate_status_response:
3133 error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; break;
3134 case bad_certificate_hash_value:
3135 error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT; break;
3136 default: error = SSL_ERROR_RX_UNKNOWN_ALERT; break;
3138 if (level == alert_fatal) {
3139 if (!ss->opt.noCache) {
3140 if (ss->sec.uncache)
3141 ss->sec.uncache(ss->sec.ci.sid);
3143 if ((ss->ssl3.hs.ws == wait_server_hello) &&
3144 (desc == handshake_failure)) {
3145 /* XXX This is a hack. We're assuming that any handshake failure
3146 * XXX on the client hello is a failure to match ciphers.
3148 error = SSL_ERROR_NO_CYPHER_OVERLAP;
3150 PORT_SetError(error);
3153 if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
3154 /* I'm a server. I've requested a client cert. He hasn't got one. */
3157 PORT_Assert(ss->sec.isServer);
3158 ss->ssl3.hs.ws = wait_client_key;
3159 rv = ssl3_HandleNoCertificate(ss);
3166 * Change Cipher Specs
3167 * Called from ssl3_HandleServerHelloDone,
3168 * ssl3_HandleClientHello,
3169 * and ssl3_HandleFinished
3171 * Acquires and releases spec write lock, to protect switching the current
3172 * and pending write spec pointers.
3176 ssl3_SendChangeCipherSpecs(sslSocket *ss)
3178 PRUint8 change = change_cipher_spec_choice;
3179 ssl3CipherSpec * pwSpec;
3183 SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
3184 SSL_GETPID(), ss->fd));
3186 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
3187 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3189 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3190 if (rv != SECSuccess) {
3191 return rv; /* error code set by ssl3_FlushHandshake */
3194 sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1,
3195 ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3197 return (SECStatus)sent; /* error code set by ssl3_SendRecord */
3200 rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1);
3201 if (rv != SECSuccess) {
3206 /* swap the pending and current write specs. */
3207 ssl_GetSpecWriteLock(ss); /**************************************/
3208 pwSpec = ss->ssl3.pwSpec;
3210 ss->ssl3.pwSpec = ss->ssl3.cwSpec;
3211 ss->ssl3.cwSpec = pwSpec;
3213 SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
3214 SSL_GETPID(), ss->fd ));
3216 /* We need to free up the contexts, keys and certs ! */
3217 /* If we are really through with the old cipher spec
3218 * (Both the read and write sides have changed) destroy it.
3220 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
3222 ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE/*freeSrvName*/);
3224 /* With DTLS, we need to set a holddown timer in case the final
3225 * message got lost */
3226 ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS;
3227 dtls_StartTimer(ss, dtls_FinishedTimerCb);
3230 ssl_ReleaseSpecWriteLock(ss); /**************************************/
3235 /* Called from ssl3_HandleRecord.
3236 ** Caller must hold both RecvBuf and Handshake locks.
3238 * Acquires and releases spec write lock, to protect switching the current
3239 * and pending write spec pointers.
3242 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
3244 ssl3CipherSpec * prSpec;
3245 SSL3WaitState ws = ss->ssl3.hs.ws;
3246 SSL3ChangeCipherSpecChoice change;
3248 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3249 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3251 SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
3252 SSL_GETPID(), ss->fd));
3254 if (ws != wait_change_cipher) {
3255 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3256 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3261 (void)ssl3_DecodeError(ss);
3262 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3265 change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
3266 if (change != change_cipher_spec_choice) {
3267 /* illegal_parameter is correct here for both SSL3 and TLS. */
3268 (void)ssl3_IllegalParameter(ss);
3269 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3274 /* Swap the pending and current read specs. */
3275 ssl_GetSpecWriteLock(ss); /*************************************/
3276 prSpec = ss->ssl3.prSpec;
3278 ss->ssl3.prSpec = ss->ssl3.crSpec;
3279 ss->ssl3.crSpec = prSpec;
3280 ss->ssl3.hs.ws = wait_finished;
3282 SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
3283 SSL_GETPID(), ss->fd ));
3285 /* If we are really through with the old cipher prSpec
3286 * (Both the read and write sides have changed) destroy it.
3288 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
3289 ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/);
3291 ssl_ReleaseSpecWriteLock(ss); /*************************************/
3295 /* This method uses PKCS11 to derive the MS from the PMS, where PMS
3296 ** is a PKCS11 symkey. This is used in all cases except the
3297 ** "triple bypass" with RSA key exchange.
3298 ** Called from ssl3_InitPendingCipherSpec. prSpec is pwSpec.
3301 ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms)
3303 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec;
3304 const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def;
3305 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random;
3306 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random;
3307 PRBool isTLS = (PRBool)(kea_def->tls_keygen ||
3308 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
3310 (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3312 * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
3313 * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
3314 * data into a 48-byte value.
3316 PRBool isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) ||
3317 (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh));
3318 SECStatus rv = SECFailure;
3319 CK_MECHANISM_TYPE master_derive;
3320 CK_MECHANISM_TYPE key_derive;
3323 CK_VERSION pms_version;
3324 CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params;
3326 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3327 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3328 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
3330 if(isDH) master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256;
3331 else master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256;
3332 key_derive = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256;
3333 keyFlags = CKF_SIGN | CKF_VERIFY;
3335 if(isDH) master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
3336 else master_derive = CKM_TLS_MASTER_KEY_DERIVE;
3337 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3338 keyFlags = CKF_SIGN | CKF_VERIFY;
3340 if (isDH) master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
3341 else master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
3342 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3346 if (pms || !pwSpec->master_secret) {
3348 master_params.pVersion = NULL;
3350 master_params.pVersion = &pms_version;
3352 master_params.RandomInfo.pClientRandom = cr;
3353 master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3354 master_params.RandomInfo.pServerRandom = sr;
3355 master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3357 params.data = (unsigned char *) &master_params;
3358 params.len = sizeof master_params;
3363 if (ssl_trace >= 100) {
3364 SECStatus extractRV = PK11_ExtractKeyValue(pms);
3365 if (extractRV == SECSuccess) {
3366 SECItem * keyData = PK11_GetKeyData(pms);
3367 if (keyData && keyData->data && keyData->len) {
3368 ssl_PrintBuf(ss, "Pre-Master Secret",
3369 keyData->data, keyData->len);
3374 pwSpec->master_secret = PK11_DeriveWithFlags(pms, master_derive,
3375 ¶ms, key_derive, CKA_DERIVE, 0, keyFlags);
3376 if (!isDH && pwSpec->master_secret && ss->opt.detectRollBack) {
3377 SSL3ProtocolVersion client_version;
3378 client_version = pms_version.major << 8 | pms_version.minor;
3381 client_version = dtls_DTLSVersionToTLSVersion(client_version);
3384 if (client_version != ss->clientHelloVersion) {
3385 /* Destroy it. Version roll-back detected. */
3386 PK11_FreeSymKey(pwSpec->master_secret);
3387 pwSpec->master_secret = NULL;
3390 if (pwSpec->master_secret == NULL) {
3391 /* Generate a faux master secret in the same slot as the old one. */
3392 PK11SlotInfo * slot = PK11_GetSlotFromKey((PK11SymKey *)pms);
3393 PK11SymKey * fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
3395 PK11_FreeSlot(slot);
3397 pwSpec->master_secret = PK11_DeriveWithFlags(fpms,
3398 master_derive, ¶ms, key_derive,
3399 CKA_DERIVE, 0, keyFlags);
3400 PK11_FreeSymKey(fpms);
3404 if (pwSpec->master_secret == NULL) {
3405 /* Generate a faux master secret from the internal slot. */
3406 PK11SlotInfo * slot = PK11_GetInternalSlot();
3407 PK11SymKey * fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
3409 PK11_FreeSlot(slot);
3411 pwSpec->master_secret = PK11_DeriveWithFlags(fpms,
3412 master_derive, ¶ms, key_derive,
3413 CKA_DERIVE, 0, keyFlags);
3414 if (pwSpec->master_secret == NULL) {
3415 pwSpec->master_secret = fpms; /* use the fpms as the master. */
3420 PK11_FreeSymKey(fpms);
3423 if (pwSpec->master_secret == NULL) {
3424 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3427 #ifndef NO_PKCS11_BYPASS
3428 if (ss->opt.bypassPKCS11) {
3430 /* In hope of doing a "double bypass",
3431 * need to extract the master secret's value from the key object
3432 * and store it raw in the sslSocket struct.
3434 rv = PK11_ExtractKeyValue(pwSpec->master_secret);
3435 if (rv != SECSuccess) {
3438 /* This returns the address of the secItem inside the key struct,
3439 * not a copy or a reference. So, there's no need to free it.
3441 keydata = PK11_GetKeyData(pwSpec->master_secret);
3442 if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) {
3443 memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len);
3444 pwSpec->msItem.data = pwSpec->raw_master_secret;
3445 pwSpec->msItem.len = keydata->len;
3447 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3457 * Derive encryption and MAC Keys (and IVs) from master secret
3458 * Sets a useful error code when returning SECFailure.
3460 * Called only from ssl3_InitPendingCipherSpec(),
3461 * which in turn is called from
3462 * sendRSAClientKeyExchange (for Full handshake)
3463 * sendDHClientKeyExchange (for Full handshake)
3464 * ssl3_HandleClientKeyExchange (for Full handshake)
3465 * ssl3_HandleServerHello (for session restart)
3466 * ssl3_HandleClientHello (for session restart)
3467 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
3468 * ssl3_InitPendingCipherSpec does that.
3472 ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss)
3474 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec;
3475 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
3476 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random;
3477 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random;
3478 PRBool isTLS = (PRBool)(kea_def->tls_keygen ||
3479 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
3481 (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3482 /* following variables used in PKCS11 path */
3483 const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def;
3484 PK11SlotInfo * slot = NULL;
3485 PK11SymKey * symKey = NULL;
3486 void * pwArg = ss->pkcs11PinArg;
3488 CK_SSL3_KEY_MAT_PARAMS key_material_params;
3489 CK_SSL3_KEY_MAT_OUT returnedKeys;
3490 CK_MECHANISM_TYPE key_derive;
3491 CK_MECHANISM_TYPE bulk_mechanism;
3492 SSLCipherAlgorithm calg;
3494 PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null);
3496 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3497 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3498 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
3500 if (!pwSpec->master_secret) {
3501 PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3505 * generate the key material
3507 key_material_params.ulMacSizeInBits = pwSpec->mac_size * BPB;
3508 key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB;
3509 key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB;
3510 if (cipher_def->type == type_block &&
3511 pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
3512 /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
3513 key_material_params.ulIVSizeInBits = 0;
3514 memset(pwSpec->client.write_iv, 0, cipher_def->iv_size);
3515 memset(pwSpec->server.write_iv, 0, cipher_def->iv_size);
3518 key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited);
3519 /* was: (CK_BBOOL)(cipher_def->keygen_mode != kg_strong); */
3521 key_material_params.RandomInfo.pClientRandom = cr;
3522 key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3523 key_material_params.RandomInfo.pServerRandom = sr;
3524 key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3525 key_material_params.pReturnedKeyMaterial = &returnedKeys;
3527 returnedKeys.pIVClient = pwSpec->client.write_iv;
3528 returnedKeys.pIVServer = pwSpec->server.write_iv;
3529 keySize = cipher_def->key_size;
3531 if (skipKeysAndIVs) {
3533 key_material_params.ulKeySizeInBits = 0;
3534 key_material_params.ulIVSizeInBits = 0;
3535 returnedKeys.pIVClient = NULL;
3536 returnedKeys.pIVServer = NULL;
3539 calg = cipher_def->calg;
3540 PORT_Assert( alg2Mech[calg].calg == calg);
3541 bulk_mechanism = alg2Mech[calg].cmech;
3543 params.data = (unsigned char *)&key_material_params;
3544 params.len = sizeof(key_material_params);
3547 key_derive = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256;
3549 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3551 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3554 /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
3555 * DERIVE by DEFAULT */
3556 symKey = PK11_Derive(pwSpec->master_secret, key_derive, ¶ms,
3557 bulk_mechanism, CKA_ENCRYPT, keySize);
3559 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3562 /* we really should use the actual mac'ing mechanism here, but we
3563 * don't because these types are used to map keytype anyway and both
3564 * mac's map to the same keytype.
3566 slot = PK11_GetSlotFromKey(symKey);
3568 PK11_FreeSlot(slot); /* slot is held until the key is freed */
3569 pwSpec->client.write_mac_key =
3570 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3571 CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg);
3572 if (pwSpec->client.write_mac_key == NULL ) {
3573 goto loser; /* loser sets err */
3575 pwSpec->server.write_mac_key =
3576 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3577 CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg);
3578 if (pwSpec->server.write_mac_key == NULL ) {
3579 goto loser; /* loser sets err */
3581 if (!skipKeysAndIVs) {
3582 pwSpec->client.write_key =
3583 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3584 bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg);
3585 if (pwSpec->client.write_key == NULL ) {
3586 goto loser; /* loser sets err */
3588 pwSpec->server.write_key =
3589 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
3590 bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg);
3591 if (pwSpec->server.write_key == NULL ) {
3592 goto loser; /* loser sets err */
3595 PK11_FreeSymKey(symKey);
3600 if (symKey) PK11_FreeSymKey(symKey);
3601 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3605 /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
3606 * buffered messages in ss->ssl3.hs.messages. */
3608 ssl3_InitHandshakeHashes(sslSocket *ss)
3610 SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
3612 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
3613 #ifndef NO_PKCS11_BYPASS
3614 if (ss->opt.bypassPKCS11) {
3615 PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone);
3616 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
3617 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
3618 * then this will need to be updated. */
3619 ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256);
3620 if (!ss->ssl3.hs.sha_obj) {
3621 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3624 ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone;
3625 ss->ssl3.hs.hashType = handshake_hash_single;
3626 ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx);
3628 ss->ssl3.hs.hashType = handshake_hash_combo;
3629 MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx);
3630 SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx);
3635 PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha);
3637 * note: We should probably lookup an SSL3 slot for these
3638 * handshake hashes in hopes that we wind up with the same slots
3639 * that the master secret will wind up in ...
3641 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
3642 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
3643 * then this will need to be updated. */
3644 ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256);
3645 if (ss->ssl3.hs.sha == NULL) {
3646 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3649 ss->ssl3.hs.hashType = handshake_hash_single;
3651 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3652 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3656 /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
3657 * created successfully. */
3658 ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
3659 if (ss->ssl3.hs.md5 == NULL) {
3660 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3663 ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
3664 if (ss->ssl3.hs.sha == NULL) {
3665 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
3666 ss->ssl3.hs.md5 = NULL;
3667 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3670 ss->ssl3.hs.hashType = handshake_hash_combo;
3672 if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
3673 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3676 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3677 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3683 if (ss->ssl3.hs.messages.len > 0) {
3684 if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
3685 ss->ssl3.hs.messages.len) !=
3689 PORT_Free(ss->ssl3.hs.messages.buf);
3690 ss->ssl3.hs.messages.buf = NULL;
3691 ss->ssl3.hs.messages.len = 0;
3692 ss->ssl3.hs.messages.space = 0;
3699 ssl3_RestartHandshakeHashes(sslSocket *ss)
3701 SECStatus rv = SECSuccess;
3703 SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
3704 SSL_GETPID(), ss->fd ));
3705 ss->ssl3.hs.hashType = handshake_hash_unknown;
3706 ss->ssl3.hs.messages.len = 0;
3707 #ifndef NO_PKCS11_BYPASS
3708 ss->ssl3.hs.sha_obj = NULL;
3709 ss->ssl3.hs.sha_clone = NULL;
3711 if (ss->ssl3.hs.md5) {
3712 PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
3713 ss->ssl3.hs.md5 = NULL;
3715 if (ss->ssl3.hs.sha) {
3716 PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
3717 ss->ssl3.hs.sha = NULL;
3723 * Handshake messages
3725 /* Called from ssl3_InitHandshakeHashes()
3726 ** ssl3_AppendHandshake()
3727 ** ssl3_StartHandshakeHash()
3728 ** ssl3_HandleV2ClientHello()
3729 ** ssl3_HandleHandshakeMessage()
3730 ** Caller must hold the ssl3Handshake lock.
3733 ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b,
3736 SECStatus rv = SECSuccess;
3738 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3740 /* We need to buffer the handshake messages until we have established
3741 * which handshake hash function to use. */
3742 if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
3743 return sslBuffer_Append(&ss->ssl3.hs.messages, b, l);
3746 PRINT_BUF(90, (NULL, "handshake hash input:", b, l));
3748 #ifndef NO_PKCS11_BYPASS
3749 if (ss->opt.bypassPKCS11) {
3750 if (ss->ssl3.hs.hashType == handshake_hash_single) {
3751 ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l);
3753 MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l);
3754 SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l);
3759 if (ss->ssl3.hs.hashType == handshake_hash_single) {
3760 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
3761 if (rv != SECSuccess) {
3762 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3766 rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
3767 if (rv != SECSuccess) {
3768 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3771 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
3772 if (rv != SECSuccess) {
3773 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3780 /**************************************************************************
3781 * Append Handshake functions.
3782 * All these functions set appropriate error codes.
3783 * Most rely on ssl3_AppendHandshake to set the error code.
3784 **************************************************************************/
3786 ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes)
3788 unsigned char * src = (unsigned char *)void_src;
3789 int room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
3792 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); /* protects sendBuf. */
3796 if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) {
3797 rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH,
3798 PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes)));
3799 if (rv != SECSuccess)
3800 return rv; /* sslBuffer_Grow has set a memory error code. */
3801 room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
3804 PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char*)void_src, bytes));
3805 rv = ssl3_UpdateHandshakeHashes(ss, src, bytes);
3806 if (rv != SECSuccess)
3807 return rv; /* error code set by ssl3_UpdateHandshakeHashes */
3809 while (bytes > room) {
3811 PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src,
3813 ss->sec.ci.sendBuf.len += room;
3814 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3815 if (rv != SECSuccess) {
3816 return rv; /* error code set by ssl3_FlushHandshake */
3820 room = ss->sec.ci.sendBuf.space;
3821 PORT_Assert(ss->sec.ci.sendBuf.len == 0);
3823 PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes);
3824 ss->sec.ci.sendBuf.len += bytes;
3829 ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize)
3837 *p++ = (num >> 24) & 0xff;
3839 *p++ = (num >> 16) & 0xff;
3841 *p++ = (num >> 8) & 0xff;
3845 SSL_TRC(60, ("%d: number:", SSL_GETPID()));
3846 rv = ssl3_AppendHandshake(ss, &b[0], lenSize);
3847 return rv; /* error code set by AppendHandshake, if applicable. */
3851 ssl3_AppendHandshakeVariable(
3852 sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize)
3856 PORT_Assert((bytes < (1<<8) && lenSize == 1) ||
3857 (bytes < (1L<<16) && lenSize == 2) ||
3858 (bytes < (1L<<24) && lenSize == 3));
3860 SSL_TRC(60,("%d: append variable:", SSL_GETPID()));
3861 rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize);
3862 if (rv != SECSuccess) {
3863 return rv; /* error code set by AppendHandshake, if applicable. */
3865 SSL_TRC(60, ("data:"));
3866 rv = ssl3_AppendHandshake(ss, src, bytes);
3867 return rv; /* error code set by AppendHandshake, if applicable. */
3871 ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length)
3875 /* If we already have a message in place, we need to enqueue it.
3876 * This empties the buffer. This is a convenient place to call
3877 * dtls_StageHandshakeMessage to mark the message boundary.
3880 rv = dtls_StageHandshakeMessage(ss);
3881 if (rv != SECSuccess) {
3886 SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s",
3887 SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
3889 rv = ssl3_AppendHandshakeNumber(ss, t, 1);
3890 if (rv != SECSuccess) {
3891 return rv; /* error code set by AppendHandshake, if applicable. */
3893 rv = ssl3_AppendHandshakeNumber(ss, length, 3);
3894 if (rv != SECSuccess) {
3895 return rv; /* error code set by AppendHandshake, if applicable. */
3899 /* Note that we make an unfragmented message here. We fragment in the
3900 * transmission code, if necessary */
3901 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2);
3902 if (rv != SECSuccess) {
3903 return rv; /* error code set by AppendHandshake, if applicable. */
3905 ss->ssl3.hs.sendMessageSeq++;
3907 /* 0 is the fragment offset, because it's not fragmented yet */
3908 rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
3909 if (rv != SECSuccess) {
3910 return rv; /* error code set by AppendHandshake, if applicable. */
3913 /* Fragment length -- set to the packet length because not fragmented */
3914 rv = ssl3_AppendHandshakeNumber(ss, length, 3);
3915 if (rv != SECSuccess) {
3916 return rv; /* error code set by AppendHandshake, if applicable. */
3920 return rv; /* error code set by AppendHandshake, if applicable. */
3923 /* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of
3924 * |sigAndHash| to the current handshake message. */
3926 ssl3_AppendSignatureAndHashAlgorithm(
3927 sslSocket *ss, const SSL3SignatureAndHashAlgorithm* sigAndHash)
3929 unsigned char serialized[2];
3931 serialized[0] = ssl3_OIDToTLSHashAlgorithm(sigAndHash->hashAlg);
3932 if (serialized[0] == 0) {
3933 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
3937 serialized[1] = sigAndHash->sigAlg;
3939 return ssl3_AppendHandshake(ss, serialized, sizeof(serialized));
3942 /**************************************************************************
3943 * Consume Handshake functions.
3945 * All data used in these functions is protected by two locks,
3946 * the RecvBufLock and the SSL3HandshakeLock
3947 **************************************************************************/
3949 /* Read up the next "bytes" number of bytes from the (decrypted) input
3950 * stream "b" (which is *length bytes long). Copy them into buffer "v".
3951 * Reduces *length by bytes. Advances *b by bytes.
3953 * If this function returns SECFailure, it has already sent an alert,
3954 * and has set a generic error code. The caller should probably
3955 * override the generic error code by setting another.
3958 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b,
3961 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3962 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3964 if ((PRUint32)bytes > *length) {
3965 return ssl3_DecodeError(ss);
3967 PORT_Memcpy(v, *b, bytes);
3968 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
3974 /* Read up the next "bytes" number of bytes from the (decrypted) input
3975 * stream "b" (which is *length bytes long), and interpret them as an
3976 * integer in network byte order. Returns the received value.
3977 * Reduces *length by bytes. Advances *b by bytes.
3979 * Returns SECFailure (-1) on failure.
3980 * This value is indistinguishable from the equivalent received value.
3981 * Only positive numbers are to be received this way.
3982 * Thus, the largest value that may be sent this way is 0x7fffffff.
3983 * On error, an alert has been sent, and a generic error code has been set.
3986 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b,
3993 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
3994 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
3995 PORT_Assert( bytes <= sizeof num);
3997 if ((PRUint32)bytes > *length) {
3998 return ssl3_DecodeError(ss);
4000 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4002 for (i = 0; i < bytes; i++)
4003 num = (num << 8) + buf[i];
4009 /* Read in two values from the incoming decrypted byte stream "b", which is
4010 * *length bytes long. The first value is a number whose size is "bytes"
4011 * bytes long. The second value is a byte-string whose size is the value
4012 * of the first number received. The latter byte-string, and its length,
4013 * is returned in the SECItem i.
4015 * Returns SECFailure (-1) on failure.
4016 * On error, an alert has been sent, and a generic error code has been set.
4018 * RADICAL CHANGE for NSS 3.11. All callers of this function make copies
4019 * of the data returned in the SECItem *i, so making a copy of it here
4020 * is simply wasteful. So, This function now just sets SECItem *i to
4021 * point to the values in the buffer **b.
4024 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes,
4025 SSL3Opaque **b, PRUint32 *length)
4029 PORT_Assert(bytes <= 3);
4032 count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length);
4033 if (count < 0) { /* Can't test for SECSuccess here. */
4037 if ((PRUint32)count > *length) {
4038 return ssl3_DecodeError(ss);
4048 /* tlsHashOIDMap contains the mapping between TLS hash identifiers and the
4049 * SECOidTag used internally by NSS. */
4050 static const struct {
4053 } tlsHashOIDMap[] = {
4054 { tls_hash_md5, SEC_OID_MD5 },
4055 { tls_hash_sha1, SEC_OID_SHA1 },
4056 { tls_hash_sha224, SEC_OID_SHA224 },
4057 { tls_hash_sha256, SEC_OID_SHA256 },
4058 { tls_hash_sha384, SEC_OID_SHA384 },
4059 { tls_hash_sha512, SEC_OID_SHA512 }
4062 /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
4063 * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
4065 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4067 ssl3_TLSHashAlgorithmToOID(int hashFunc)
4071 for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) {
4072 if (hashFunc == tlsHashOIDMap[i].tlsHash) {
4073 return tlsHashOIDMap[i].oid;
4076 return SEC_OID_UNKNOWN;
4079 /* ssl3_OIDToTLSHashAlgorithm converts an OID to a TLS hash algorithm
4080 * identifier. If the hash is not recognised, zero is returned.
4082 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4084 ssl3_OIDToTLSHashAlgorithm(SECOidTag oid)
4088 for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) {
4089 if (oid == tlsHashOIDMap[i].oid) {
4090 return tlsHashOIDMap[i].tlsHash;
4096 /* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm
4097 * identifier for a given KeyType. */
4099 ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType,
4100 TLSSignatureAlgorithm *out)
4110 *out = tls_sig_ecdsa;
4113 PORT_SetError(SEC_ERROR_INVALID_KEY);
4118 /* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature
4119 * algorithm identifier for the given certificate. */
4121 ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert,
4122 TLSSignatureAlgorithm *out)
4124 SECKEYPublicKey *key;
4127 key = CERT_ExtractPublicKey(cert);
4129 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
4133 keyType = key->keyType;
4134 SECKEY_DestroyPublicKey(key);
4135 return ssl3_TLSSignatureAlgorithmForKeyType(keyType, out);
4138 /* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature
4139 * algorithm identifier in |sigAndHash| is consistent with the public key in
4140 * |cert|. If so, SECSuccess is returned. Otherwise, PORT_SetError is called
4141 * and SECFailure is returned. */
4143 ssl3_CheckSignatureAndHashAlgorithmConsistency(
4144 const SSL3SignatureAndHashAlgorithm *sigAndHash, CERTCertificate* cert)
4147 TLSSignatureAlgorithm sigAlg;
4149 rv = ssl3_TLSSignatureAlgorithmForCertificate(cert, &sigAlg);
4150 if (rv != SECSuccess) {
4153 if (sigAlg != sigAndHash->sigAlg) {
4154 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4160 /* ssl3_ConsumeSignatureAndHashAlgorithm reads a SignatureAndHashAlgorithm
4161 * structure from |b| and puts the resulting value into |out|. |b| and |length|
4162 * are updated accordingly.
4164 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4166 ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss,
4169 SSL3SignatureAndHashAlgorithm *out)
4171 unsigned char bytes[2];
4174 rv = ssl3_ConsumeHandshake(ss, bytes, sizeof(bytes), b, length);
4175 if (rv != SECSuccess) {
4179 out->hashAlg = ssl3_TLSHashAlgorithmToOID(bytes[0]);
4180 if (out->hashAlg == SEC_OID_UNKNOWN) {
4181 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
4185 out->sigAlg = bytes[1];
4189 /**************************************************************************
4190 * end of Consume Handshake functions.
4191 **************************************************************************/
4193 /* Extract the hashes of handshake messages to this point.
4194 * Called from ssl3_SendCertificateVerify
4196 * ssl3_HandleHandshakeMessage
4198 * Caller must hold the SSL3HandshakeLock.
4199 * Caller must hold a read or write lock on the Spec R/W lock.
4200 * (There is presently no way to assert on a Read lock.)
4203 ssl3_ComputeHandshakeHashes(sslSocket * ss,
4204 ssl3CipherSpec *spec, /* uses ->master_secret */
4205 SSL3Hashes * hashes, /* output goes here. */
4208 SECStatus rv = SECSuccess;
4209 PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
4210 unsigned int outLength;
4211 SSL3Opaque md5_inner[MAX_MAC_LENGTH];
4212 SSL3Opaque sha_inner[MAX_MAC_LENGTH];
4214 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4215 hashes->hashAlg = SEC_OID_UNKNOWN;
4217 #ifndef NO_PKCS11_BYPASS
4218 if (ss->opt.bypassPKCS11 &&
4219 ss->ssl3.hs.hashType == handshake_hash_single) {
4220 /* compute them without PKCS11 */
4221 PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS];
4223 if (!spec->msItem.data) {
4224 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4228 ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx);
4229 ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len,
4230 sizeof(hashes->u.raw));
4232 PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len));
4234 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4235 * then this will need to be updated. */
4236 hashes->hashAlg = SEC_OID_SHA256;
4238 } else if (ss->opt.bypassPKCS11) {
4239 /* compute them without PKCS11 */
4240 PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS];
4241 PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS];
4243 #define md5cx ((MD5Context *)md5_cx)
4244 #define shacx ((SHA1Context *)sha_cx)
4246 if (!spec->msItem.data) {
4247 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4251 MD5_Clone (md5cx, (MD5Context *)ss->ssl3.hs.md5_cx);
4252 SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx);
4255 /* compute hashes for SSL3. */
4258 s[0] = (unsigned char)(sender >> 24);
4259 s[1] = (unsigned char)(sender >> 16);
4260 s[2] = (unsigned char)(sender >> 8);
4261 s[3] = (unsigned char)sender;
4264 MD5_Update(md5cx, s, 4);
4265 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
4268 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
4269 mac_defs[mac_md5].pad_size));
4271 MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
4272 MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size);
4273 MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH);
4275 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
4278 SHA1_Update(shacx, s, 4);
4279 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
4282 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
4283 mac_defs[mac_sha].pad_size));
4285 SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
4286 SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size);
4287 SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH);
4289 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
4290 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
4291 mac_defs[mac_md5].pad_size));
4292 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
4295 MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
4296 MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size);
4297 MD5_Update(md5cx, md5_inner, MD5_LENGTH);
4299 MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH);
4301 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
4304 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
4305 mac_defs[mac_sha].pad_size));
4306 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
4309 SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
4310 SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size);
4311 SHA1_Update(shacx, sha_inner, SHA1_LENGTH);
4313 SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH);
4315 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
4317 hashes->len = MD5_LENGTH + SHA1_LENGTH;
4323 if (ss->ssl3.hs.hashType == handshake_hash_single) {
4324 /* compute hashes with PKCS11 */
4326 unsigned int stateLen;
4327 unsigned char stackBuf[1024];
4328 unsigned char *stateBuf = NULL;
4330 if (!spec->master_secret) {
4331 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4335 h = ss->ssl3.hs.sha;
4336 stateBuf = PK11_SaveContextAlloc(h, stackBuf,
4337 sizeof(stackBuf), &stateLen);
4338 if (stateBuf == NULL) {
4339 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4342 rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
4343 sizeof(hashes->u.raw));
4344 if (rv != SECSuccess) {
4345 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4349 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4350 * then this will need to be updated. */
4351 hashes->hashAlg = SEC_OID_SHA256;
4356 if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
4357 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4360 if (stateBuf != stackBuf) {
4361 PORT_ZFree(stateBuf, stateLen);
4365 /* compute hashes with PKCS11 */
4367 PK11Context * sha = NULL;
4368 unsigned char *md5StateBuf = NULL;
4369 unsigned char *shaStateBuf = NULL;
4370 unsigned int md5StateLen, shaStateLen;
4371 unsigned char md5StackBuf[256];
4372 unsigned char shaStackBuf[512];
4374 if (!spec->master_secret) {
4375 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4379 md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
4380 sizeof md5StackBuf, &md5StateLen);
4381 if (md5StateBuf == NULL) {
4382 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4385 md5 = ss->ssl3.hs.md5;
4387 shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
4388 sizeof shaStackBuf, &shaStateLen);
4389 if (shaStateBuf == NULL) {
4390 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4393 sha = ss->ssl3.hs.sha;
4396 /* compute hashes for SSL3. */
4399 s[0] = (unsigned char)(sender >> 24);
4400 s[1] = (unsigned char)(sender >> 16);
4401 s[2] = (unsigned char)(sender >> 8);
4402 s[3] = (unsigned char)sender;
4405 rv |= PK11_DigestOp(md5, s, 4);
4406 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
4409 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
4410 mac_defs[mac_md5].pad_size));
4412 rv |= PK11_DigestKey(md5,spec->master_secret);
4413 rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size);
4414 rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
4415 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4416 if (rv != SECSuccess) {
4417 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4422 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
4425 rv |= PK11_DigestOp(sha, s, 4);
4426 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
4429 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
4430 mac_defs[mac_sha].pad_size));
4432 rv |= PK11_DigestKey(sha, spec->master_secret);
4433 rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size);
4434 rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
4435 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4436 if (rv != SECSuccess) {
4437 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4442 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
4444 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
4445 mac_defs[mac_md5].pad_size));
4446 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
4448 rv |= PK11_DigestBegin(md5);
4449 rv |= PK11_DigestKey(md5, spec->master_secret);
4450 rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size);
4451 rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
4453 rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH);
4454 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4455 if (rv != SECSuccess) {
4456 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4461 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
4464 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
4465 mac_defs[mac_sha].pad_size));
4466 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
4468 rv |= PK11_DigestBegin(sha);
4469 rv |= PK11_DigestKey(sha,spec->master_secret);
4470 rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size);
4471 rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
4473 rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH);
4474 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4475 if (rv != SECSuccess) {
4476 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4481 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
4483 hashes->len = MD5_LENGTH + SHA1_LENGTH;
4488 if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen)
4491 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4494 if (md5StateBuf != md5StackBuf) {
4495 PORT_ZFree(md5StateBuf, md5StateLen);
4499 if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen)
4502 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4505 if (shaStateBuf != shaStackBuf) {
4506 PORT_ZFree(shaStateBuf, shaStateLen);
4514 * SSL 2 based implementations pass in the initial outbound buffer
4515 * so that the handshake hash can contain the included information.
4517 * Called from ssl2_BeginClientHandshake() in sslcon.c
4520 ssl3_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length)
4524 ssl_GetSSL3HandshakeLock(ss); /**************************************/
4526 rv = ssl3_InitState(ss);
4527 if (rv != SECSuccess) {
4528 goto done; /* ssl3_InitState has set the error code. */
4530 rv = ssl3_RestartHandshakeHashes(ss);
4531 if (rv != SECSuccess) {
4535 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
4537 &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES],
4538 &ss->sec.ci.clientChallenge,
4539 SSL_CHALLENGE_BYTES);
4541 rv = ssl3_UpdateHandshakeHashes(ss, buf, length);
4542 /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */
4545 ssl_ReleaseSSL3HandshakeLock(ss); /**************************************/
4549 /**************************************************************************
4550 * end of Handshake Hash functions.
4551 * Begin Send and Handle functions for handshakes.
4552 **************************************************************************/
4554 /* Called from ssl3_HandleHelloRequest(),
4555 * ssl3_RedoHandshake()
4556 * ssl2_BeginClientHandshake (when resuming ssl3 session)
4557 * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
4560 ssl3_SendClientHello(sslSocket *ss, PRBool resending)
4563 ssl3CipherSpec * cwSpec;
4568 int actual_count = 0;
4569 PRBool isTLS = PR_FALSE;
4570 PRBool requestingResume = PR_FALSE;
4571 PRInt32 total_exten_len = 0;
4572 unsigned numCompressionMethods;
4575 SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(),
4578 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4579 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
4581 rv = ssl3_InitState(ss);
4582 if (rv != SECSuccess) {
4583 return rv; /* ssl3_InitState has set the error code. */
4585 ss->ssl3.hs.sendingSCSV = PR_FALSE; /* Must be reset every handshake */
4586 PORT_Assert(IS_DTLS(ss) || !resending);
4588 /* We might be starting a session renegotiation in which case we should
4589 * clear previous state.
4591 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
4593 rv = ssl3_RestartHandshakeHashes(ss);
4594 if (rv != SECSuccess) {
4599 * During a renegotiation, ss->clientHelloVersion will be used again to
4600 * work around a Windows SChannel bug. Ensure that it is still enabled.
4602 if (ss->firstHsDone) {
4603 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
4604 PORT_SetError(SSL_ERROR_SSL_DISABLED);
4608 if (ss->clientHelloVersion < ss->vrange.min ||
4609 ss->clientHelloVersion > ss->vrange.max) {
4610 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
4615 /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
4616 * handles expired entries and other details.
4617 * XXX If we've been called from ssl2_BeginClientHandshake, then
4618 * this lookup is duplicative and wasteful.
4620 sid = (ss->opt.noCache) ? NULL
4621 : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url);
4623 /* We can't resume based on a different token. If the sid exists,
4624 * make sure the token that holds the master secret still exists ...
4625 * If we previously did client-auth, make sure that the token that holds
4626 * the private key still exists, is logged in, hasn't been removed, etc.
4629 PRBool sidOK = PR_TRUE;
4630 if (sid->u.ssl3.keys.msIsWrapped) {
4631 /* Session key was wrapped, which means it was using PKCS11, */
4632 PK11SlotInfo *slot = NULL;
4633 if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) {
4634 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
4635 sid->u.ssl3.masterSlotID);
4640 PK11SymKey *wrapKey = NULL;
4641 if (!PK11_IsPresent(slot) ||
4642 ((wrapKey = PK11_GetWrapKey(slot,
4643 sid->u.ssl3.masterWrapIndex,
4644 sid->u.ssl3.masterWrapMech,
4645 sid->u.ssl3.masterWrapSeries,
4646 ss->pkcs11PinArg)) == NULL) ) {
4649 if (wrapKey) PK11_FreeSymKey(wrapKey);
4650 PK11_FreeSlot(slot);
4654 /* If we previously did client-auth, make sure that the token that
4655 ** holds the private key still exists, is logged in, hasn't been
4658 if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
4662 /* TLS 1.0 (RFC 2246) Appendix E says:
4663 * Whenever a client already knows the highest protocol known to
4664 * a server (for example, when resuming a session), it should
4665 * initiate the connection in that native protocol.
4666 * So we pass sid->version to ssl3_NegotiateVersion() here, except
4667 * when renegotiating.
4669 * Windows SChannel compares the client_version inside the RSA
4670 * EncryptedPreMasterSecret of a renegotiation with the
4671 * client_version of the initial ClientHello rather than the
4672 * ClientHello in the renegotiation. To work around this bug, we
4673 * continue to use the client_version used in the initial
4674 * ClientHello when renegotiating.
4677 if (ss->firstHsDone) {
4679 * The client_version of the initial ClientHello is still
4680 * available in ss->clientHelloVersion. Ensure that
4681 * sid->version is bounded within
4682 * [ss->vrange.min, ss->clientHelloVersion], otherwise we
4685 if (sid->version >= ss->vrange.min &&
4686 sid->version <= ss->clientHelloVersion) {
4687 ss->version = ss->clientHelloVersion;
4692 if (ssl3_NegotiateVersion(ss, sid->version,
4693 PR_FALSE) != SECSuccess) {
4700 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok );
4701 if (ss->sec.uncache)
4702 (*ss->sec.uncache)(sid);
4709 requestingResume = PR_TRUE;
4710 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits );
4712 /* Are we attempting a stateless session resume? */
4713 if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
4714 sid->u.ssl3.sessionTicket.ticket.data)
4715 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_stateless_resumes );
4717 PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
4718 sid->u.ssl3.sessionIDLength));
4720 ss->ssl3.policy = sid->u.ssl3.policy;
4722 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_misses );
4725 * Windows SChannel compares the client_version inside the RSA
4726 * EncryptedPreMasterSecret of a renegotiation with the
4727 * client_version of the initial ClientHello rather than the
4728 * ClientHello in the renegotiation. To work around this bug, we
4729 * continue to use the client_version used in the initial
4730 * ClientHello when renegotiating.
4732 if (ss->firstHsDone) {
4733 ss->version = ss->clientHelloVersion;
4735 rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED,
4737 if (rv != SECSuccess)
4738 return rv; /* error code was set */
4741 sid = ssl3_NewSessionID(ss, PR_FALSE);
4743 return SECFailure; /* memory error is set */
4747 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
4748 ssl_GetSpecWriteLock(ss);
4749 cwSpec = ss->ssl3.cwSpec;
4750 if (cwSpec->mac_def->mac == mac_null) {
4751 /* SSL records are not being MACed. */
4752 cwSpec->version = ss->version;
4754 ssl_ReleaseSpecWriteLock(ss);
4756 if (ss->sec.ci.sid != NULL) {
4757 ssl_FreeSID(ss->sec.ci.sid); /* decrement ref count, free if zero */
4759 ss->sec.ci.sid = sid;
4761 ss->sec.send = ssl3_SendApplicationData;
4763 /* shouldn't get here if SSL3 is disabled, but ... */
4764 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
4765 PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
4766 PORT_SetError(SSL_ERROR_SSL_DISABLED);
4770 /* how many suites does our PKCS11 support (regardless of policy)? */
4771 num_suites = ssl3_config_match_init(ss);
4773 return SECFailure; /* ssl3_config_match_init has set error code. */
4775 /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV,
4776 * only if we're willing to complete an SSL 3.0 handshake.
4778 if (!ss->firstHsDone && ss->vrange.min == SSL_LIBRARY_VERSION_3_0) {
4779 /* Must set this before calling Hello Extension Senders,
4780 * to suppress sending of empty RI extension.
4782 ss->ssl3.hs.sendingSCSV = PR_TRUE;
4785 if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
4786 PRUint32 maxBytes = 65535; /* 2^16 - 1 */
4789 extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL);
4794 total_exten_len += extLen;
4796 if (total_exten_len > 0)
4797 total_exten_len += 2;
4800 #if defined(NSS_ENABLE_ECC)
4801 if (!total_exten_len || !isTLS) {
4802 /* not sending the elliptic_curves and ec_point_formats extensions */
4803 ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */
4808 ssl3_DisableNonDTLSSuites(ss);
4811 /* how many suites are permitted by policy and user preference? */
4812 num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE);
4814 return SECFailure; /* count_cipher_suites has set error code. */
4815 if (ss->ssl3.hs.sendingSCSV) {
4816 ++num_suites; /* make room for SCSV */
4819 /* count compression methods */
4820 numCompressionMethods = 0;
4821 for (i = 0; i < compressionMethodsCount; i++) {
4822 if (compressionEnabled(ss, compressions[i]))
4823 numCompressionMethods++;
4826 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH +
4827 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) +
4828 2 + num_suites*sizeof(ssl3CipherSuite) +
4829 1 + numCompressionMethods + total_exten_len;
4831 length += 1 + ss->ssl3.hs.cookieLen;
4834 rv = ssl3_AppendHandshakeHeader(ss, client_hello, length);
4835 if (rv != SECSuccess) {
4836 return rv; /* err set by ssl3_AppendHandshake* */
4839 if (ss->firstHsDone) {
4840 /* The client hello version must stay unchanged to work around
4841 * the Windows SChannel bug described above. */
4842 PORT_Assert(ss->version == ss->clientHelloVersion);
4844 ss->clientHelloVersion = ss->version;
4848 version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
4849 rv = ssl3_AppendHandshakeNumber(ss, version, 2);
4851 rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2);
4853 if (rv != SECSuccess) {
4854 return rv; /* err set by ssl3_AppendHandshake* */
4857 if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */
4858 rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random);
4859 if (rv != SECSuccess) {
4860 return rv; /* err set by GetNewRandom. */
4863 rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random,
4864 SSL3_RANDOM_LENGTH);
4865 if (rv != SECSuccess) {
4866 return rv; /* err set by ssl3_AppendHandshake* */
4870 rv = ssl3_AppendHandshakeVariable(
4871 ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
4873 rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
4874 if (rv != SECSuccess) {
4875 return rv; /* err set by ssl3_AppendHandshake* */
4879 rv = ssl3_AppendHandshakeVariable(
4880 ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1);
4881 if (rv != SECSuccess) {
4882 return rv; /* err set by ssl3_AppendHandshake* */
4886 rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2);
4887 if (rv != SECSuccess) {
4888 return rv; /* err set by ssl3_AppendHandshake* */
4891 if (ss->ssl3.hs.sendingSCSV) {
4892 /* Add the actual SCSV */
4893 rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
4894 sizeof(ssl3CipherSuite));
4895 if (rv != SECSuccess) {
4896 return rv; /* err set by ssl3_AppendHandshake* */
4900 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
4901 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
4902 if (config_match(suite, ss->ssl3.policy, PR_TRUE)) {
4904 if (actual_count > num_suites) {
4905 /* set error card removal/insertion error */
4906 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
4909 rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite,
4910 sizeof(ssl3CipherSuite));
4911 if (rv != SECSuccess) {
4912 return rv; /* err set by ssl3_AppendHandshake* */
4917 /* if cards were removed or inserted between count_cipher_suites and
4918 * generating our list, detect the error here rather than send it off to
4920 if (actual_count != num_suites) {
4921 /* Card removal/insertion error */
4922 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
4926 rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1);
4927 if (rv != SECSuccess) {
4928 return rv; /* err set by ssl3_AppendHandshake* */
4930 for (i = 0; i < compressionMethodsCount; i++) {
4931 if (!compressionEnabled(ss, compressions[i]))
4933 rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1);
4934 if (rv != SECSuccess) {
4935 return rv; /* err set by ssl3_AppendHandshake* */
4939 if (total_exten_len) {
4940 PRUint32 maxBytes = total_exten_len - 2;
4943 rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2);
4944 if (rv != SECSuccess) {
4945 return rv; /* err set by AppendHandshake. */
4948 extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL);
4953 PORT_Assert(!maxBytes);
4955 if (ss->ssl3.hs.sendingSCSV) {
4956 /* Since we sent the SCSV, pretend we sent empty RI extension. */
4957 TLSExtensionData *xtnData = &ss->xtnData;
4958 xtnData->advertised[xtnData->numAdvertised++] =
4959 ssl_renegotiation_info_xtn;
4963 if (!ss->firstHsDone && !requestingResume && !IS_DTLS(ss)) {
4964 flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION;
4966 rv = ssl3_FlushHandshake(ss, flags);
4967 if (rv != SECSuccess) {
4968 return rv; /* error code set by ssl3_FlushHandshake */
4971 ss->ssl3.hs.ws = wait_server_hello;
4976 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
4977 * ssl3 Hello Request.
4978 * Caller must hold Handshake and RecvBuf locks.
4981 ssl3_HandleHelloRequest(sslSocket *ss)
4983 sslSessionID *sid = ss->sec.ci.sid;
4986 SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
4987 SSL_GETPID(), ss->fd));
4989 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
4990 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
4992 if (ss->ssl3.hs.ws == wait_server_hello)
4994 if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
4995 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
4996 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
4999 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
5000 ssl_GetXmitBufLock(ss);
5001 rv = SSL3_SendAlert(ss, alert_warning, no_renegotiation);
5002 ssl_ReleaseXmitBufLock(ss);
5003 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
5008 if (ss->sec.uncache)
5009 ss->sec.uncache(sid);
5011 ss->sec.ci.sid = NULL;
5015 dtls_RehandshakeCleanup(ss);
5018 ssl_GetXmitBufLock(ss);
5019 rv = ssl3_SendClientHello(ss, PR_FALSE);
5020 ssl_ReleaseXmitBufLock(ss);
5025 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff
5027 static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
5043 UNKNOWN_WRAP_MECHANISM
5047 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech)
5049 const CK_MECHANISM_TYPE *pMech = wrapMechanismList;
5051 while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) {
5054 return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1
5055 : (pMech - wrapMechanismList);
5059 ssl_UnwrapSymWrappingKey(
5060 SSLWrappedSymWrappingKey *pWswk,
5061 SECKEYPrivateKey * svrPrivKey,
5062 SSL3KEAType exchKeyType,
5063 CK_MECHANISM_TYPE masterWrapMech,
5066 PK11SymKey * unwrappedWrappingKey = NULL;
5068 #ifdef NSS_ENABLE_ECC
5070 SECKEYPublicKey pubWrapKey;
5071 ECCWrappedKeyInfo *ecWrapped;
5072 #endif /* NSS_ENABLE_ECC */
5074 /* found the wrapping key on disk. */
5075 PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
5076 PORT_Assert(pWswk->exchKeyType == exchKeyType);
5077 if (pWswk->symWrapMechanism != masterWrapMech ||
5078 pWswk->exchKeyType != exchKeyType) {
5081 wrappedKey.type = siBuffer;
5082 wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
5083 wrappedKey.len = pWswk->wrappedSymKeyLen;
5084 PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
5086 switch (exchKeyType) {
5089 unwrappedWrappingKey =
5090 PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
5091 masterWrapMech, CKA_UNWRAP, 0);
5094 #ifdef NSS_ENABLE_ECC
5097 * For kt_ecdh, we first create an EC public key based on
5098 * data stored with the wrappedSymmetricWrappingkey. Next,
5099 * we do an ECDH computation involving this public key and
5100 * the SSL server's (long-term) EC private key. The resulting
5101 * shared secret is treated the same way as Fortezza's Ks, i.e.,
5102 * it is used to recover the symmetric wrapping key.
5104 * The data in wrappedSymmetricWrappingkey is laid out as defined
5105 * in the ECCWrappedKeyInfo structure.
5107 ecWrapped = (ECCWrappedKeyInfo *) pWswk->wrappedSymmetricWrappingkey;
5109 PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5110 ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN);
5112 if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5113 ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) {
5114 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5118 pubWrapKey.keyType = ecKey;
5119 pubWrapKey.u.ec.size = ecWrapped->size;
5120 pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
5121 pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
5122 pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
5123 pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
5124 ecWrapped->encodedParamLen;
5126 wrappedKey.len = ecWrapped->wrappedKeyLen;
5127 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
5128 ecWrapped->pubValueLen;
5130 /* Derive Ks using ECDH */
5131 Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
5132 NULL, CKM_ECDH1_DERIVE, masterWrapMech,
5133 CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5138 /* Use Ks to unwrap the wrapping key */
5139 unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL,
5140 &wrappedKey, masterWrapMech,
5142 PK11_FreeSymKey(Ks);
5153 return unwrappedWrappingKey;
5156 /* Each process sharing the server session ID cache has its own array of
5157 * SymKey pointers for the symmetric wrapping keys that are used to wrap
5158 * the master secrets. There is one key for each KEA type. These Symkeys
5159 * correspond to the wrapped SymKeys kept in the server session cache.
5163 PK11SymKey * symWrapKey[kt_kea_size];
5166 static PZLock * symWrapKeysLock = NULL;
5167 static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS];
5169 SECStatus ssl_FreeSymWrapKeysLock(void)
5171 if (symWrapKeysLock) {
5172 PZ_DestroyLock(symWrapKeysLock);
5173 symWrapKeysLock = NULL;
5176 PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
5181 SSL3_ShutdownServerCache(void)
5185 if (!symWrapKeysLock)
5186 return SECSuccess; /* lock was never initialized */
5187 PZ_Lock(symWrapKeysLock);
5188 /* get rid of all symWrapKeys */
5189 for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
5190 for (j = 0; j < kt_kea_size; ++j) {
5191 PK11SymKey ** pSymWrapKey;
5192 pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
5194 PK11_FreeSymKey(*pSymWrapKey);
5195 *pSymWrapKey = NULL;
5200 PZ_Unlock(symWrapKeysLock);
5201 ssl_FreeSessionCacheLocks();
5205 SECStatus ssl_InitSymWrapKeysLock(void)
5207 symWrapKeysLock = PZ_NewLock(nssILockOther);
5208 return symWrapKeysLock ? SECSuccess : SECFailure;
5211 /* Try to get wrapping key for mechanism from in-memory array.
5212 * If that fails, look for one on disk.
5213 * If that fails, generate a new one, put the new one on disk,
5214 * Put the new key in the in-memory array.
5217 getWrappingKey( sslSocket * ss,
5218 PK11SlotInfo * masterSecretSlot,
5219 SSL3KEAType exchKeyType,
5220 CK_MECHANISM_TYPE masterWrapMech,
5223 SECKEYPrivateKey * svrPrivKey;
5224 SECKEYPublicKey * svrPubKey = NULL;
5225 PK11SymKey * unwrappedWrappingKey = NULL;
5226 PK11SymKey ** pSymWrapKey;
5227 CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM;
5229 int symWrapMechIndex;
5232 SSLWrappedSymWrappingKey wswk;
5233 #ifdef NSS_ENABLE_ECC
5234 PK11SymKey * Ks = NULL;
5235 SECKEYPublicKey *pubWrapKey = NULL;
5236 SECKEYPrivateKey *privWrapKey = NULL;
5237 ECCWrappedKeyInfo *ecWrapped;
5238 #endif /* NSS_ENABLE_ECC */
5240 svrPrivKey = ss->serverCerts[exchKeyType].SERVERKEY;
5241 PORT_Assert(svrPrivKey != NULL);
5243 return NULL; /* why are we here?!? */
5246 symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech);
5247 PORT_Assert(symWrapMechIndex >= 0);
5248 if (symWrapMechIndex < 0)
5249 return NULL; /* invalid masterWrapMech. */
5251 pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType];
5253 ssl_InitSessionCacheLocks(PR_TRUE);
5255 PZ_Lock(symWrapKeysLock);
5257 unwrappedWrappingKey = *pSymWrapKey;
5258 if (unwrappedWrappingKey != NULL) {
5259 if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
5260 unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
5263 /* slot series has changed, so this key is no good any more. */
5264 PK11_FreeSymKey(unwrappedWrappingKey);
5265 *pSymWrapKey = unwrappedWrappingKey = NULL;
5268 /* Try to get wrapped SymWrapping key out of the (disk) cache. */
5269 /* Following call fills in wswk on success. */
5270 if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) {
5271 /* found the wrapped sym wrapping key on disk. */
5272 unwrappedWrappingKey =
5273 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
5274 masterWrapMech, pwArg);
5275 if (unwrappedWrappingKey) {
5280 if (!masterSecretSlot) /* caller doesn't want to create a new one. */
5283 length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
5284 /* Zero length means fixed key length algorithm, or error.
5287 unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
5289 if (!unwrappedWrappingKey) {
5293 /* Prepare the buffer to receive the wrappedWrappingKey,
5294 * the symmetric wrapping key wrapped using the server's pub key.
5296 PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */
5298 if (ss->serverCerts[exchKeyType].serverKeyPair) {
5299 svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey;
5301 if (svrPubKey == NULL) {
5302 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5305 wrappedKey.type = siBuffer;
5306 wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey);
5307 wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
5309 PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
5310 if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
5313 /* wrap symmetric wrapping key in server's public key. */
5314 switch (exchKeyType) {
5316 asymWrapMechanism = CKM_RSA_PKCS;
5317 rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
5318 unwrappedWrappingKey, &wrappedKey);
5321 #ifdef NSS_ENABLE_ECC
5324 * We generate an ephemeral EC key pair. Perform an ECDH
5325 * computation involving this ephemeral EC public key and
5326 * the SSL server's (long-term) EC private key. The resulting
5327 * shared secret is treated in the same way as Fortezza's Ks,
5328 * i.e., it is used to wrap the wrapping key. To facilitate
5329 * unwrapping in ssl_UnwrapWrappingKey, we also store all
5330 * relevant info about the ephemeral EC public key in
5331 * wswk.wrappedSymmetricWrappingkey and lay it out as
5332 * described in the ECCWrappedKeyInfo structure.
5334 PORT_Assert(svrPubKey->keyType == ecKey);
5335 if (svrPubKey->keyType != ecKey) {
5336 /* something is wrong in sslsecur.c if this isn't an ecKey */
5337 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5342 privWrapKey = SECKEY_CreateECPrivateKey(
5343 &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
5344 if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
5349 /* Set the key size in bits */
5350 if (pubWrapKey->u.ec.size == 0) {
5351 pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
5354 PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +
5355 pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN);
5356 if (pubWrapKey->u.ec.DEREncodedParams.len +
5357 pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) {
5358 PORT_SetError(SEC_ERROR_INVALID_KEY);
5363 /* Derive Ks using ECDH */
5364 Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
5365 NULL, CKM_ECDH1_DERIVE, masterWrapMech,
5366 CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5372 ecWrapped = (ECCWrappedKeyInfo *) (wswk.wrappedSymmetricWrappingkey);
5373 ecWrapped->size = pubWrapKey->u.ec.size;
5374 ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
5375 PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
5376 pubWrapKey->u.ec.DEREncodedParams.len);
5378 ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
5379 PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen,
5380 pubWrapKey->u.ec.publicValue.data,
5381 pubWrapKey->u.ec.publicValue.len);
5383 wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN -
5384 (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
5385 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
5386 ecWrapped->pubValueLen;
5388 /* wrap symmetricWrapping key with the local Ks */
5389 rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
5390 unwrappedWrappingKey, &wrappedKey);
5392 if (rv != SECSuccess) {
5396 /* Write down the length of wrapped key in the buffer
5397 * wswk.wrappedSymmetricWrappingkey at the appropriate offset
5399 ecWrapped->wrappedKeyLen = wrappedKey.len;
5402 if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey);
5403 if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey);
5404 if (Ks) PK11_FreeSymKey(Ks);
5405 asymWrapMechanism = masterWrapMech;
5407 #endif /* NSS_ENABLE_ECC */
5414 if (rv != SECSuccess) {
5415 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5419 PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
5421 wswk.symWrapMechanism = masterWrapMech;
5422 wswk.symWrapMechIndex = symWrapMechIndex;
5423 wswk.asymWrapMechanism = asymWrapMechanism;
5424 wswk.exchKeyType = exchKeyType;
5425 wswk.wrappedSymKeyLen = wrappedKey.len;
5427 /* put it on disk. */
5428 /* If the wrapping key for this KEA type has already been set,
5429 * then abandon the value we just computed and
5430 * use the one we got from the disk.
5432 if (ssl_SetWrappingKey(&wswk)) {
5433 /* somebody beat us to it. The original contents of our wswk
5434 * has been replaced with the content on disk. Now, discard
5435 * the key we just created and unwrap this new one.
5437 PK11_FreeSymKey(unwrappedWrappingKey);
5439 unwrappedWrappingKey =
5440 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
5441 masterWrapMech, pwArg);
5445 if (unwrappedWrappingKey) {
5446 *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
5451 PZ_Unlock(symWrapKeysLock);
5452 return unwrappedWrappingKey;
5455 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
5456 * bytes to |out|. */
5458 hexEncode(char *out, const unsigned char *in, unsigned int length)
5460 static const char hextable[] = "0123456789abcdef";
5463 for (i = 0; i < length; i++) {
5464 *(out++) = hextable[in[i] >> 4];
5465 *(out++) = hextable[in[i] & 15];
5469 /* Called from ssl3_SendClientKeyExchange(). */
5470 /* Presently, this always uses PKCS11. There is no bypass for this. */
5472 sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
5474 PK11SymKey * pms = NULL;
5475 SECStatus rv = SECFailure;
5476 SECItem enc_pms = {siBuffer, NULL, 0};
5479 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5480 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5482 /* Generate the pre-master secret ... */
5483 ssl_GetSpecWriteLock(ss);
5484 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5486 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
5487 ssl_ReleaseSpecWriteLock(ss);
5489 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5493 /* Get the wrapped (encrypted) pre-master secret, enc_pms */
5494 enc_pms.len = SECKEY_PublicKeyStrength(svrPubKey);
5495 enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len);
5496 if (enc_pms.data == NULL) {
5497 goto loser; /* err set by PORT_Alloc */
5500 /* wrap pre-master secret in server's public key. */
5501 rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
5502 if (rv != SECSuccess) {
5503 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5507 if (ssl_keylog_iob) {
5508 SECStatus extractRV = PK11_ExtractKeyValue(pms);
5509 if (extractRV == SECSuccess) {
5510 SECItem * keyData = PK11_GetKeyData(pms);
5511 if (keyData && keyData->data && keyData->len) {
5513 if (ssl_trace >= 100) {
5514 ssl_PrintBuf(ss, "Pre-Master Secret",
5515 keyData->data, keyData->len);
5518 if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) {
5519 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
5521 /* There could be multiple, concurrent writers to the
5522 * keylog, so we have to do everything in a single call to
5524 char buf[4 + 8*2 + 1 + 48*2 + 1];
5526 strcpy(buf, "RSA ");
5527 hexEncode(buf + 4, enc_pms.data, 8);
5529 hexEncode(buf + 21, keyData->data, 48);
5530 buf[sizeof(buf) - 1] = '\n';
5532 fwrite(buf, sizeof(buf), 1, ssl_keylog_iob);
5533 fflush(ssl_keylog_iob);
5539 rv = ssl3_InitPendingCipherSpec(ss, pms);
5540 PK11_FreeSymKey(pms); pms = NULL;
5542 if (rv != SECSuccess) {
5543 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5547 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
5548 isTLS ? enc_pms.len + 2 : enc_pms.len);
5549 if (rv != SECSuccess) {
5550 goto loser; /* err set by ssl3_AppendHandshake* */
5553 rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
5555 rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
5557 if (rv != SECSuccess) {
5558 goto loser; /* err set by ssl3_AppendHandshake* */
5564 if (enc_pms.data != NULL) {
5565 PORT_Free(enc_pms.data);
5568 PK11_FreeSymKey(pms);
5573 /* Called from ssl3_SendClientKeyExchange(). */
5574 /* Presently, this always uses PKCS11. There is no bypass for this. */
5576 sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
5578 PK11SymKey * pms = NULL;
5579 SECStatus rv = SECFailure;
5581 CK_MECHANISM_TYPE target;
5583 SECKEYDHParams dhParam; /* DH parameters */
5584 SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */
5585 SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */
5587 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5588 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5590 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5592 /* Copy DH parameters from server key */
5594 if (svrPubKey->keyType != dhKey) {
5595 PORT_SetError(SEC_ERROR_BAD_KEY);
5598 dhParam.prime.data = svrPubKey->u.dh.prime.data;
5599 dhParam.prime.len = svrPubKey->u.dh.prime.len;
5600 dhParam.base.data = svrPubKey->u.dh.base.data;
5601 dhParam.base.len = svrPubKey->u.dh.base.len;
5603 /* Generate ephemeral DH keypair */
5604 privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
5605 if (!privKey || !pubKey) {
5606 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
5610 PRINT_BUF(50, (ss, "DH public value:",
5611 pubKey->u.dh.publicValue.data,
5612 pubKey->u.dh.publicValue.len));
5614 if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH;
5615 else target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
5617 /* Determine the PMS */
5619 pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL,
5620 CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
5623 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5627 SECKEY_DestroyPrivateKey(privKey);
5630 rv = ssl3_InitPendingCipherSpec(ss, pms);
5631 PK11_FreeSymKey(pms); pms = NULL;
5633 if (rv != SECSuccess) {
5634 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5638 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
5639 pubKey->u.dh.publicValue.len + 2);
5640 if (rv != SECSuccess) {
5641 goto loser; /* err set by ssl3_AppendHandshake* */
5643 rv = ssl3_AppendHandshakeVariable(ss,
5644 pubKey->u.dh.publicValue.data,
5645 pubKey->u.dh.publicValue.len, 2);
5646 SECKEY_DestroyPublicKey(pubKey);
5649 if (rv != SECSuccess) {
5650 goto loser; /* err set by ssl3_AppendHandshake* */
5658 if(pms) PK11_FreeSymKey(pms);
5659 if(privKey) SECKEY_DestroyPrivateKey(privKey);
5660 if(pubKey) SECKEY_DestroyPublicKey(pubKey);
5668 /* Called from ssl3_HandleServerHelloDone(). */
5670 ssl3_SendClientKeyExchange(sslSocket *ss)
5672 SECKEYPublicKey * serverKey = NULL;
5673 SECStatus rv = SECFailure;
5676 SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
5677 SSL_GETPID(), ss->fd));
5679 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5680 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5682 if (ss->sec.peerKey == NULL) {
5683 serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
5684 if (serverKey == NULL) {
5685 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
5689 serverKey = ss->sec.peerKey;
5690 ss->sec.peerKey = NULL; /* we're done with it now */
5693 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5694 /* enforce limits on kea key sizes. */
5695 if (ss->ssl3.hs.kea_def->is_limited) {
5696 int keyLen = SECKEY_PublicKeyStrength(serverKey); /* bytes */
5698 if (keyLen * BPB > ss->ssl3.hs.kea_def->key_size_limit) {
5700 (void)SSL3_SendAlert(ss, alert_fatal, export_restriction);
5702 (void)ssl3_HandshakeFailure(ss);
5703 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
5708 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
5709 ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
5711 switch (ss->ssl3.hs.kea_def->exchKeyType) {
5713 rv = sendRSAClientKeyExchange(ss, serverKey);
5717 rv = sendDHClientKeyExchange(ss, serverKey);
5720 #ifdef NSS_ENABLE_ECC
5722 rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
5724 #endif /* NSS_ENABLE_ECC */
5727 /* got an unknown or unsupported Key Exchange Algorithm. */
5729 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
5733 SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
5734 SSL_GETPID(), ss->fd));
5738 SECKEY_DestroyPublicKey(serverKey);
5739 return rv; /* err code already set. */
5742 /* Called from ssl3_HandleServerHelloDone(). */
5744 ssl3_SendCertificateVerify(sslSocket *ss)
5746 SECStatus rv = SECFailure;
5749 SECItem buf = {siBuffer, NULL, 0};
5753 SSL3SignatureAndHashAlgorithm sigAndHash;
5755 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5756 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5758 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
5759 SSL_GETPID(), ss->fd));
5761 ssl_GetSpecReadLock(ss);
5762 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
5763 ssl_ReleaseSpecReadLock(ss);
5764 if (rv != SECSuccess) {
5765 goto done; /* err code was set by ssl3_ComputeHandshakeHashes */
5768 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
5769 isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
5770 keyType = ss->ssl3.clientPrivateKey->keyType;
5771 rv = ssl3_SignHashes(&hashes, ss->ssl3.clientPrivateKey, &buf, isTLS);
5772 if (rv == SECSuccess) {
5773 PK11SlotInfo * slot;
5774 sslSessionID * sid = ss->sec.ci.sid;
5776 /* Remember the info about the slot that did the signing.
5777 ** Later, when doing an SSL restart handshake, verify this.
5778 ** These calls are mere accessors, and can't fail.
5780 slot = PK11_GetSlotFromPrivateKey(ss->ssl3.clientPrivateKey);
5781 sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
5782 sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
5783 sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
5784 sid->u.ssl3.clAuthValid = PR_TRUE;
5785 PK11_FreeSlot(slot);
5787 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
5788 ss->ssl3.clientPrivateKey = NULL;
5789 if (rv != SECSuccess) {
5790 goto done; /* err code was set by ssl3_SignHashes */
5793 len = buf.len + 2 + (isTLS12 ? 2 : 0);
5795 rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len);
5796 if (rv != SECSuccess) {
5797 goto done; /* error code set by AppendHandshake */
5800 rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType,
5801 &sigAndHash.sigAlg);
5802 if (rv != SECSuccess) {
5805 /* We always sign using the handshake hash function. It's possible that
5806 * a server could support SHA-256 as the handshake hash but not as a
5807 * signature hash. In that case we wouldn't be able to do client
5808 * certificates with it. The alternative is to buffer all handshake
5810 sigAndHash.hashAlg = hashes.hashAlg;
5812 rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
5813 if (rv != SECSuccess) {
5814 goto done; /* err set by AppendHandshake. */
5817 rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
5818 if (rv != SECSuccess) {
5819 goto done; /* error code set by AppendHandshake */
5824 PORT_Free(buf.data);
5828 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5829 * ssl3 ServerHello message.
5830 * Caller must hold Handshake and RecvBuf locks.
5833 ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
5835 sslSessionID *sid = ss->sec.ci.sid;
5836 PRInt32 temp; /* allow for consume number failure */
5837 PRBool suite_found = PR_FALSE;
5839 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
5841 SECItem sidBytes = {siBuffer, NULL, 0};
5843 PRBool isTLS = PR_FALSE;
5844 SSL3AlertDescription desc = illegal_parameter;
5845 SSL3ProtocolVersion version;
5847 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
5848 SSL_GETPID(), ss->fd));
5849 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
5850 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
5851 PORT_Assert( ss->ssl3.initialized );
5853 if (ss->ssl3.hs.ws != wait_server_hello) {
5854 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
5855 desc = unexpected_message;
5859 /* clean up anything left from previous handshake. */
5860 if (ss->ssl3.clientCertChain != NULL) {
5861 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
5862 ss->ssl3.clientCertChain = NULL;
5864 if (ss->ssl3.clientCertificate != NULL) {
5865 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
5866 ss->ssl3.clientCertificate = NULL;
5868 if (ss->ssl3.clientPrivateKey != NULL) {
5869 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
5870 ss->ssl3.clientPrivateKey = NULL;
5873 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
5875 goto loser; /* alert has been sent */
5877 version = (SSL3ProtocolVersion)temp;
5880 /* RFC 4347 required that you verify that the server versions
5881 * match (Section 4.2.1) in the HelloVerifyRequest and the
5884 * RFC 6347 suggests (SHOULD) that servers always use 1.0
5885 * in HelloVerifyRequest and allows the versions not to match,
5886 * especially when 1.2 is being negotiated.
5888 * Therefore we do not check for matching here.
5890 version = dtls_DTLSVersionToTLSVersion(version);
5891 if (version == 0) { /* Insane version number */
5896 rv = ssl3_NegotiateVersion(ss, version, PR_FALSE);
5897 if (rv != SECSuccess) {
5898 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
5899 : handshake_failure;
5900 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
5903 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
5905 rv = ssl3_InitHandshakeHashes(ss);
5906 if (rv != SECSuccess) {
5907 desc = internal_error;
5908 errCode = PORT_GetError();
5912 rv = ssl3_ConsumeHandshake(
5913 ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
5914 if (rv != SECSuccess) {
5915 goto loser; /* alert has been sent */
5918 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
5919 if (rv != SECSuccess) {
5920 goto loser; /* alert has been sent */
5922 if (sidBytes.len > SSL3_SESSIONID_BYTES) {
5924 desc = decode_error;
5925 goto alert_loser; /* malformed. */
5928 /* find selected cipher suite in our list. */
5929 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
5931 goto loser; /* alert has been sent */
5933 ssl3_config_match_init(ss);
5934 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
5935 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
5936 if (temp == suite->cipher_suite) {
5937 if (!config_match(suite, ss->ssl3.policy, PR_TRUE)) {
5938 break; /* failure */
5940 if (!ssl3_CipherSuiteAllowedForVersion(suite->cipher_suite,
5942 desc = handshake_failure;
5943 errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION;
5947 suite_found = PR_TRUE;
5948 break; /* success */
5952 desc = handshake_failure;
5953 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
5956 ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp;
5957 ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp);
5958 PORT_Assert(ss->ssl3.hs.suite_def);
5959 if (!ss->ssl3.hs.suite_def) {
5960 PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE);
5961 goto loser; /* we don't send alerts for our screw-ups. */
5964 /* find selected compression method in our list. */
5965 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
5967 goto loser; /* alert has been sent */
5969 suite_found = PR_FALSE;
5970 for (i = 0; i < compressionMethodsCount; i++) {
5971 if (temp == compressions[i]) {
5972 if (!compressionEnabled(ss, compressions[i])) {
5973 break; /* failure */
5975 suite_found = PR_TRUE;
5976 break; /* success */
5980 desc = handshake_failure;
5981 errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
5984 ss->ssl3.hs.compression = (SSLCompressionMethod)temp;
5986 /* Note that if !isTLS and the extra stuff is not extensions, we
5987 * do NOT goto alert_loser.
5988 * There are some old SSL 3.0 implementations that do send stuff
5989 * after the end of the server hello, and we deliberately ignore
5990 * such stuff in the interest of maximal interoperability (being
5991 * "generous in what you accept").
5992 * Update: Starting in NSS 3.12.6, we handle the renegotiation_info
5993 * extension in SSL 3.0.
5997 rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length);
5998 if (rv != SECSuccess || length != 0) {
6002 rv = ssl3_HandleHelloExtensions(ss, &extensions.data,
6004 if (rv != SECSuccess)
6008 if ((ss->opt.requireSafeNegotiation ||
6009 (ss->firstHsDone && (ss->peerRequestedProtection ||
6010 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN))) &&
6011 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
6012 desc = handshake_failure;
6013 errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
6014 : SSL_ERROR_UNSAFE_NEGOTIATION;
6018 /* Any errors after this point are not "malformed" errors. */
6019 desc = handshake_failure;
6021 /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
6022 * key exchange algorithm. */
6023 rv = ssl3_SetupPendingCipherSpec(ss);
6024 if (rv != SECSuccess) {
6025 goto alert_loser; /* error code is set. */
6028 /* We may or may not have sent a session id, we may get one back or
6029 * not and if so it may match the one we sent.
6030 * Attempt to restore the master secret to see if this is so...
6031 * Don't consider failure to find a matching SID an error.
6033 sid_match = (PRBool)(sidBytes.len > 0 &&
6034 sidBytes.len == sid->u.ssl3.sessionIDLength &&
6035 !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len));
6038 sid->version == ss->version &&
6039 sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do {
6040 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
6042 SECItem wrappedMS; /* wrapped master secret. */
6044 ss->sec.authAlgorithm = sid->authAlgorithm;
6045 ss->sec.authKeyBits = sid->authKeyBits;
6046 ss->sec.keaType = sid->keaType;
6047 ss->sec.keaKeyBits = sid->keaKeyBits;
6050 * a) key is wrapped (implies using PKCS11)
6051 * b) key is unwrapped, but we're still using PKCS11
6052 * c) key is unwrapped, and we're bypassing PKCS11.
6054 if (sid->u.ssl3.keys.msIsWrapped) {
6056 PK11SymKey * wrapKey; /* wrapping key */
6057 CK_FLAGS keyFlags = 0;
6059 #ifndef NO_PKCS11_BYPASS
6060 if (ss->opt.bypassPKCS11) {
6061 /* we cannot restart a non-bypass session in a
6067 /* unwrap master secret with PKCS11 */
6068 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
6069 sid->u.ssl3.masterSlotID);
6071 break; /* not considered an error. */
6073 if (!PK11_IsPresent(slot)) {
6074 PK11_FreeSlot(slot);
6075 break; /* not considered an error. */
6077 wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
6078 sid->u.ssl3.masterWrapMech,
6079 sid->u.ssl3.masterWrapSeries,
6081 PK11_FreeSlot(slot);
6082 if (wrapKey == NULL) {
6083 break; /* not considered an error. */
6086 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
6087 keyFlags = CKF_SIGN | CKF_VERIFY;
6090 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6091 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
6092 pwSpec->master_secret =
6093 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
6094 NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
6095 CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
6096 errCode = PORT_GetError();
6097 PK11_FreeSymKey(wrapKey);
6098 if (pwSpec->master_secret == NULL) {
6099 break; /* errorCode set just after call to UnwrapSymKey. */
6101 #ifndef NO_PKCS11_BYPASS
6102 } else if (ss->opt.bypassPKCS11) {
6103 /* MS is not wrapped */
6104 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6105 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
6106 memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
6107 pwSpec->msItem.data = pwSpec->raw_master_secret;
6108 pwSpec->msItem.len = wrappedMS.len;
6111 /* We CAN restart a bypass session in a non-bypass socket. */
6112 /* need to import the raw master secret to session object */
6113 PK11SlotInfo *slot = PK11_GetInternalSlot();
6114 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6115 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
6116 pwSpec->master_secret =
6117 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
6118 PK11_OriginUnwrap, CKA_ENCRYPT,
6120 PK11_FreeSlot(slot);
6121 if (pwSpec->master_secret == NULL) {
6127 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_hits );
6129 /* If we sent a session ticket, then this is a stateless resume. */
6130 if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
6131 sid->u.ssl3.sessionTicket.ticket.data != NULL)
6132 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_stateless_resumes );
6134 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
6135 ss->ssl3.hs.ws = wait_new_session_ticket;
6137 ss->ssl3.hs.ws = wait_change_cipher;
6139 ss->ssl3.hs.isResuming = PR_TRUE;
6141 /* copy the peer cert from the SID */
6142 if (sid->peerCert != NULL) {
6143 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
6146 /* NULL value for PMS signifies re-use of the old MS */
6147 rv = ssl3_InitPendingCipherSpec(ss, NULL);
6148 if (rv != SECSuccess) {
6149 goto alert_loser; /* err code was set */
6155 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_not_ok );
6157 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses );
6159 /* throw the old one away */
6160 sid->u.ssl3.keys.resumable = PR_FALSE;
6161 if (ss->sec.uncache)
6162 (*ss->sec.uncache)(sid);
6166 ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
6168 goto alert_loser; /* memory error is set. */
6171 sid->version = ss->version;
6172 sid->u.ssl3.sessionIDLength = sidBytes.len;
6173 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len);
6175 ss->ssl3.hs.isResuming = PR_FALSE;
6176 ss->ssl3.hs.ws = wait_server_cert;
6180 (void)SSL3_SendAlert(ss, alert_fatal, desc);
6183 errCode = ssl_MapLowLevelError(errCode);
6187 /* ssl3_BigIntGreaterThanOne returns true iff |mpint|, taken as an unsigned,
6188 * big-endian integer is > 1 */
6190 ssl3_BigIntGreaterThanOne(const SECItem* mpint) {
6191 unsigned char firstNonZeroByte = 0;
6194 for (i = 0; i < mpint->len; i++) {
6195 if (mpint->data[i]) {
6196 firstNonZeroByte = mpint->data[i];
6201 if (firstNonZeroByte == 0)
6203 if (firstNonZeroByte > 1)
6206 /* firstNonZeroByte == 1, therefore mpint > 1 iff the first non-zero byte
6207 * is followed by another byte. */
6208 return (i < mpint->len - 1);
6211 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6212 * ssl3 ServerKeyExchange message.
6213 * Caller must hold Handshake and RecvBuf locks.
6216 ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
6218 PLArenaPool * arena = NULL;
6219 SECKEYPublicKey *peerKey = NULL;
6220 PRBool isTLS, isTLS12;
6222 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
6223 SSL3AlertDescription desc = illegal_parameter;
6225 SECItem signature = {siBuffer, NULL, 0};
6226 SSL3SignatureAndHashAlgorithm sigAndHash;
6228 sigAndHash.hashAlg = SEC_OID_UNKNOWN;
6230 SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
6231 SSL_GETPID(), ss->fd));
6232 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6233 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6235 if (ss->ssl3.hs.ws != wait_server_key &&
6236 ss->ssl3.hs.ws != wait_server_cert) {
6237 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
6238 desc = unexpected_message;
6241 if (ss->sec.peerCert == NULL) {
6242 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
6243 desc = unexpected_message;
6247 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
6248 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
6250 switch (ss->ssl3.hs.kea_def->exchKeyType) {
6253 SECItem modulus = {siBuffer, NULL, 0};
6254 SECItem exponent = {siBuffer, NULL, 0};
6256 rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length);
6257 if (rv != SECSuccess) {
6258 goto loser; /* malformed. */
6260 rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length);
6261 if (rv != SECSuccess) {
6262 goto loser; /* malformed. */
6265 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
6267 if (rv != SECSuccess) {
6268 goto loser; /* malformed or unsupported. */
6270 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
6271 &sigAndHash, ss->sec.peerCert);
6272 if (rv != SECSuccess) {
6276 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
6277 if (rv != SECSuccess) {
6278 goto loser; /* malformed. */
6282 desc = decode_error;
6283 goto alert_loser; /* malformed. */
6286 /* failures after this point are not malformed handshakes. */
6287 /* TLS: send decrypt_error if signature failed. */
6288 desc = isTLS ? decrypt_error : handshake_failure;
6291 * check to make sure the hash is signed by right guy
6293 rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, exponent,
6294 &ss->ssl3.hs.client_random,
6295 &ss->ssl3.hs.server_random,
6296 &hashes, ss->opt.bypassPKCS11);
6297 if (rv != SECSuccess) {
6299 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6302 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
6303 isTLS, ss->pkcs11PinArg);
6304 if (rv != SECSuccess) {
6306 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6311 * we really need to build a new key here because we can no longer
6312 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
6313 * pkcs11 slots and ID's.
6315 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
6316 if (arena == NULL) {
6320 peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
6321 if (peerKey == NULL) {
6322 PORT_FreeArena(arena, PR_FALSE);
6326 peerKey->arena = arena;
6327 peerKey->keyType = rsaKey;
6328 peerKey->pkcs11Slot = NULL;
6329 peerKey->pkcs11ID = CK_INVALID_HANDLE;
6330 if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus, &modulus) ||
6331 SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent))
6333 PORT_FreeArena(arena, PR_FALSE);
6336 ss->sec.peerKey = peerKey;
6337 ss->ssl3.hs.ws = wait_cert_request;
6342 SECItem dh_p = {siBuffer, NULL, 0};
6343 SECItem dh_g = {siBuffer, NULL, 0};
6344 SECItem dh_Ys = {siBuffer, NULL, 0};
6346 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
6347 if (rv != SECSuccess) {
6348 goto loser; /* malformed. */
6350 if (dh_p.len < 512/8) {
6351 errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
6354 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
6355 if (rv != SECSuccess) {
6356 goto loser; /* malformed. */
6358 if (dh_g.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_g))
6360 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
6361 if (rv != SECSuccess) {
6362 goto loser; /* malformed. */
6364 if (dh_Ys.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_Ys))
6367 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
6369 if (rv != SECSuccess) {
6370 goto loser; /* malformed or unsupported. */
6372 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
6373 &sigAndHash, ss->sec.peerCert);
6374 if (rv != SECSuccess) {
6378 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
6379 if (rv != SECSuccess) {
6380 goto loser; /* malformed. */
6384 desc = decode_error;
6385 goto alert_loser; /* malformed. */
6388 PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
6389 PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
6390 PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
6392 /* failures after this point are not malformed handshakes. */
6393 /* TLS: send decrypt_error if signature failed. */
6394 desc = isTLS ? decrypt_error : handshake_failure;
6397 * check to make sure the hash is signed by right guy
6399 rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys,
6400 &ss->ssl3.hs.client_random,
6401 &ss->ssl3.hs.server_random,
6402 &hashes, ss->opt.bypassPKCS11);
6403 if (rv != SECSuccess) {
6405 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6408 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
6409 isTLS, ss->pkcs11PinArg);
6410 if (rv != SECSuccess) {
6412 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6417 * we really need to build a new key here because we can no longer
6418 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
6419 * pkcs11 slots and ID's.
6421 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
6422 if (arena == NULL) {
6426 ss->sec.peerKey = peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
6427 if (peerKey == NULL) {
6431 peerKey->arena = arena;
6432 peerKey->keyType = dhKey;
6433 peerKey->pkcs11Slot = NULL;
6434 peerKey->pkcs11ID = CK_INVALID_HANDLE;
6436 if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) ||
6437 SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) ||
6438 SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys))
6440 PORT_FreeArena(arena, PR_FALSE);
6443 ss->sec.peerKey = peerKey;
6444 ss->ssl3.hs.ws = wait_cert_request;
6448 #ifdef NSS_ENABLE_ECC
6450 rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
6452 #endif /* NSS_ENABLE_ECC */
6455 desc = handshake_failure;
6456 errCode = SEC_ERROR_UNSUPPORTED_KEYALG;
6457 break; /* goto alert_loser; */
6461 (void)SSL3_SendAlert(ss, alert_fatal, desc);
6463 PORT_SetError( errCode );
6466 no_memory: /* no-memory error has already been set. */
6467 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
6472 typedef struct dnameNode {
6473 struct dnameNode *next;
6477 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6478 * ssl3 Certificate Request message.
6479 * Caller must hold Handshake and RecvBuf locks.
6482 ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
6484 PLArenaPool * arena = NULL;
6487 PRBool isTLS = PR_FALSE;
6488 PRBool isTLS12 = PR_FALSE;
6490 int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
6493 SSL3AlertDescription desc = illegal_parameter;
6494 SECItem cert_types = {siBuffer, NULL, 0};
6495 SECItem algorithms = {siBuffer, NULL, 0};
6496 CERTDistNames ca_list;
6498 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
6499 SSL_GETPID(), ss->fd));
6500 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6501 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6503 if (ss->ssl3.hs.ws != wait_cert_request &&
6504 ss->ssl3.hs.ws != wait_server_key) {
6505 desc = unexpected_message;
6506 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
6510 PORT_Assert(ss->ssl3.clientCertChain == NULL);
6511 PORT_Assert(ss->ssl3.clientCertificate == NULL);
6512 PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
6514 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
6515 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
6516 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
6517 if (rv != SECSuccess)
6518 goto loser; /* malformed, alert has been sent */
6521 rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length);
6522 if (rv != SECSuccess)
6523 goto loser; /* malformed, alert has been sent */
6524 /* An empty or odd-length value is invalid.
6525 * SignatureAndHashAlgorithm
6526 * supported_signature_algorithms<2..2^16-2>;
6528 if (algorithms.len == 0 || (algorithms.len & 1) != 0)
6532 arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
6536 remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6538 goto loser; /* malformed, alert has been sent */
6540 if ((PRUint32)remaining > length)
6543 ca_list.head = node = PORT_ArenaZNew(arena, dnameNode);
6547 while (remaining > 0) {
6551 goto alert_loser; /* malformed */
6553 node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6555 goto loser; /* malformed, alert has been sent */
6558 if (remaining < len)
6559 goto alert_loser; /* malformed */
6561 node->name.data = b;
6567 break; /* success */
6569 node->next = PORT_ArenaZNew(arena, dnameNode);
6575 ca_list.nnames = nnames;
6576 ca_list.names = PORT_ArenaNewArray(arena, SECItem, nnames);
6577 if (nnames > 0 && ca_list.names == NULL)
6580 for(i = 0, node = (dnameNode*)ca_list.head;
6582 i++, node = node->next) {
6583 ca_list.names[i] = node->name;
6587 goto alert_loser; /* malformed */
6589 desc = no_certificate;
6590 ss->ssl3.hs.ws = wait_hello_done;
6592 if (ss->getClientAuthData != NULL) {
6593 /* XXX Should pass cert_types and algorithms in this call!! */
6594 rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
6596 &ss->ssl3.clientCertificate,
6597 &ss->ssl3.clientPrivateKey);
6599 rv = SECFailure; /* force it to send a no_certificate alert */
6602 case SECWouldBlock: /* getClientAuthData has put up a dialog box. */
6603 ssl3_SetAlwaysBlock(ss);
6604 break; /* not an error */
6607 /* check what the callback function returned */
6608 if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
6609 /* we are missing either the key or cert */
6610 if (ss->ssl3.clientCertificate) {
6611 /* got a cert, but no key - free it */
6612 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6613 ss->ssl3.clientCertificate = NULL;
6615 if (ss->ssl3.clientPrivateKey) {
6616 /* got a key, but no cert - free it */
6617 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6618 ss->ssl3.clientPrivateKey = NULL;
6620 goto send_no_certificate;
6622 /* Setting ssl3.clientCertChain non-NULL will cause
6623 * ssl3_HandleServerHelloDone to call SendCertificate.
6625 ss->ssl3.clientCertChain = CERT_CertChainFromCert(
6626 ss->ssl3.clientCertificate,
6627 certUsageSSLClient, PR_FALSE);
6628 if (ss->ssl3.clientCertChain == NULL) {
6629 if (ss->ssl3.clientCertificate != NULL) {
6630 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6631 ss->ssl3.clientCertificate = NULL;
6633 if (ss->ssl3.clientPrivateKey != NULL) {
6634 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6635 ss->ssl3.clientPrivateKey = NULL;
6637 goto send_no_certificate;
6639 break; /* not an error */
6643 send_no_certificate:
6645 ss->ssl3.sendEmptyCert = PR_TRUE;
6647 (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
6656 PORT_SetError(SEC_ERROR_NO_MEMORY);
6660 if (isTLS && desc == illegal_parameter)
6661 desc = decode_error;
6662 (void)SSL3_SendAlert(ss, alert_fatal, desc);
6664 PORT_SetError(errCode);
6668 PORT_FreeArena(arena, PR_FALSE);
6673 ssl3_CanFalseStart(sslSocket *ss) {
6676 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6678 /* XXX: does not take into account whether we are waiting for
6679 * SSL_AuthCertificateComplete or SSL_RestartHandshakeAfterCertReq. If/when
6680 * that is done, this function could return different results each time it
6684 ssl_GetSpecReadLock(ss);
6685 rv = ss->opt.enableFalseStart &&
6686 !ss->sec.isServer &&
6687 !ss->ssl3.hs.isResuming &&
6690 /* An attacker can control the selected ciphersuite so we only wish to
6691 * do False Start in the case that the selected ciphersuite is
6692 * sufficiently strong that the attack can gain no advantage.
6693 * Therefore we require an 80-bit cipher and a forward-secret key
6695 ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10 &&
6696 (ss->ssl3.hs.kea_def->kea == kea_dhe_dss ||
6697 ss->ssl3.hs.kea_def->kea == kea_dhe_rsa ||
6698 ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
6699 ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa);
6700 ssl_ReleaseSpecReadLock(ss);
6704 static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
6706 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6707 * ssl3 Server Hello Done message.
6708 * Caller must hold Handshake and RecvBuf locks.
6711 ssl3_HandleServerHelloDone(sslSocket *ss)
6714 SSL3WaitState ws = ss->ssl3.hs.ws;
6716 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
6717 SSL_GETPID(), ss->fd));
6718 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6719 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6721 if (ws != wait_hello_done &&
6722 ws != wait_server_cert &&
6723 ws != wait_server_key &&
6724 ws != wait_cert_request) {
6725 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
6726 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
6730 rv = ssl3_SendClientSecondRound(ss);
6735 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
6737 * Caller must hold Handshake and RecvBuf locks.
6740 ssl3_SendClientSecondRound(sslSocket *ss)
6743 PRBool sendClientCert;
6745 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
6746 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6748 sendClientCert = !ss->ssl3.sendEmptyCert &&
6749 ss->ssl3.clientCertChain != NULL &&
6750 ss->ssl3.clientPrivateKey != NULL;
6752 /* We must wait for the server's certificate to be authenticated before
6753 * sending the client certificate in order to disclosing the client
6754 * certificate to an attacker that does not have a valid cert for the
6755 * domain we are connecting to.
6757 * XXX: We should do the same for the NPN extension, but for that we
6758 * need an option to give the application the ability to leak the NPN
6759 * information to get better performance.
6761 * During the initial handshake on a connection, we never send/receive
6762 * application data until we have authenticated the server's certificate;
6763 * i.e. we have fully authenticated the handshake before using the cipher
6764 * specs agreed upon for that handshake. During a renegotiation, we may
6765 * continue sending and receiving application data during the handshake
6766 * interleaved with the handshake records. If we were to send the client's
6767 * second round for a renegotiation before the server's certificate was
6768 * authenticated, then the application data sent/received after this point
6769 * would be using cipher spec that hadn't been authenticated. By waiting
6770 * until the server's certificate has been authenticated during
6771 * renegotiations, we ensure that renegotiations have the same property
6772 * as initial handshakes; i.e. we have fully authenticated the handshake
6773 * before using the cipher specs agreed upon for that handshake for
6776 if (ss->ssl3.hs.restartTarget) {
6777 PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
6778 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6781 if (ss->ssl3.hs.authCertificatePending &&
6782 (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) {
6783 ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
6784 return SECWouldBlock;
6787 ssl_GetXmitBufLock(ss); /*******************************/
6789 if (ss->ssl3.sendEmptyCert) {
6790 ss->ssl3.sendEmptyCert = PR_FALSE;
6791 rv = ssl3_SendEmptyCertificate(ss);
6792 /* Don't send verify */
6793 if (rv != SECSuccess) {
6794 goto loser; /* error code is set. */
6796 } else if (sendClientCert) {
6797 rv = ssl3_SendCertificate(ss);
6798 if (rv != SECSuccess) {
6799 goto loser; /* error code is set. */
6803 rv = ssl3_SendClientKeyExchange(ss);
6804 if (rv != SECSuccess) {
6805 goto loser; /* err is set. */
6808 if (sendClientCert) {
6809 rv = ssl3_SendCertificateVerify(ss);
6810 if (rv != SECSuccess) {
6811 goto loser; /* err is set. */
6815 rv = ssl3_SendChangeCipherSpecs(ss);
6816 if (rv != SECSuccess) {
6817 goto loser; /* err code was set. */
6820 /* XXX: If the server's certificate hasn't been authenticated by this
6821 * point, then we may be leaking this NPN message to an attacker.
6823 if (!ss->firstHsDone) {
6824 rv = ssl3_SendNextProto(ss);
6825 if (rv != SECSuccess) {
6826 goto loser; /* err code was set. */
6830 rv = ssl3_SendFinished(ss, 0);
6831 if (rv != SECSuccess) {
6832 goto loser; /* err code was set. */
6835 ssl_ReleaseXmitBufLock(ss); /*******************************/
6837 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
6838 ss->ssl3.hs.ws = wait_new_session_ticket;
6840 ss->ssl3.hs.ws = wait_change_cipher;
6842 /* Do the handshake callback for sslv3 here, if we can false start. */
6843 if (ss->handshakeCallback != NULL && ssl3_CanFalseStart(ss)) {
6844 (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
6850 ssl_ReleaseXmitBufLock(ss);
6855 * Routines used by servers
6858 ssl3_SendHelloRequest(sslSocket *ss)
6862 SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
6865 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6866 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
6868 rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0);
6869 if (rv != SECSuccess) {
6870 return rv; /* err set by AppendHandshake */
6872 rv = ssl3_FlushHandshake(ss, 0);
6873 if (rv != SECSuccess) {
6874 return rv; /* error code set by ssl3_FlushHandshake */
6876 ss->ssl3.hs.ws = wait_client_hello;
6882 * ssl3_HandleClientHello()
6884 static SECComparison
6885 ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
6887 if (!name1 != !name2) {
6893 if (name1->type != name2->type) {
6896 return SECITEM_CompareItem(name1, name2);
6899 /* Sets memory error when returning NULL.
6901 * ssl3_SendClientHello()
6902 * ssl3_HandleServerHello()
6903 * ssl3_HandleClientHello()
6904 * ssl3_HandleV2ClientHello()
6907 ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
6911 sid = PORT_ZNew(sslSessionID);
6916 const SECItem * srvName;
6917 SECStatus rv = SECSuccess;
6919 ssl_GetSpecReadLock(ss); /********************************/
6920 srvName = &ss->ssl3.prSpec->srvVirtName;
6921 if (srvName->len && srvName->data) {
6922 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
6924 ssl_ReleaseSpecReadLock(ss); /************************************/
6925 if (rv != SECSuccess) {
6930 sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
6931 sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url);
6932 sid->addr = ss->sec.ci.peer;
6933 sid->port = ss->sec.ci.port;
6934 sid->references = 1;
6935 sid->cached = never_cached;
6936 sid->version = ss->version;
6938 sid->u.ssl3.keys.resumable = PR_TRUE;
6939 sid->u.ssl3.policy = SSL_ALLOWED;
6940 sid->u.ssl3.clientWriteKey = NULL;
6941 sid->u.ssl3.serverWriteKey = NULL;
6945 int pid = SSL_GETPID();
6947 sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
6948 sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff;
6949 sid->u.ssl3.sessionID[1] = pid & 0xff;
6950 rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
6951 SSL3_SESSIONID_BYTES -2);
6952 if (rv != SECSuccess) {
6954 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
6961 /* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
6963 ssl3_SendServerHelloSequence(sslSocket *ss)
6965 const ssl3KEADef *kea_def;
6968 SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
6969 SSL_GETPID(), ss->fd));
6971 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
6972 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
6974 rv = ssl3_SendServerHello(ss);
6975 if (rv != SECSuccess) {
6976 return rv; /* err code is set. */
6978 rv = ssl3_SendCertificate(ss);
6979 if (rv != SECSuccess) {
6980 return rv; /* error code is set. */
6982 rv = ssl3_SendCertificateStatus(ss);
6983 if (rv != SECSuccess) {
6984 return rv; /* error code is set. */
6986 /* We have to do this after the call to ssl3_SendServerHello,
6987 * because kea_def is set up by ssl3_SendServerHello().
6989 kea_def = ss->ssl3.hs.kea_def;
6990 ss->ssl3.hs.usedStepDownKey = PR_FALSE;
6992 if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) {
6993 /* see if we can legally use the key in the cert. */
6994 int keyLen; /* bytes */
6996 keyLen = PK11_GetPrivateModulusLen(
6997 ss->serverCerts[kea_def->exchKeyType].SERVERKEY);
7000 keyLen * BPB <= kea_def->key_size_limit ) {
7001 /* XXX AND cert is not signing only!! */
7002 /* just fall through and use it. */
7003 } else if (ss->stepDownKeyPair != NULL) {
7004 ss->ssl3.hs.usedStepDownKey = PR_TRUE;
7005 rv = ssl3_SendServerKeyExchange(ss);
7006 if (rv != SECSuccess) {
7007 return rv; /* err code was set. */
7010 #ifndef HACKED_EXPORT_SERVER
7011 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
7015 #ifdef NSS_ENABLE_ECC
7016 } else if ((kea_def->kea == kea_ecdhe_rsa) ||
7017 (kea_def->kea == kea_ecdhe_ecdsa)) {
7018 rv = ssl3_SendServerKeyExchange(ss);
7019 if (rv != SECSuccess) {
7020 return rv; /* err code was set. */
7022 #endif /* NSS_ENABLE_ECC */
7025 if (ss->opt.requestCertificate) {
7026 rv = ssl3_SendCertificateRequest(ss);
7027 if (rv != SECSuccess) {
7028 return rv; /* err code is set. */
7031 rv = ssl3_SendServerHelloDone(ss);
7032 if (rv != SECSuccess) {
7033 return rv; /* err code is set. */
7036 ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
7041 /* An empty TLS Renegotiation Info (RI) extension */
7042 static const PRUint8 emptyRIext[5] = {0xff, 0x01, 0x00, 0x01, 0x00};
7044 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7045 * ssl3 Client Hello message.
7046 * Caller must hold Handshake and RecvBuf locks.
7049 ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
7051 sslSessionID * sid = NULL;
7056 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
7057 SSL3AlertDescription desc = illegal_parameter;
7058 SSL3AlertLevel level = alert_fatal;
7059 SSL3ProtocolVersion version;
7060 SECItem sidBytes = {siBuffer, NULL, 0};
7061 SECItem cookieBytes = {siBuffer, NULL, 0};
7062 SECItem suites = {siBuffer, NULL, 0};
7063 SECItem comps = {siBuffer, NULL, 0};
7064 PRBool haveSpecWriteLock = PR_FALSE;
7065 PRBool haveXmitBufLock = PR_FALSE;
7067 SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
7068 SSL_GETPID(), ss->fd));
7070 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
7071 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7072 PORT_Assert( ss->ssl3.initialized );
7074 /* Get peer name of client */
7075 rv = ssl_GetPeerInfo(ss);
7076 if (rv != SECSuccess) {
7077 return rv; /* error code is set. */
7080 /* Clearing the handshake pointers so that ssl_Do1stHandshake won't
7081 * call ssl2_HandleMessage.
7083 * The issue here is that TLS ordinarily starts out in
7084 * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility
7085 * code paths. That function zeroes these next pointers. But with DTLS,
7086 * we don't even try to do the v2 ClientHello so we skip that function
7087 * and need to reset these values here.
7090 ss->nextHandshake = 0;
7091 ss->securityHandshake = 0;
7094 /* We might be starting session renegotiation in which case we should
7095 * clear previous state.
7097 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
7098 ss->statelessResume = PR_FALSE;
7100 if ((ss->ssl3.hs.ws != wait_client_hello) &&
7101 (ss->ssl3.hs.ws != idle_handshake)) {
7102 desc = unexpected_message;
7103 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
7106 if (ss->ssl3.hs.ws == idle_handshake &&
7107 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
7108 desc = no_renegotiation;
7109 level = alert_warning;
7110 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
7115 dtls_RehandshakeCleanup(ss);
7118 tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
7120 goto loser; /* malformed, alert already sent */
7122 /* Translate the version */
7124 ss->clientHelloVersion = version =
7125 dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
7127 ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp;
7130 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
7131 if (rv != SECSuccess) {
7132 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
7133 : handshake_failure;
7134 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
7138 rv = ssl3_InitHandshakeHashes(ss);
7139 if (rv != SECSuccess) {
7140 desc = internal_error;
7141 errCode = PORT_GetError();
7145 /* grab the client random data. */
7146 rv = ssl3_ConsumeHandshake(
7147 ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length);
7148 if (rv != SECSuccess) {
7149 goto loser; /* malformed */
7152 /* grab the client's SID, if present. */
7153 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
7154 if (rv != SECSuccess) {
7155 goto loser; /* malformed */
7158 /* grab the client's cookie, if present. */
7160 rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length);
7161 if (rv != SECSuccess) {
7162 goto loser; /* malformed */
7166 /* grab the list of cipher suites. */
7167 rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length);
7168 if (rv != SECSuccess) {
7169 goto loser; /* malformed */
7172 /* grab the list of compression methods. */
7173 rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length);
7174 if (rv != SECSuccess) {
7175 goto loser; /* malformed */
7178 desc = handshake_failure;
7180 /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
7181 * we are restarting a previous session until extensions have been
7182 * parsed, since we might have received a SessionTicket extension.
7183 * Note: we allow extensions even when negotiating SSL3 for the sake
7184 * of interoperability (and backwards compatibility).
7188 /* Get length of hello extensions */
7189 PRInt32 extension_length;
7190 extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
7191 if (extension_length < 0) {
7192 goto loser; /* alert already sent */
7194 if (extension_length != length) {
7195 ssl3_DecodeError(ss); /* send alert */
7198 rv = ssl3_HandleHelloExtensions(ss, &b, &length);
7199 if (rv != SECSuccess) {
7200 goto loser; /* malformed */
7203 if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7204 /* If we didn't receive an RI extension, look for the SCSV,
7205 * and if found, treat it just like an empty RI extension
7206 * by processing a local copy of an empty RI extension.
7208 for (i = 0; i + 1 < suites.len; i += 2) {
7209 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
7210 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
7211 SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
7212 PRUint32 L2 = sizeof emptyRIext;
7213 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
7218 if (ss->firstHsDone &&
7219 (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
7220 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) &&
7221 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7222 desc = no_renegotiation;
7223 level = alert_warning;
7224 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
7227 if ((ss->opt.requireSafeNegotiation ||
7228 (ss->firstHsDone && ss->peerRequestedProtection)) &&
7229 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7230 desc = handshake_failure;
7231 errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
7235 /* We do stateful resumes only if either of the following
7236 * conditions are satisfied: (1) the client does not support the
7237 * session ticket extension, or (2) the client support the session
7238 * ticket extension, but sent an empty ticket.
7240 if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
7241 ss->xtnData.emptySessionTicket) {
7242 if (sidBytes.len > 0 && !ss->opt.noCache) {
7243 SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
7244 SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
7245 ss->sec.ci.peer.pr_s6_addr32[1],
7246 ss->sec.ci.peer.pr_s6_addr32[2],
7247 ss->sec.ci.peer.pr_s6_addr32[3]));
7248 if (ssl_sid_lookup) {
7249 sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data,
7250 sidBytes.len, ss->dbHandle);
7252 errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
7256 } else if (ss->statelessResume) {
7257 /* Fill in the client's session ID if doing a stateless resume.
7258 * (When doing stateless resumes, server echos client's SessionID.)
7260 sid = ss->sec.ci.sid;
7261 PORT_Assert(sid != NULL); /* Should have already been filled in.*/
7263 if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
7264 sid->u.ssl3.sessionIDLength = sidBytes.len;
7265 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
7267 sid->u.ssl3.sessionIDLength = sidBytes.len;
7269 sid->u.ssl3.sessionIDLength = 0;
7271 ss->sec.ci.sid = NULL;
7274 /* We only send a session ticket extension if the client supports
7275 * the extension and we are unable to do either a stateful or
7278 * TODO: send a session ticket if performing a stateful
7279 * resumption. (As per RFC4507, a server may issue a session
7280 * ticket while doing a (stateless or stateful) session resume,
7281 * but OpenSSL-0.9.8g does not accept session tickets while
7284 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) {
7285 ssl3_RegisterServerHelloExtensionSender(ss,
7286 ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn);
7290 /* We've found a session cache entry for this client.
7291 * Now, if we're going to require a client-auth cert,
7292 * and we don't already have this client's cert in the session cache,
7293 * and this is the first handshake on this connection (not a redo),
7294 * then drop this old cache entry and start a new session.
7296 if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
7297 ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
7298 (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
7299 ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE)
7300 && !ss->firstHsDone))) {
7302 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
7303 if (ss->sec.uncache)
7304 ss->sec.uncache(sid);
7310 #ifdef NSS_ENABLE_ECC
7311 /* Disable any ECC cipher suites for which we have no cert. */
7312 ssl3_FilterECCipherSuitesByServerCerts(ss);
7316 ssl3_DisableNonDTLSSuites(ss);
7320 /* Look for a matching cipher suite. */
7321 j = ssl3_config_match_init(ss);
7322 if (j <= 0) { /* no ciphers are working/supported by PK11 */
7323 errCode = PORT_GetError(); /* error code is already set. */
7328 /* If we already have a session for this client, be sure to pick the
7329 ** same cipher suite and compression method we picked before.
7330 ** This is not a loop, despite appearances.
7333 ssl3CipherSuiteCfg *suite;
7335 /* Check that the cached compression method is still enabled. */
7336 if (!compressionEnabled(ss, sid->u.ssl3.compression))
7339 /* Check that the cached compression method is in the client's list */
7340 for (i = 0; i < comps.len; i++) {
7341 if (comps.data[i] == sid->u.ssl3.compression)
7347 suite = ss->cipherSuites;
7348 /* Find the entry for the cipher suite used in the cached session. */
7349 for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
7350 if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
7357 /* Double check that the cached cipher suite is still enabled,
7358 * implemented, and allowed by policy. Might have been disabled.
7359 * The product policy won't change during the process lifetime.
7360 * Implemented ("isPresent") shouldn't change for servers.
7362 if (!config_match(suite, ss->ssl3.policy, PR_TRUE))
7365 if (!suite->enabled)
7368 /* Double check that the cached cipher suite is in the client's list */
7369 for (i = 0; i + 1 < suites.len; i += 2) {
7370 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
7371 if (suite_i == suite->cipher_suite) {
7372 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
7373 ss->ssl3.hs.suite_def =
7374 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
7376 /* Use the cached compression method. */
7377 ss->ssl3.hs.compression = sid->u.ssl3.compression;
7378 goto compression_found;
7383 /* START A NEW SESSION */
7386 /* Look for a matching cipher suite. */
7387 j = ssl3_config_match_init(ss);
7388 if (j <= 0) { /* no ciphers are working/supported by PK11 */
7389 errCode = PORT_GetError(); /* error code is already set. */
7394 /* Select a cipher suite.
7396 ** NOTE: This suite selection algorithm should be the same as the one in
7397 ** ssl3_HandleV2ClientHello().
7399 ** If TLS 1.0 is enabled, we could handle the case where the client
7400 ** offered TLS 1.1 but offered only export cipher suites by choosing TLS
7401 ** 1.0 and selecting one of those export cipher suites. However, a secure
7402 ** TLS 1.1 client should not have export cipher suites enabled at all,
7403 ** and a TLS 1.1 client should definitely not be offering *only* export
7404 ** cipher suites. Therefore, we refuse to negotiate export cipher suites
7405 ** with any client that indicates support for TLS 1.1 or higher when we
7406 ** (the server) have TLS 1.1 support enabled.
7408 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
7409 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
7410 if (!config_match(suite, ss->ssl3.policy, PR_TRUE) ||
7411 !ssl3_CipherSuiteAllowedForVersion(suite->cipher_suite,
7415 for (i = 0; i + 1 < suites.len; i += 2) {
7416 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
7417 if (suite_i == suite->cipher_suite) {
7418 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
7419 ss->ssl3.hs.suite_def =
7420 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
7425 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
7429 /* Look for a matching compression algorithm. */
7430 for (i = 0; i < comps.len; i++) {
7431 if (!compressionEnabled(ss, comps.data[i]))
7433 for (j = 0; j < compressionMethodsCount; j++) {
7434 if (comps.data[i] == compressions[j]) {
7435 ss->ssl3.hs.compression =
7436 (SSLCompressionMethod)compressions[j];
7437 goto compression_found;
7441 errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
7442 /* null compression must be supported */
7449 ss->sec.send = ssl3_SendApplicationData;
7451 /* If there are any failures while processing the old sid,
7452 * we don't consider them to be errors. Instead, We just behave
7453 * as if the client had sent us no sid to begin with, and make a new one.
7455 if (sid != NULL) do {
7456 ssl3CipherSpec *pwSpec;
7457 SECItem wrappedMS; /* wrapped key */
7459 if (sid->version != ss->version ||
7460 sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite ||
7461 sid->u.ssl3.compression != ss->ssl3.hs.compression) {
7462 break; /* not an error */
7465 if (ss->sec.ci.sid) {
7466 if (ss->sec.uncache)
7467 ss->sec.uncache(ss->sec.ci.sid);
7468 PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */
7469 if (ss->sec.ci.sid != sid) {
7470 ssl_FreeSID(ss->sec.ci.sid);
7472 ss->sec.ci.sid = NULL;
7474 /* we need to resurrect the master secret.... */
7476 ssl_GetSpecWriteLock(ss); haveSpecWriteLock = PR_TRUE;
7477 pwSpec = ss->ssl3.pwSpec;
7478 if (sid->u.ssl3.keys.msIsWrapped) {
7479 PK11SymKey * wrapKey; /* wrapping key */
7480 CK_FLAGS keyFlags = 0;
7481 #ifndef NO_PKCS11_BYPASS
7482 if (ss->opt.bypassPKCS11) {
7483 /* we cannot restart a non-bypass session in a
7490 wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType,
7491 sid->u.ssl3.masterWrapMech,
7494 /* we have a SID cache entry, but no wrapping key for it??? */
7498 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
7499 keyFlags = CKF_SIGN | CKF_VERIFY;
7502 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
7503 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
7505 /* unwrap the master secret. */
7506 pwSpec->master_secret =
7507 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
7508 NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
7509 CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
7510 PK11_FreeSymKey(wrapKey);
7511 if (pwSpec->master_secret == NULL) {
7512 break; /* not an error */
7514 #ifndef NO_PKCS11_BYPASS
7515 } else if (ss->opt.bypassPKCS11) {
7516 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
7517 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
7518 memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
7519 pwSpec->msItem.data = pwSpec->raw_master_secret;
7520 pwSpec->msItem.len = wrappedMS.len;
7523 /* We CAN restart a bypass session in a non-bypass socket. */
7524 /* need to import the raw master secret to session object */
7525 PK11SlotInfo * slot;
7526 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
7527 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
7528 slot = PK11_GetInternalSlot();
7529 pwSpec->master_secret =
7530 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
7531 PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS,
7533 PK11_FreeSlot(slot);
7534 if (pwSpec->master_secret == NULL) {
7535 break; /* not an error */
7538 ss->sec.ci.sid = sid;
7539 if (sid->peerCert != NULL) {
7540 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
7544 * Old SID passed all tests, so resume this old session.
7546 * XXX make sure compression still matches
7548 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_hits );
7549 if (ss->statelessResume)
7550 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_stateless_resumes );
7551 ss->ssl3.hs.isResuming = PR_TRUE;
7553 ss->sec.authAlgorithm = sid->authAlgorithm;
7554 ss->sec.authKeyBits = sid->authKeyBits;
7555 ss->sec.keaType = sid->keaType;
7556 ss->sec.keaKeyBits = sid->keaKeyBits;
7558 /* server sids don't remember the server cert we previously sent,
7559 ** but they do remember the kea type we originally used, so we
7560 ** can locate it again, provided that the current ssl socket
7561 ** has had its server certs configured the same as the previous one.
7564 CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert);
7566 /* Copy cached name in to pending spec */
7568 sid->version > SSL_LIBRARY_VERSION_3_0 &&
7569 sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
7570 /* Set server name from sid */
7571 SECItem *sidName = &sid->u.ssl3.srvName;
7572 SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName;
7573 if (pwsName->data) {
7574 SECITEM_FreeItem(pwsName, PR_FALSE);
7576 rv = SECITEM_CopyItem(NULL, pwsName, sidName);
7577 if (rv != SECSuccess) {
7578 errCode = PORT_GetError();
7579 desc = internal_error;
7584 /* Clean up sni name array */
7585 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) &&
7586 ss->xtnData.sniNameArr) {
7587 PORT_Free(ss->xtnData.sniNameArr);
7588 ss->xtnData.sniNameArr = NULL;
7589 ss->xtnData.sniNameArrSize = 0;
7592 ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE;
7594 rv = ssl3_SendServerHello(ss);
7595 if (rv != SECSuccess) {
7596 errCode = PORT_GetError();
7600 if (haveSpecWriteLock) {
7601 ssl_ReleaseSpecWriteLock(ss);
7602 haveSpecWriteLock = PR_FALSE;
7605 /* NULL value for PMS signifies re-use of the old MS */
7606 rv = ssl3_InitPendingCipherSpec(ss, NULL);
7607 if (rv != SECSuccess) {
7608 errCode = PORT_GetError();
7612 rv = ssl3_SendChangeCipherSpecs(ss);
7613 if (rv != SECSuccess) {
7614 errCode = PORT_GetError();
7617 rv = ssl3_SendFinished(ss, 0);
7618 ss->ssl3.hs.ws = wait_change_cipher;
7619 if (rv != SECSuccess) {
7620 errCode = PORT_GetError();
7624 if (haveXmitBufLock) {
7625 ssl_ReleaseXmitBufLock(ss);
7626 haveXmitBufLock = PR_FALSE;
7632 if (haveSpecWriteLock) {
7633 ssl_ReleaseSpecWriteLock(ss);
7634 haveSpecWriteLock = PR_FALSE;
7637 if (sid) { /* we had a sid, but it's no longer valid, free it */
7638 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
7639 if (ss->sec.uncache)
7640 ss->sec.uncache(sid);
7644 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
7646 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
7648 if (ss->sniSocketConfig) do { /* not a loop */
7649 ret = SSL_SNI_SEND_ALERT;
7650 /* If extension is negotiated, the len of names should > 0. */
7651 if (ss->xtnData.sniNameArrSize) {
7652 /* Calling client callback to reconfigure the socket. */
7653 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
7654 ss->xtnData.sniNameArr,
7655 ss->xtnData.sniNameArrSize,
7656 ss->sniSocketConfigArg);
7658 if (ret <= SSL_SNI_SEND_ALERT) {
7659 /* Application does not know the name or was not able to
7660 * properly reconfigure the socket. */
7661 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7662 desc = unrecognized_name;
7664 } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
7665 SECStatus rv = SECSuccess;
7666 SECItem * cwsName, *pwsName;
7668 ssl_GetSpecWriteLock(ss); /*******************************/
7669 pwsName = &ss->ssl3.pwSpec->srvVirtName;
7670 cwsName = &ss->ssl3.cwSpec->srvVirtName;
7671 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
7672 /* not allow name change on the 2d HS */
7673 if (ss->firstHsDone) {
7674 if (ssl3_ServerNameCompare(pwsName, cwsName)) {
7675 ssl_ReleaseSpecWriteLock(ss); /******************/
7676 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7677 desc = handshake_failure;
7678 ret = SSL_SNI_SEND_ALERT;
7683 if (pwsName->data) {
7684 SECITEM_FreeItem(pwsName, PR_FALSE);
7686 if (cwsName->data) {
7687 rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
7689 ssl_ReleaseSpecWriteLock(ss); /**************************/
7690 if (rv != SECSuccess) {
7691 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
7692 desc = internal_error;
7693 ret = SSL_SNI_SEND_ALERT;
7696 } else if (ret < ss->xtnData.sniNameArrSize) {
7697 /* Application has configured new socket info. Lets check it
7698 * and save the name. */
7700 SECItem * name = &ss->xtnData.sniNameArr[ret];
7701 int configedCiphers;
7704 /* get rid of the old name and save the newly picked. */
7705 /* This code is protected by ssl3HandshakeLock. */
7706 ssl_GetSpecWriteLock(ss); /*******************************/
7707 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
7708 /* not allow name change on the 2d HS */
7709 if (ss->firstHsDone) {
7710 SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName;
7711 if (ssl3_ServerNameCompare(name, cwsName)) {
7712 ssl_ReleaseSpecWriteLock(ss); /******************/
7713 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7714 desc = handshake_failure;
7715 ret = SSL_SNI_SEND_ALERT;
7720 pwsName = &ss->ssl3.pwSpec->srvVirtName;
7721 if (pwsName->data) {
7722 SECITEM_FreeItem(pwsName, PR_FALSE);
7724 rv = SECITEM_CopyItem(NULL, pwsName, name);
7725 ssl_ReleaseSpecWriteLock(ss); /***************************/
7726 if (rv != SECSuccess) {
7727 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
7728 desc = internal_error;
7729 ret = SSL_SNI_SEND_ALERT;
7732 configedCiphers = ssl3_config_match_init(ss);
7733 if (configedCiphers <= 0) {
7734 /* no ciphers are working/supported */
7735 errCode = PORT_GetError();
7736 desc = handshake_failure;
7737 ret = SSL_SNI_SEND_ALERT;
7740 /* Need to tell the client that application has picked
7741 * the name from the offered list and reconfigured the socket.
7743 ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn,
7744 ssl3_SendServerNameXtn);
7746 /* Callback returned index outside of the boundary. */
7747 PORT_Assert(ret < ss->xtnData.sniNameArrSize);
7748 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
7749 desc = internal_error;
7750 ret = SSL_SNI_SEND_ALERT;
7754 /* Free sniNameArr. The data that each SECItem in the array
7755 * points into is the data from the input buffer "b". It will
7756 * not be available outside the scope of this or it's child
7758 if (ss->xtnData.sniNameArr) {
7759 PORT_Free(ss->xtnData.sniNameArr);
7760 ss->xtnData.sniNameArr = NULL;
7761 ss->xtnData.sniNameArrSize = 0;
7763 if (ret <= SSL_SNI_SEND_ALERT) {
7764 /* desc and errCode should be set. */
7768 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
7769 else if (ss->firstHsDone) {
7770 /* Check that we don't have the name is current spec
7771 * if this extension was not negotiated on the 2d hs. */
7772 PRBool passed = PR_TRUE;
7773 ssl_GetSpecReadLock(ss); /*******************************/
7774 if (ss->ssl3.cwSpec->srvVirtName.data) {
7777 ssl_ReleaseSpecReadLock(ss); /***************************/
7779 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7780 desc = handshake_failure;
7786 sid = ssl3_NewSessionID(ss, PR_TRUE);
7788 errCode = PORT_GetError();
7789 goto loser; /* memory error is set. */
7791 ss->sec.ci.sid = sid;
7793 ss->ssl3.hs.isResuming = PR_FALSE;
7794 ssl_GetXmitBufLock(ss);
7795 rv = ssl3_SendServerHelloSequence(ss);
7796 ssl_ReleaseXmitBufLock(ss);
7797 if (rv != SECSuccess) {
7798 errCode = PORT_GetError();
7802 if (haveXmitBufLock) {
7803 ssl_ReleaseXmitBufLock(ss);
7804 haveXmitBufLock = PR_FALSE;
7810 if (haveSpecWriteLock) {
7811 ssl_ReleaseSpecWriteLock(ss);
7812 haveSpecWriteLock = PR_FALSE;
7814 (void)SSL3_SendAlert(ss, level, desc);
7817 if (haveSpecWriteLock) {
7818 ssl_ReleaseSpecWriteLock(ss);
7819 haveSpecWriteLock = PR_FALSE;
7822 if (haveXmitBufLock) {
7823 ssl_ReleaseXmitBufLock(ss);
7824 haveXmitBufLock = PR_FALSE;
7827 PORT_SetError(errCode);
7832 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
7833 * in asking to use the V3 handshake.
7834 * Called from ssl2_HandleClientHelloMessage() in sslcon.c
7837 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length)
7839 sslSessionID * sid = NULL;
7840 unsigned char * suites;
7841 unsigned char * random;
7842 SSL3ProtocolVersion version;
7849 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
7850 SSL3AlertDescription desc = handshake_failure;
7852 SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
7854 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
7856 ssl_GetSSL3HandshakeLock(ss);
7858 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
7860 rv = ssl3_InitState(ss);
7861 if (rv != SECSuccess) {
7862 ssl_ReleaseSSL3HandshakeLock(ss);
7863 return rv; /* ssl3_InitState has set the error code. */
7865 rv = ssl3_RestartHandshakeHashes(ss);
7866 if (rv != SECSuccess) {
7867 ssl_ReleaseSSL3HandshakeLock(ss);
7871 if (ss->ssl3.hs.ws != wait_client_hello) {
7872 desc = unexpected_message;
7873 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
7874 goto loser; /* alert_loser */
7877 version = (buffer[1] << 8) | buffer[2];
7878 suite_length = (buffer[3] << 8) | buffer[4];
7879 sid_length = (buffer[5] << 8) | buffer[6];
7880 rand_length = (buffer[7] << 8) | buffer[8];
7881 ss->clientHelloVersion = version;
7883 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
7884 if (rv != SECSuccess) {
7885 /* send back which ever alert client will understand. */
7886 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version : handshake_failure;
7887 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
7891 rv = ssl3_InitHandshakeHashes(ss);
7892 if (rv != SECSuccess) {
7893 desc = internal_error;
7894 errCode = PORT_GetError();
7898 /* if we get a non-zero SID, just ignore it. */
7900 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) {
7901 SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
7902 SSL_GETPID(), ss->fd, length,
7903 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length +
7905 goto loser; /* malformed */ /* alert_loser */
7908 suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
7909 random = suites + suite_length + sid_length;
7911 if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
7912 rand_length > SSL_MAX_CHALLENGE_BYTES) {
7913 goto loser; /* malformed */ /* alert_loser */
7916 PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
7918 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
7920 &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length],
7921 random, rand_length);
7923 PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0],
7924 SSL3_RANDOM_LENGTH));
7925 #ifdef NSS_ENABLE_ECC
7926 /* Disable any ECC cipher suites for which we have no cert. */
7927 ssl3_FilterECCipherSuitesByServerCerts(ss);
7929 i = ssl3_config_match_init(ss);
7931 errCode = PORT_GetError(); /* error code is already set. */
7935 /* Select a cipher suite.
7937 ** NOTE: This suite selection algorithm should be the same as the one in
7938 ** ssl3_HandleClientHello().
7940 ** See the comments about export cipher suites in ssl3_HandleClientHello().
7942 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
7943 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
7944 if (!config_match(suite, ss->ssl3.policy, PR_TRUE) ||
7945 !ssl3_CipherSuiteAllowedForVersion(suite->cipher_suite,
7949 for (i = 0; i+2 < suite_length; i += 3) {
7950 PRUint32 suite_i = (suites[i] << 16)|(suites[i+1] << 8)|suites[i+2];
7951 if (suite_i == suite->cipher_suite) {
7952 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
7953 ss->ssl3.hs.suite_def =
7954 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
7959 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
7964 /* Look for the SCSV, and if found, treat it just like an empty RI
7965 * extension by processing a local copy of an empty RI extension.
7967 for (i = 0; i+2 < suite_length; i += 3) {
7968 PRUint32 suite_i = (suites[i] << 16) | (suites[i+1] << 8) | suites[i+2];
7969 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
7970 SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
7971 PRUint32 L2 = sizeof emptyRIext;
7972 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
7977 if (ss->opt.requireSafeNegotiation &&
7978 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7979 desc = handshake_failure;
7980 errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
7984 ss->ssl3.hs.compression = ssl_compression_null;
7985 ss->sec.send = ssl3_SendApplicationData;
7987 /* we don't even search for a cache hit here. It's just a miss. */
7988 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
7989 sid = ssl3_NewSessionID(ss, PR_TRUE);
7991 errCode = PORT_GetError();
7992 goto loser; /* memory error is set. */
7994 ss->sec.ci.sid = sid;
7995 /* do not worry about memory leak of sid since it now belongs to ci */
7997 /* We have to update the handshake hashes before we can send stuff */
7998 rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
7999 if (rv != SECSuccess) {
8000 errCode = PORT_GetError();
8004 ssl_GetXmitBufLock(ss);
8005 rv = ssl3_SendServerHelloSequence(ss);
8006 ssl_ReleaseXmitBufLock(ss);
8007 if (rv != SECSuccess) {
8008 errCode = PORT_GetError();
8012 /* XXX_1 The call stack to here is:
8013 * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here.
8014 * ssl2_HandleClientHelloMessage returns whatever we return here.
8015 * ssl_Do1stHandshake will continue looping if it gets back either
8016 * SECSuccess or SECWouldBlock.
8017 * SECSuccess is preferable here. See XXX_1 in sslgathr.c.
8019 ssl_ReleaseSSL3HandshakeLock(ss);
8023 SSL3_SendAlert(ss, alert_fatal, desc);
8025 ssl_ReleaseSSL3HandshakeLock(ss);
8026 PORT_SetError(errCode);
8030 /* The negotiated version number has been already placed in ss->version.
8032 ** Called from: ssl3_HandleClientHello (resuming session),
8033 ** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session),
8034 ** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
8037 ssl3_SendServerHello(sslSocket *ss)
8041 PRUint32 maxBytes = 65535;
8043 PRInt32 extensions_len = 0;
8044 SSL3ProtocolVersion version;
8046 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
8049 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8050 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8053 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
8055 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
8056 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8060 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0));
8062 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) {
8063 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8068 sid = ss->sec.ci.sid;
8070 extensions_len = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes,
8071 &ss->xtnData.serverSenders[0]);
8072 if (extensions_len > 0)
8073 extensions_len += 2; /* Add sizeof total extension length */
8075 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 +
8076 ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength) +
8077 sizeof(ssl3CipherSuite) + 1 + extensions_len;
8078 rv = ssl3_AppendHandshakeHeader(ss, server_hello, length);
8079 if (rv != SECSuccess) {
8080 return rv; /* err set by AppendHandshake. */
8084 version = dtls_TLSVersionToDTLSVersion(ss->version);
8086 version = ss->version;
8089 rv = ssl3_AppendHandshakeNumber(ss, version, 2);
8090 if (rv != SECSuccess) {
8091 return rv; /* err set by AppendHandshake. */
8093 rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random);
8094 if (rv != SECSuccess) {
8095 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
8098 rv = ssl3_AppendHandshake(
8099 ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
8100 if (rv != SECSuccess) {
8101 return rv; /* err set by AppendHandshake. */
8105 rv = ssl3_AppendHandshakeVariable(
8106 ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
8108 rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
8109 if (rv != SECSuccess) {
8110 return rv; /* err set by AppendHandshake. */
8113 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2);
8114 if (rv != SECSuccess) {
8115 return rv; /* err set by AppendHandshake. */
8117 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1);
8118 if (rv != SECSuccess) {
8119 return rv; /* err set by AppendHandshake. */
8121 if (extensions_len) {
8124 extensions_len -= 2;
8125 rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2);
8126 if (rv != SECSuccess)
8127 return rv; /* err set by ssl3_SetupPendingCipherSpec */
8128 sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len,
8129 &ss->xtnData.serverSenders[0]);
8130 PORT_Assert(sent_len == extensions_len);
8131 if (sent_len != extensions_len) {
8133 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
8137 rv = ssl3_SetupPendingCipherSpec(ss);
8138 if (rv != SECSuccess) {
8139 return rv; /* err set by ssl3_SetupPendingCipherSpec */
8145 /* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing
8146 * elements of the handshake. (The negotiated cipher suite determines the
8147 * signature algorithm.) Prior to TLS 1.2, the MD5/SHA1 combination is always
8148 * used. With TLS 1.2, a client may advertise its support for signature and
8149 * hash combinations. */
8151 ssl3_PickSignatureHashAlgorithm(sslSocket *ss,
8152 SSL3SignatureAndHashAlgorithm* out)
8154 TLSSignatureAlgorithm sigAlg;
8156 /* hashPreference expresses our preferences for hash algorithms, most
8157 * preferable first. */
8158 static const PRUint8 hashPreference[] = {
8165 switch (ss->ssl3.hs.kea_def->kea) {
8167 case kea_rsa_export:
8168 case kea_rsa_export_1024:
8170 case kea_dh_rsa_export:
8172 case kea_dhe_rsa_export:
8176 sigAlg = tls_sig_rsa;
8179 case kea_dh_dss_export:
8181 case kea_dhe_dss_export:
8182 sigAlg = tls_sig_dsa;
8184 case kea_ecdh_ecdsa:
8185 case kea_ecdhe_ecdsa:
8186 sigAlg = tls_sig_ecdsa;
8189 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
8192 out->sigAlg = sigAlg;
8194 if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) {
8195 /* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and
8197 out->hashAlg = SEC_OID_UNKNOWN;
8201 if (ss->ssl3.hs.numClientSigAndHash == 0) {
8202 /* If the client didn't provide any signature_algorithms extension then
8203 * we can assume that they support SHA-1:
8204 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
8205 out->hashAlg = SEC_OID_SHA1;
8209 for (i = 0; i < PR_ARRAY_SIZE(hashPreference); i++) {
8210 for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) {
8211 const SSL3SignatureAndHashAlgorithm* sh =
8212 &ss->ssl3.hs.clientSigAndHash[j];
8213 if (sh->sigAlg == sigAlg && sh->hashAlg == hashPreference[i]) {
8214 out->hashAlg = sh->hashAlg;
8220 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
8226 ssl3_SendServerKeyExchange(sslSocket *ss)
8228 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
8229 SECStatus rv = SECFailure;
8232 SECItem signed_hash = {siBuffer, NULL, 0};
8234 SECKEYPublicKey * sdPub; /* public key for step-down */
8235 SSL3SignatureAndHashAlgorithm sigAndHash;
8237 SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
8238 SSL_GETPID(), ss->fd));
8240 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8241 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8243 if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) {
8247 switch (kea_def->exchKeyType) {
8249 /* Perform SSL Step-Down here. */
8250 sdPub = ss->stepDownKeyPair->pubKey;
8251 PORT_Assert(sdPub != NULL);
8253 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
8256 rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg,
8257 sdPub->u.rsa.modulus,
8258 sdPub->u.rsa.publicExponent,
8259 &ss->ssl3.hs.client_random,
8260 &ss->ssl3.hs.server_random,
8261 &hashes, ss->opt.bypassPKCS11);
8262 if (rv != SECSuccess) {
8263 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
8267 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
8268 rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY,
8269 &signed_hash, isTLS);
8270 if (rv != SECSuccess) {
8271 goto loser; /* ssl3_SignHashes has set err. */
8273 if (signed_hash.data == NULL) {
8274 /* how can this happen and rv == SECSuccess ?? */
8275 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
8278 length = 2 + sdPub->u.rsa.modulus.len +
8279 2 + sdPub->u.rsa.publicExponent.len +
8280 2 + signed_hash.len;
8282 rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length);
8283 if (rv != SECSuccess) {
8284 goto loser; /* err set by AppendHandshake. */
8287 rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data,
8288 sdPub->u.rsa.modulus.len, 2);
8289 if (rv != SECSuccess) {
8290 goto loser; /* err set by AppendHandshake. */
8293 rv = ssl3_AppendHandshakeVariable(
8294 ss, sdPub->u.rsa.publicExponent.data,
8295 sdPub->u.rsa.publicExponent.len, 2);
8296 if (rv != SECSuccess) {
8297 goto loser; /* err set by AppendHandshake. */
8300 if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
8301 rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
8302 if (rv != SECSuccess) {
8303 goto loser; /* err set by AppendHandshake. */
8307 rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
8308 signed_hash.len, 2);
8309 if (rv != SECSuccess) {
8310 goto loser; /* err set by AppendHandshake. */
8312 PORT_Free(signed_hash.data);
8315 #ifdef NSS_ENABLE_ECC
8317 rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash);
8320 #endif /* NSS_ENABLE_ECC */
8325 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
8329 if (signed_hash.data != NULL)
8330 PORT_Free(signed_hash.data);
8336 ssl3_SendCertificateRequest(sslSocket *ss)
8340 CERTDistNames *ca_list;
8341 const PRUint8 *certTypes;
8342 const PRUint8 *sigAlgs;
8343 SECItem * names = NULL;
8349 int certTypesLength;
8352 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
8353 SSL_GETPID(), ss->fd));
8355 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8356 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8358 isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
8360 /* ssl3.ca_list is initialized to NULL, and never changed. */
8361 ca_list = ss->ssl3.ca_list;
8363 ca_list = ssl3_server_ca_list;
8366 if (ca_list != NULL) {
8367 names = ca_list->names;
8368 nnames = ca_list->nnames;
8371 for (i = 0, name = names; i < nnames; i++, name++) {
8372 calen += 2 + name->len;
8375 certTypes = certificate_types;
8376 certTypesLength = sizeof certificate_types;
8377 sigAlgs = supported_signature_algorithms;
8378 sigAlgsLength = sizeof supported_signature_algorithms;
8380 length = 1 + certTypesLength + 2 + calen;
8382 length += 2 + sigAlgsLength;
8385 rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length);
8386 if (rv != SECSuccess) {
8387 return rv; /* err set by AppendHandshake. */
8389 rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
8390 if (rv != SECSuccess) {
8391 return rv; /* err set by AppendHandshake. */
8394 rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2);
8395 if (rv != SECSuccess) {
8396 return rv; /* err set by AppendHandshake. */
8399 rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
8400 if (rv != SECSuccess) {
8401 return rv; /* err set by AppendHandshake. */
8403 for (i = 0, name = names; i < nnames; i++, name++) {
8404 rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
8405 if (rv != SECSuccess) {
8406 return rv; /* err set by AppendHandshake. */
8414 ssl3_SendServerHelloDone(sslSocket *ss)
8418 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
8419 SSL_GETPID(), ss->fd));
8421 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8422 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8424 rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0);
8425 if (rv != SECSuccess) {
8426 return rv; /* err set by AppendHandshake. */
8428 rv = ssl3_FlushHandshake(ss, 0);
8429 if (rv != SECSuccess) {
8430 return rv; /* error code set by ssl3_FlushHandshake */
8435 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
8436 * ssl3 Certificate Verify message
8437 * Caller must hold Handshake and RecvBuf locks.
8440 ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
8443 SECItem signed_hash = {siBuffer, NULL, 0};
8445 int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
8446 SSL3AlertDescription desc = handshake_failure;
8447 PRBool isTLS, isTLS12;
8448 SSL3SignatureAndHashAlgorithm sigAndHash;
8450 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
8451 SSL_GETPID(), ss->fd));
8452 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8453 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8455 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
8456 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
8458 if (ss->ssl3.hs.ws != wait_cert_verify || ss->sec.peerCert == NULL) {
8459 desc = unexpected_message;
8460 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
8465 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
8467 if (rv != SECSuccess) {
8468 goto loser; /* malformed or unsupported. */
8470 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
8471 &sigAndHash, ss->sec.peerCert);
8472 if (rv != SECSuccess) {
8473 errCode = PORT_GetError();
8474 desc = decrypt_error;
8478 /* We only support CertificateVerify messages that use the handshake
8480 if (sigAndHash.hashAlg != hashes->hashAlg) {
8481 errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM;
8482 desc = decrypt_error;
8487 rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
8488 if (rv != SECSuccess) {
8489 goto loser; /* malformed. */
8492 /* XXX verify that the key & kea match */
8493 rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash,
8494 isTLS, ss->pkcs11PinArg);
8495 if (rv != SECSuccess) {
8496 errCode = PORT_GetError();
8497 desc = isTLS ? decrypt_error : handshake_failure;
8501 signed_hash.data = NULL;
8504 desc = isTLS ? decode_error : illegal_parameter;
8505 goto alert_loser; /* malformed */
8507 ss->ssl3.hs.ws = wait_change_cipher;
8511 SSL3_SendAlert(ss, alert_fatal, desc);
8513 PORT_SetError(errCode);
8518 /* find a slot that is able to generate a PMS and wrap it with RSA.
8519 * Then generate and return the PMS.
8520 * If the serverKeySlot parameter is non-null, this function will use
8521 * that slot to do the job, otherwise it will find a slot.
8523 * Called from ssl3_DeriveConnectionKeysPKCS11() (above)
8524 * sendRSAClientKeyExchange() (above)
8525 * ssl3_HandleRSAClientKeyExchange() (below)
8526 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
8529 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
8530 PK11SlotInfo * serverKeySlot)
8532 PK11SymKey * pms = NULL;
8533 PK11SlotInfo * slot = serverKeySlot;
8534 void * pwArg = ss->pkcs11PinArg;
8537 CK_MECHANISM_TYPE mechanism_array[3];
8539 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8542 SSLCipherAlgorithm calg;
8543 /* The specReadLock would suffice here, but we cannot assert on
8544 ** read locks. Also, all the callers who call with a non-null
8545 ** slot already hold the SpecWriteLock.
8547 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
8548 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
8550 calg = spec->cipher_def->calg;
8551 PORT_Assert(alg2Mech[calg].calg == calg);
8553 /* First get an appropriate slot. */
8554 mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
8555 mechanism_array[1] = CKM_RSA_PKCS;
8556 mechanism_array[2] = alg2Mech[calg].cmech;
8558 slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
8560 /* can't find a slot with all three, find a slot with the minimum */
8561 slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
8563 PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
8564 return pms; /* which is NULL */
8569 /* Generate the pre-master secret ... */
8571 SSL3ProtocolVersion temp;
8573 temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
8574 version.major = MSB(temp);
8575 version.minor = LSB(temp);
8577 version.major = MSB(ss->clientHelloVersion);
8578 version.minor = LSB(ss->clientHelloVersion);
8581 param.data = (unsigned char *)&version;
8582 param.len = sizeof version;
8584 pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, ¶m, 0, pwArg);
8586 PK11_FreeSlot(slot);
8588 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
8593 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
8594 * return any indication of failure of the Client Key Exchange message,
8595 * where that failure is caused by the content of the client's message.
8596 * This function must not return SECFailure for any reason that is directly
8597 * or indirectly caused by the content of the client's encrypted PMS.
8598 * We must not send an alert and also not drop the connection.
8599 * Instead, we generate a random PMS. This will cause a failure
8600 * in the processing the finished message, which is exactly where
8601 * the failure must occur.
8603 * Called from ssl3_HandleClientKeyExchange
8606 ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
8609 SECKEYPrivateKey *serverKey)
8612 #ifndef NO_PKCS11_BYPASS
8613 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random;
8614 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random;
8615 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec;
8616 unsigned int outLen = 0;
8618 PRBool isTLS = PR_FALSE;
8621 unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH];
8622 SECItem pmsItem = {siBuffer, NULL, 0};
8624 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8625 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8626 PORT_Assert( ss->ssl3.prSpec == ss->ssl3.pwSpec );
8629 enc_pms.len = length;
8630 pmsItem.data = rsaPmsBuf;
8631 pmsItem.len = sizeof rsaPmsBuf;
8633 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
8635 kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len);
8637 PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
8640 if ((unsigned)kLen < enc_pms.len) {
8645 isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0);
8648 #ifndef NO_PKCS11_BYPASS
8649 if (ss->opt.bypassPKCS11) {
8650 /* TRIPLE BYPASS, get PMS directly from RSA decryption.
8651 * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer,
8652 * then, check for version rollback attack, then
8653 * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in
8654 * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with
8655 * ss and NULL, so that it will use the MS we've already derived here.
8658 rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen,
8659 sizeof rsaPmsBuf, enc_pms.data, enc_pms.len);
8660 if (rv != SECSuccess) {
8661 /* triple bypass failed. Let's try for a double bypass. */
8663 } else if (ss->opt.detectRollBack) {
8664 SSL3ProtocolVersion client_version =
8665 (rsaPmsBuf[0] << 8) | rsaPmsBuf[1];
8668 client_version = dtls_DTLSVersionToTLSVersion(client_version);
8671 if (client_version != ss->clientHelloVersion) {
8672 /* Version roll-back detected. ensure failure. */
8673 rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf);
8676 /* have PMS, build MS without PKCS11 */
8677 rv = ssl3_MasterKeyDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS,
8679 if (rv != SECSuccess) {
8680 pwSpec->msItem.data = pwSpec->raw_master_secret;
8681 pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH;
8682 PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len);
8684 rv = ssl3_InitPendingCipherSpec(ss, NULL);
8688 #ifndef NO_PKCS11_BYPASS
8692 * unwrap pms out of the incoming buffer
8693 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
8694 * the unwrap. Rather, it is the mechanism with which the
8695 * unwrapped pms will be used.
8697 pms = PK11_PubUnwrapSymKey(serverKey, &enc_pms,
8698 CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
8700 PRINT_BUF(60, (ss, "decrypted premaster secret:",
8701 PK11_GetKeyData(pms)->data,
8702 PK11_GetKeyData(pms)->len));
8704 /* unwrap failed. Generate a bogus PMS and carry on. */
8705 PK11SlotInfo * slot = PK11_GetSlotFromPrivateKey(serverKey);
8707 ssl_GetSpecWriteLock(ss);
8708 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
8709 ssl_ReleaseSpecWriteLock(ss);
8710 PK11_FreeSlot(slot);
8715 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
8719 /* This step will derive the MS from the PMS, among other things. */
8720 rv = ssl3_InitPendingCipherSpec(ss, pms);
8721 PK11_FreeSymKey(pms);
8724 if (rv != SECSuccess) {
8726 return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
8732 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
8733 * ssl3 ClientKeyExchange message from the remote client
8734 * Caller must hold Handshake and RecvBuf locks.
8737 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
8739 SECKEYPrivateKey *serverKey = NULL;
8741 const ssl3KEADef *kea_def;
8742 ssl3KeyPair *serverKeyPair = NULL;
8743 #ifdef NSS_ENABLE_ECC
8744 SECKEYPublicKey *serverPubKey = NULL;
8745 #endif /* NSS_ENABLE_ECC */
8747 SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
8748 SSL_GETPID(), ss->fd));
8750 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8751 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8753 if (ss->ssl3.hs.ws != wait_client_key) {
8754 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8755 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
8759 kea_def = ss->ssl3.hs.kea_def;
8761 if (ss->ssl3.hs.usedStepDownKey) {
8762 PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */
8763 && kea_def->exchKeyType == kt_rsa
8764 && ss->stepDownKeyPair != NULL);
8765 if (!kea_def->is_limited ||
8766 kea_def->exchKeyType != kt_rsa ||
8767 ss->stepDownKeyPair == NULL) {
8768 /* shouldn't happen, don't use step down if it does */
8771 serverKeyPair = ss->stepDownKeyPair;
8772 ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB;
8775 #ifdef NSS_ENABLE_ECC
8776 /* XXX Using SSLKEAType to index server certifiates
8777 * does not work for (EC)DHE ciphers. Until we have
8778 * an indexing mechanism general enough for all key
8779 * exchange algorithms, we'll need to deal with each
8782 if ((kea_def->kea == kea_ecdhe_rsa) ||
8783 (kea_def->kea == kea_ecdhe_ecdsa)) {
8784 if (ss->ephemeralECDHKeyPair != NULL) {
8785 serverKeyPair = ss->ephemeralECDHKeyPair;
8786 if (serverKeyPair->pubKey) {
8787 ss->sec.keaKeyBits =
8788 SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
8794 sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType;
8795 serverKeyPair = sc->serverKeyPair;
8796 ss->sec.keaKeyBits = sc->serverKeyBits;
8799 if (serverKeyPair) {
8800 serverKey = serverKeyPair->privKey;
8803 if (serverKey == NULL) {
8805 PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
8809 ss->sec.keaType = kea_def->exchKeyType;
8811 switch (kea_def->exchKeyType) {
8813 rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey);
8814 if (rv != SECSuccess) {
8816 return SECFailure; /* error code set */
8821 #ifdef NSS_ENABLE_ECC
8823 /* XXX We really ought to be able to store multiple
8824 * EC certs (a requirement if we wish to support both
8825 * ECDH-RSA and ECDH-ECDSA key exchanges concurrently).
8826 * When we make that change, we'll need an index other
8827 * than kt_ecdh to pick the right EC certificate.
8829 if (serverKeyPair) {
8830 serverPubKey = serverKeyPair->pubKey;
8832 if (serverPubKey == NULL) {
8833 /* XXX Is this the right error code? */
8834 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
8837 rv = ssl3_HandleECDHClientKeyExchange(ss, b, length,
8838 serverPubKey, serverKey);
8839 if (rv != SECSuccess) {
8840 return SECFailure; /* error code set */
8843 #endif /* NSS_ENABLE_ECC */
8846 (void) ssl3_HandshakeFailure(ss);
8847 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
8850 ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
8855 /* This is TLS's equivalent of sending a no_certificate alert. */
8857 ssl3_SendEmptyCertificate(sslSocket *ss)
8861 rv = ssl3_AppendHandshakeHeader(ss, certificate, 3);
8862 if (rv == SECSuccess) {
8863 rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
8865 return rv; /* error, if any, set by functions called above. */
8869 ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
8872 NewSessionTicket session_ticket;
8874 SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
8875 SSL_GETPID(), ss->fd));
8877 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
8878 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
8880 if (ss->ssl3.hs.ws != wait_new_session_ticket) {
8881 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8882 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
8886 session_ticket.received_timestamp = ssl_Time();
8888 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
8889 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
8892 session_ticket.ticket_lifetime_hint =
8893 (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length);
8895 rv = ssl3_ConsumeHandshakeVariable(ss, &session_ticket.ticket, 2,
8897 if (length != 0 || rv != SECSuccess) {
8898 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
8899 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
8900 return SECFailure; /* malformed */
8903 rv = ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &session_ticket);
8904 if (rv != SECSuccess) {
8905 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
8906 PORT_SetError(SSL_ERROR_INTERNAL_ERROR_ALERT);
8909 ss->ssl3.hs.ws = wait_change_cipher;
8914 static PRInt32 connNum = 0;
8917 get_fake_cert(SECItem *pCertItem, int *pIndex)
8923 const char *extension;
8925 PRInt32 numBytes = 0;
8930 pCertItem->data = 0;
8931 if ((testdir = PR_GetEnv("NISCC_TEST")) == NULL) {
8934 *pIndex = (NULL != strstr(testdir, "root"));
8935 extension = (strstr(testdir, "simple") ? "" : ".der");
8936 fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1;
8937 if ((startat = PR_GetEnv("START_AT")) != NULL) {
8938 fileNum += atoi(startat);
8940 if ((stopat = PR_GetEnv("STOP_AT")) != NULL &&
8941 fileNum >= atoi(stopat)) {
8945 sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension);
8946 cf = PR_Open(cfn, PR_RDONLY, 0);
8950 prStatus = PR_GetOpenFileInfo(cf, &info);
8951 if (prStatus != PR_SUCCESS) {
8955 pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
8957 numBytes = PR_Read(cf, pCertItem->data, info.size);
8960 if (numBytes != info.size) {
8961 SECITEM_FreeItem(pCertItem, PR_FALSE);
8962 PORT_SetError(SEC_ERROR_IO);
8965 fprintf(stderr, "using %s\n", cfn);
8969 fprintf(stderr, "failed to use %s\n", cfn);
8976 * Used by both client and server.
8977 * Called from HandleServerHelloDone and from SendServerHelloSequence.
8980 ssl3_SendCertificate(sslSocket *ss)
8983 CERTCertificateList *certChain;
8986 SSL3KEAType certIndex;
8992 SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
8993 SSL_GETPID(), ss->fd));
8995 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8996 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8998 if (ss->sec.localCert)
8999 CERT_DestroyCertificate(ss->sec.localCert);
9000 if (ss->sec.isServer) {
9001 sslServerCerts * sc = NULL;
9003 /* XXX SSLKEAType isn't really a good choice for
9004 * indexing certificates (it breaks when we deal
9005 * with (EC)DHE-* cipher suites. This hack ensures
9006 * the RSA cert is picked for (EC)DHE-RSA.
9007 * Revisit this when we add server side support
9008 * for ECDHE-ECDSA or client-side authentication
9009 * using EC certificates.
9011 if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
9012 (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
9015 certIndex = ss->ssl3.hs.kea_def->exchKeyType;
9017 sc = ss->serverCerts + certIndex;
9018 certChain = sc->serverCertChain;
9019 ss->sec.authKeyBits = sc->serverKeyBits;
9020 ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
9021 ss->sec.localCert = CERT_DupCertificate(sc->serverCert);
9023 certChain = ss->ssl3.clientCertChain;
9024 ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
9028 rv = get_fake_cert(&fakeCert, &ndex);
9032 for (i = 0; i < certChain->len; i++) {
9034 if (fakeCert.len > 0 && i == ndex) {
9035 len += fakeCert.len + 3;
9037 len += certChain->certs[i].len + 3;
9040 len += certChain->certs[i].len + 3;
9045 rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3);
9046 if (rv != SECSuccess) {
9047 return rv; /* err set by AppendHandshake. */
9049 rv = ssl3_AppendHandshakeNumber(ss, len, 3);
9050 if (rv != SECSuccess) {
9051 return rv; /* err set by AppendHandshake. */
9054 for (i = 0; i < certChain->len; i++) {
9056 if (fakeCert.len > 0 && i == ndex) {
9057 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
9059 SECITEM_FreeItem(&fakeCert, PR_FALSE);
9061 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
9062 certChain->certs[i].len, 3);
9065 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
9066 certChain->certs[i].len, 3);
9068 if (rv != SECSuccess) {
9069 return rv; /* err set by AppendHandshake. */
9078 * Used by server only.
9079 * single-stapling, send only a single cert status
9082 ssl3_SendCertificateStatus(sslSocket *ss)
9086 SECItemArray *statusToSend = NULL;
9087 SSL3KEAType certIndex;
9089 SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
9090 SSL_GETPID(), ss->fd));
9092 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9093 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9094 PORT_Assert( ss->sec.isServer);
9096 if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
9099 /* Use certStatus based on the cert being used. */
9100 if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
9101 (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
9104 certIndex = ss->ssl3.hs.kea_def->exchKeyType;
9106 if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) {
9107 statusToSend = ss->certStatusArray[certIndex];
9112 /* Use the array's first item only (single stapling) */
9113 len = 1 + statusToSend->items[0].len + 3;
9115 rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len);
9116 if (rv != SECSuccess) {
9117 return rv; /* err set by AppendHandshake. */
9119 rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
9120 if (rv != SECSuccess)
9121 return rv; /* err set by AppendHandshake. */
9123 rv = ssl3_AppendHandshakeVariable(ss,
9124 statusToSend->items[0].data,
9125 statusToSend->items[0].len,
9127 if (rv != SECSuccess)
9128 return rv; /* err set by AppendHandshake. */
9133 /* This is used to delete the CA certificates in the peer certificate chain
9134 * from the cert database after they've been validated.
9137 ssl3_CleanupPeerCerts(sslSocket *ss)
9139 PLArenaPool * arena = ss->ssl3.peerCertArena;
9140 ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
9142 for (; certs; certs = certs->next) {
9143 CERT_DestroyCertificate(certs->cert);
9145 if (arena) PORT_FreeArena(arena, PR_FALSE);
9146 ss->ssl3.peerCertArena = NULL;
9147 ss->ssl3.peerCertChain = NULL;
9150 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9151 * ssl3 CertificateStatus message.
9152 * Caller must hold Handshake and RecvBuf locks.
9153 * This is always called before ssl3_HandleCertificate, even if the Certificate
9154 * message is sent first.
9157 ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
9159 PRInt32 status, len;
9161 if (ss->ssl3.hs.ws != wait_certificate_status) {
9162 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9163 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
9167 PORT_Assert(!ss->sec.isServer);
9169 /* Consume the CertificateStatusType enum */
9170 status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
9171 if (status != 1 /* ocsp */) {
9175 len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
9176 if (len != length) {
9180 #define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */
9181 if (length > MAX_CERTSTATUS_LEN)
9183 #undef MAX_CERTSTATUS_LEN
9185 /* Array size 1, because we currently implement single-stapling only */
9186 SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
9187 if (!ss->sec.ci.sid->peerCertStatus.items)
9190 ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
9192 if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
9193 SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
9197 PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
9198 ss->sec.ci.sid->peerCertStatus.items[0].len = length;
9199 ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
9201 return ssl3_AuthCertificate(ss);
9204 return ssl3_DecodeError(ss);
9207 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9208 * ssl3 Certificate message.
9209 * Caller must hold Handshake and RecvBuf locks.
9212 ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
9215 ssl3CertNode * lastCert = NULL;
9216 PRInt32 remaining = 0;
9219 PRBool isServer = (PRBool)(!!ss->sec.isServer);
9221 SSL3AlertDescription desc;
9222 int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
9225 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
9226 SSL_GETPID(), ss->fd));
9227 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9228 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9230 if ((ss->ssl3.hs.ws != wait_server_cert) &&
9231 (ss->ssl3.hs.ws != wait_client_cert)) {
9232 desc = unexpected_message;
9233 errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE;
9237 if (ss->sec.peerCert != NULL) {
9238 if (ss->sec.peerKey) {
9239 SECKEY_DestroyPublicKey(ss->sec.peerKey);
9240 ss->sec.peerKey = NULL;
9242 CERT_DestroyCertificate(ss->sec.peerCert);
9243 ss->sec.peerCert = NULL;
9246 ssl3_CleanupPeerCerts(ss);
9247 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
9249 /* It is reported that some TLS client sends a Certificate message
9250 ** with a zero-length message body. We'll treat that case like a
9251 ** normal no_certificates message to maximize interoperability.
9254 remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
9256 goto loser; /* fatal alert already sent by ConsumeHandshake. */
9257 if ((PRUint32)remaining > length)
9262 if (!(isTLS && isServer)) {
9263 desc = bad_certificate;
9266 /* This is TLS's version of a no_certificate alert. */
9267 /* I'm a server. I've requested a client cert. He hasn't got one. */
9268 rv = ssl3_HandleNoCertificate(ss);
9269 if (rv != SECSuccess) {
9270 errCode = PORT_GetError();
9273 ss->ssl3.hs.ws = wait_client_key;
9277 ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
9278 if (ss->ssl3.peerCertArena == NULL) {
9279 goto loser; /* don't send alerts on memory errors */
9282 /* First get the peer cert. */
9287 size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
9289 goto loser; /* fatal alert already sent by ConsumeHandshake. */
9291 if (remaining < size)
9295 certItem.len = size;
9300 ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
9302 if (ss->sec.peerCert == NULL) {
9303 /* We should report an alert if the cert was bad, but not if the
9304 * problem was just some local problem, like memory error.
9309 /* Now get all of the CA certs. */
9310 while (remaining > 0) {
9315 size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
9317 goto loser; /* fatal alert already sent by ConsumeHandshake. */
9319 if (remaining < size)
9323 certItem.len = size;
9328 c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
9330 goto loser; /* don't send alerts on memory errors */
9333 c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
9335 if (c->cert == NULL) {
9343 ss->ssl3.peerCertChain = c;
9351 SECKEY_UpdateCertPQG(ss->sec.peerCert);
9353 if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
9354 ss->ssl3.hs.ws = wait_certificate_status;
9357 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
9363 errCode = PORT_GetError();
9365 case PR_OUT_OF_MEMORY_ERROR:
9366 case SEC_ERROR_BAD_DATABASE:
9367 case SEC_ERROR_NO_MEMORY:
9369 desc = internal_error;
9374 ssl3_SendAlertForCertError(ss, errCode);
9378 desc = isTLS ? decode_error : bad_certificate;
9381 (void)SSL3_SendAlert(ss, alert_fatal, desc);
9384 (void)ssl_MapLowLevelError(errCode);
9389 ssl3_AuthCertificate(sslSocket *ss)
9392 PRBool isServer = (PRBool)(!!ss->sec.isServer);
9395 ss->ssl3.hs.authCertificatePending = PR_FALSE;
9398 * Ask caller-supplied callback function to validate cert chain.
9400 rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
9403 errCode = PORT_GetError();
9404 if (rv != SECWouldBlock) {
9405 if (ss->handleBadCert) {
9406 rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
9410 if (rv == SECWouldBlock) {
9411 if (ss->sec.isServer) {
9412 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
9417 ss->ssl3.hs.authCertificatePending = PR_TRUE;
9420 /* XXX: Async cert validation and False Start don't work together
9421 * safely yet; if we leave False Start enabled, we may end up false
9422 * starting (sending application data) before we
9423 * SSL_AuthCertificateComplete has been called.
9425 ss->opt.enableFalseStart = PR_FALSE;
9428 if (rv != SECSuccess) {
9429 ssl3_SendAlertForCertError(ss, errCode);
9434 ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
9436 if (!ss->sec.isServer) {
9437 CERTCertificate *cert = ss->sec.peerCert;
9439 /* set the server authentication and key exchange types and sizes
9440 ** from the value in the cert. If the key exchange key is different,
9441 ** it will get fixed when we handle the server key exchange message.
9443 SECKEYPublicKey * pubKey = CERT_ExtractPublicKey(cert);
9444 ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
9445 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
9447 ss->sec.keaKeyBits = ss->sec.authKeyBits =
9448 SECKEY_PublicKeyStrengthInBits(pubKey);
9449 #ifdef NSS_ENABLE_ECC
9450 if (ss->sec.keaType == kt_ecdh) {
9451 /* Get authKeyBits from signing key.
9452 * XXX The code below uses a quick approximation of
9453 * key size based on cert->signatureWrap.signature.data
9454 * (which contains the DER encoded signature). The field
9455 * cert->signatureWrap.signature.len contains the
9456 * length of the encoded signature in bits.
9458 if (ss->ssl3.hs.kea_def->kea == kea_ecdh_ecdsa) {
9459 ss->sec.authKeyBits =
9460 cert->signatureWrap.signature.data[3]*8;
9461 if (cert->signatureWrap.signature.data[4] == 0x00)
9462 ss->sec.authKeyBits -= 8;
9464 * XXX: if cert is not signed by ecdsa we should
9465 * destroy pubKey and goto bad_cert
9467 } else if (ss->ssl3.hs.kea_def->kea == kea_ecdh_rsa) {
9468 ss->sec.authKeyBits = cert->signatureWrap.signature.len;
9470 * XXX: if cert is not signed by rsa we should
9471 * destroy pubKey and goto bad_cert
9475 #endif /* NSS_ENABLE_ECC */
9476 SECKEY_DestroyPublicKey(pubKey);
9480 ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */
9481 if (ss->ssl3.hs.kea_def->is_limited ||
9482 /* XXX OR server cert is signing only. */
9483 #ifdef NSS_ENABLE_ECC
9484 ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
9485 ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa ||
9486 #endif /* NSS_ENABLE_ECC */
9487 ss->ssl3.hs.kea_def->exchKeyType == kt_dh) {
9488 ss->ssl3.hs.ws = wait_server_key; /* allow server_key_exchange */
9491 ss->ssl3.hs.ws = wait_client_key;
9494 PORT_Assert(rv == SECSuccess);
9495 if (rv != SECSuccess) {
9496 errCode = SEC_ERROR_LIBRARY_FAILURE;
9504 (void)ssl_MapLowLevelError(errCode);
9508 static SECStatus ssl3_FinishHandshake(sslSocket *ss);
9511 ssl3_AlwaysFail(sslSocket * ss)
9513 PORT_SetError(PR_INVALID_STATE_ERROR);
9517 /* Caller must hold 1stHandshakeLock.
9520 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
9524 PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
9526 if (ss->sec.isServer) {
9527 PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
9531 ssl_GetRecvBufLock(ss);
9532 ssl_GetSSL3HandshakeLock(ss);
9534 if (!ss->ssl3.hs.authCertificatePending) {
9535 PORT_SetError(PR_INVALID_STATE_ERROR);
9540 ss->ssl3.hs.authCertificatePending = PR_FALSE;
9543 ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
9544 ssl3_SendAlertForCertError(ss, error);
9546 } else if (ss->ssl3.hs.restartTarget != NULL) {
9547 sslRestartTarget target = ss->ssl3.hs.restartTarget;
9548 ss->ssl3.hs.restartTarget = NULL;
9550 /* Even if we blocked here, we have accomplished enough to claim
9551 * success. Any remaining work will be taken care of by subsequent
9552 * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc.
9554 if (rv == SECWouldBlock) {
9562 ssl_ReleaseSSL3HandshakeLock(ss);
9563 ssl_ReleaseRecvBufLock(ss);
9569 ssl3_ComputeTLSFinished(ssl3CipherSpec *spec,
9571 const SSL3Hashes * hashes,
9572 TLSFinished * tlsFinished)
9578 label = isServer ? "server finished" : "client finished";
9581 rv = ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw,
9582 hashes->len, tlsFinished->verify_data,
9583 sizeof tlsFinished->verify_data);
9588 /* The calling function must acquire and release the appropriate
9589 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
9593 ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label,
9594 unsigned int labelLen, const unsigned char *val, unsigned int valLen,
9595 unsigned char *out, unsigned int outLen)
9597 SECStatus rv = SECSuccess;
9599 if (spec->master_secret && !spec->bypassCiphers) {
9600 SECItem param = {siBuffer, NULL, 0};
9601 CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
9602 PK11Context *prf_context;
9603 unsigned int retLen;
9605 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
9606 mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
9608 prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
9609 spec->master_secret, ¶m);
9613 rv = PK11_DigestBegin(prf_context);
9614 rv |= PK11_DigestOp(prf_context, (unsigned char *) label, labelLen);
9615 rv |= PK11_DigestOp(prf_context, val, valLen);
9616 rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
9617 PORT_Assert(rv != SECSuccess || retLen == outLen);
9619 PK11_DestroyContext(prf_context, PR_TRUE);
9622 #ifdef NO_PKCS11_BYPASS
9623 PORT_Assert(spec->master_secret);
9624 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
9627 SECItem inData = { siBuffer, };
9628 SECItem outData = { siBuffer, };
9629 PRBool isFIPS = PR_FALSE;
9631 inData.data = (unsigned char *) val;
9632 inData.len = valLen;
9634 outData.len = outLen;
9635 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
9636 rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData,
9639 rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS);
9641 PORT_Assert(rv != SECSuccess || outData.len == outLen);
9647 /* called from ssl3_HandleServerHelloDone
9650 ssl3_SendNextProto(sslSocket *ss)
9654 static const unsigned char padding[32] = {0};
9656 if (ss->ssl3.nextProto.len == 0)
9659 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9660 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9662 padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32);
9664 rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len +
9666 if (rv != SECSuccess) {
9667 return rv; /* error code set by AppendHandshakeHeader */
9669 rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data,
9670 ss->ssl3.nextProto.len, 1);
9671 if (rv != SECSuccess) {
9672 return rv; /* error code set by AppendHandshake */
9674 rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
9675 if (rv != SECSuccess) {
9676 return rv; /* error code set by AppendHandshake */
9681 /* called from ssl3_SendFinished
9683 * This function is simply a debugging aid and therefore does not return a
9686 ssl3_RecordKeyLog(sslSocket *ss)
9691 char buf[14 /* "CLIENT_RANDOM " */ +
9692 SSL3_RANDOM_LENGTH*2 /* client_random */ +
9694 48*2 /* master secret */ +
9698 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9700 sid = ss->sec.ci.sid;
9702 if (!ssl_keylog_iob)
9705 rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret);
9706 if (rv != SECSuccess)
9709 ssl_GetSpecReadLock(ss);
9711 /* keyData does not need to be freed. */
9712 keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret);
9713 if (!keyData || !keyData->data || keyData->len != 48) {
9714 ssl_ReleaseSpecReadLock(ss);
9718 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
9720 /* There could be multiple, concurrent writers to the
9721 * keylog, so we have to do everything in a single call to
9724 memcpy(buf, "CLIENT_RANDOM ", 14);
9726 hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH);
9727 j += SSL3_RANDOM_LENGTH*2;
9729 hexEncode(buf + j, keyData->data, 48);
9733 PORT_Assert(j == sizeof(buf));
9735 ssl_ReleaseSpecReadLock(ss);
9737 if (fwrite(buf, sizeof(buf), 1, ssl_keylog_iob) != 1)
9739 fflush(ssl_keylog_iob);
9743 /* called from ssl3_HandleServerHelloDone
9744 * ssl3_HandleClientHello
9745 * ssl3_HandleFinished
9748 ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
9750 ssl3CipherSpec *cwSpec;
9752 PRBool isServer = ss->sec.isServer;
9754 SSL3Sender sender = isServer ? sender_server : sender_client;
9756 TLSFinished tlsFinished;
9758 SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
9760 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9761 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9763 ssl_GetSpecReadLock(ss);
9764 cwSpec = ss->ssl3.cwSpec;
9765 isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
9766 rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
9767 if (isTLS && rv == SECSuccess) {
9768 rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished);
9770 ssl_ReleaseSpecReadLock(ss);
9771 if (rv != SECSuccess) {
9772 goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */
9777 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
9779 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
9780 ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
9781 rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished);
9782 if (rv != SECSuccess)
9783 goto fail; /* err set by AppendHandshake. */
9784 rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
9785 if (rv != SECSuccess)
9786 goto fail; /* err set by AppendHandshake. */
9789 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
9791 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
9792 PORT_Assert(hashes.len == sizeof hashes.u.s);
9793 ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
9794 rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s);
9795 if (rv != SECSuccess)
9796 goto fail; /* err set by AppendHandshake. */
9797 rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
9798 if (rv != SECSuccess)
9799 goto fail; /* err set by AppendHandshake. */
9801 rv = ssl3_FlushHandshake(ss, flags);
9802 if (rv != SECSuccess) {
9803 goto fail; /* error code set by ssl3_FlushHandshake */
9806 ssl3_RecordKeyLog(ss);
9814 /* wrap the master secret, and put it into the SID.
9815 * Caller holds the Spec read lock.
9818 ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid,
9819 ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType)
9821 PK11SymKey * wrappingKey = NULL;
9822 PK11SlotInfo * symKeySlot;
9823 void * pwArg = ss->pkcs11PinArg;
9824 SECStatus rv = SECFailure;
9825 PRBool isServer = ss->sec.isServer;
9826 CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
9827 symKeySlot = PK11_GetSlotFromKey(spec->master_secret);
9832 /* these next few functions are mere accessors and don't fail. */
9833 sid->u.ssl3.masterWrapIndex = wrapKeyIndex =
9834 PK11_GetCurrentWrapIndex(symKeySlot);
9835 PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
9837 sid->u.ssl3.masterWrapSeries = incarnation =
9838 PK11_GetSlotSeries(symKeySlot);
9839 sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot);
9840 sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
9841 sid->u.ssl3.masterValid = PR_TRUE;
9842 /* Get the default wrapping key, for wrapping the master secret before
9843 * placing it in the SID cache entry. */
9844 wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
9845 CKM_INVALID_MECHANISM, incarnation,
9848 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
9851 /* if the wrappingKey doesn't exist, attempt to create it.
9852 * Note: we intentionally ignore errors here. If we cannot
9853 * generate a wrapping key, it is not fatal to this SSL connection,
9854 * but we will not be able to restart this session.
9856 mechanism = PK11_GetBestWrapMechanism(symKeySlot);
9857 keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
9858 /* Zero length means fixed key length algorithm, or error.
9861 wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
9864 PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
9868 /* server socket using session cache. */
9869 mechanism = PK11_GetBestWrapMechanism(symKeySlot);
9870 if (mechanism != CKM_INVALID_MECHANISM) {
9872 getWrappingKey(ss, symKeySlot, effectiveExchKeyType,
9875 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
9880 sid->u.ssl3.masterWrapMech = mechanism;
9881 PK11_FreeSlot(symKeySlot);
9886 wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
9887 wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret;
9888 rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
9889 spec->master_secret, &wmsItem);
9890 /* rv is examined below. */
9891 sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
9892 PK11_FreeSymKey(wrappingKey);
9897 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9898 * ssl3 Finished message from the peer.
9899 * Caller must hold Handshake and RecvBuf locks.
9902 ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
9903 const SSL3Hashes *hashes)
9905 sslSessionID * sid = ss->sec.ci.sid;
9906 SECStatus rv = SECSuccess;
9907 PRBool isServer = ss->sec.isServer;
9909 SSL3KEAType effectiveExchKeyType;
9911 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
9912 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
9914 SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
9915 SSL_GETPID(), ss->fd));
9917 if (ss->ssl3.hs.ws != wait_finished) {
9918 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9919 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
9923 isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
9925 TLSFinished tlsFinished;
9927 if (length != sizeof tlsFinished) {
9928 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
9929 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
9932 rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer,
9933 hashes, &tlsFinished);
9935 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
9937 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
9938 ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
9939 if (rv != SECSuccess ||
9940 0 != NSS_SecureMemcmp(&tlsFinished, b, length)) {
9941 (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
9942 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
9946 if (length != sizeof(SSL3Finished)) {
9947 (void)ssl3_IllegalParameter(ss);
9948 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
9953 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s;
9955 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s;
9956 PORT_Assert(hashes->len == sizeof hashes->u.s);
9957 ss->ssl3.hs.finishedBytes = sizeof hashes->u.s;
9958 if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) {
9959 (void)ssl3_HandshakeFailure(ss);
9960 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
9965 ssl_GetXmitBufLock(ss); /*************************************/
9967 if ((isServer && !ss->ssl3.hs.isResuming) ||
9968 (!isServer && ss->ssl3.hs.isResuming)) {
9971 /* Send a NewSessionTicket message if the client sent us
9972 * either an empty session ticket, or one that did not verify.
9973 * (Note that if either of these conditions was met, then the
9974 * server has sent a SessionTicket extension in the
9975 * ServerHello message.)
9977 if (isServer && !ss->ssl3.hs.isResuming &&
9978 ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) {
9979 rv = ssl3_SendNewSessionTicket(ss);
9980 if (rv != SECSuccess) {
9985 rv = ssl3_SendChangeCipherSpecs(ss);
9986 if (rv != SECSuccess) {
9987 goto xmit_loser; /* err is set. */
9989 /* If this thread is in SSL_SecureSend (trying to write some data)
9990 ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
9991 ** last two handshake messages (change cipher spec and finished)
9992 ** will be sent in the same send/write call as the application data.
9994 if (ss->writerThread == PR_GetCurrentThread()) {
9995 flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
9998 if (!isServer && !ss->firstHsDone) {
9999 rv = ssl3_SendNextProto(ss);
10000 if (rv != SECSuccess) {
10001 goto xmit_loser; /* err code was set. */
10006 flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
10009 rv = ssl3_SendFinished(ss, flags);
10010 if (rv != SECSuccess) {
10011 goto xmit_loser; /* err is set. */
10016 ssl_ReleaseXmitBufLock(ss); /*************************************/
10017 if (rv != SECSuccess) {
10021 ss->gs.writeOffset = 0;
10022 ss->gs.readOffset = 0;
10024 if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) {
10025 effectiveExchKeyType = kt_rsa;
10027 effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
10030 if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) {
10031 /* fill in the sid */
10032 sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
10033 sid->u.ssl3.compression = ss->ssl3.hs.compression;
10034 sid->u.ssl3.policy = ss->ssl3.policy;
10035 #ifdef NSS_ENABLE_ECC
10036 sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves;
10038 sid->u.ssl3.exchKeyType = effectiveExchKeyType;
10039 sid->version = ss->version;
10040 sid->authAlgorithm = ss->sec.authAlgorithm;
10041 sid->authKeyBits = ss->sec.authKeyBits;
10042 sid->keaType = ss->sec.keaType;
10043 sid->keaKeyBits = ss->sec.keaKeyBits;
10044 sid->lastAccessTime = sid->creationTime = ssl_Time();
10045 sid->expirationTime = sid->creationTime + ssl3_sid_timeout;
10046 sid->localCert = CERT_DupCertificate(ss->sec.localCert);
10048 ssl_GetSpecReadLock(ss); /*************************************/
10050 /* Copy the master secret (wrapped or unwrapped) into the sid */
10051 if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) {
10052 sid->u.ssl3.keys.wrapped_master_secret_len =
10053 ss->ssl3.crSpec->msItem.len;
10054 memcpy(sid->u.ssl3.keys.wrapped_master_secret,
10055 ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len);
10056 sid->u.ssl3.masterValid = PR_TRUE;
10057 sid->u.ssl3.keys.msIsWrapped = PR_FALSE;
10060 rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid,
10062 effectiveExchKeyType);
10063 sid->u.ssl3.keys.msIsWrapped = PR_TRUE;
10065 ssl_ReleaseSpecReadLock(ss); /*************************************/
10067 /* If the wrap failed, we don't cache the sid.
10068 * The connection continues normally however.
10070 ss->ssl3.hs.cacheSID = rv == SECSuccess;
10073 if (ss->ssl3.hs.authCertificatePending) {
10074 if (ss->ssl3.hs.restartTarget) {
10075 PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
10076 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10080 ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
10081 return SECWouldBlock;
10084 rv = ssl3_FinishHandshake(ss);
10089 ssl3_FinishHandshake(sslSocket * ss)
10091 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10092 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
10093 PORT_Assert( ss->ssl3.hs.restartTarget == NULL );
10095 /* The first handshake is now completed. */
10096 ss->handshake = NULL;
10097 ss->firstHsDone = PR_TRUE;
10099 if (ss->ssl3.hs.cacheSID) {
10100 (*ss->sec.cache)(ss->sec.ci.sid);
10101 ss->ssl3.hs.cacheSID = PR_FALSE;
10104 ss->ssl3.hs.ws = idle_handshake;
10106 /* Do the handshake callback for sslv3 here, if we cannot false start. */
10107 if (ss->handshakeCallback != NULL && !ssl3_CanFalseStart(ss)) {
10108 (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
10114 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
10115 * hanshake message.
10116 * Caller must hold Handshake and RecvBuf locks.
10119 ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
10121 SECStatus rv = SECSuccess;
10122 SSL3HandshakeType type = ss->ssl3.hs.msg_type;
10123 SSL3Hashes hashes; /* computed hashes are put here. */
10125 PRUint8 dtlsData[8];
10127 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10128 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
10130 * We have to compute the hashes before we update them with the
10133 ssl_GetSpecReadLock(ss); /************************************/
10134 if((type == finished) || (type == certificate_verify)) {
10135 SSL3Sender sender = (SSL3Sender)0;
10136 ssl3CipherSpec *rSpec = ss->ssl3.prSpec;
10138 if (type == finished) {
10139 sender = ss->sec.isServer ? sender_client : sender_server;
10140 rSpec = ss->ssl3.crSpec;
10142 rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender);
10144 ssl_ReleaseSpecReadLock(ss); /************************************/
10145 if (rv != SECSuccess) {
10146 return rv; /* error code was set by ssl3_ComputeHandshakeHashes*/
10148 SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
10149 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
10151 hdr[0] = (PRUint8)ss->ssl3.hs.msg_type;
10152 hdr[1] = (PRUint8)(length >> 16);
10153 hdr[2] = (PRUint8)(length >> 8);
10154 hdr[3] = (PRUint8)(length );
10156 /* Start new handshake hashes when we start a new handshake */
10157 if (ss->ssl3.hs.msg_type == client_hello) {
10158 rv = ssl3_RestartHandshakeHashes(ss);
10159 if (rv != SECSuccess) {
10163 /* We should not include hello_request and hello_verify_request messages
10164 * in the handshake hashes */
10165 if ((ss->ssl3.hs.msg_type != hello_request) &&
10166 (ss->ssl3.hs.msg_type != hello_verify_request)) {
10167 rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4);
10168 if (rv != SECSuccess) return rv; /* err code already set. */
10170 /* Extra data to simulate a complete DTLS handshake fragment */
10172 /* Sequence number */
10173 dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq);
10174 dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq);
10176 /* Fragment offset */
10181 /* Fragment length */
10182 dtlsData[5] = (PRUint8)(length >> 16);
10183 dtlsData[6] = (PRUint8)(length >> 8);
10184 dtlsData[7] = (PRUint8)(length );
10186 rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) dtlsData,
10188 if (rv != SECSuccess) return rv; /* err code already set. */
10191 /* The message body */
10192 rv = ssl3_UpdateHandshakeHashes(ss, b, length);
10193 if (rv != SECSuccess) return rv; /* err code already set. */
10196 PORT_SetError(0); /* each message starts with no error. */
10198 if (ss->ssl3.hs.ws == wait_certificate_status &&
10199 ss->ssl3.hs.msg_type != certificate_status) {
10200 /* If we negotiated the certificate_status extension then we deferred
10201 * certificate validation until we get the CertificateStatus messsage.
10202 * But the CertificateStatus message is optional. If the server did
10203 * not send it then we need to validate the certificate now. If the
10204 * server does send the CertificateStatus message then we will
10205 * authenticate the certificate in ssl3_HandleCertificateStatus.
10207 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
10208 PORT_Assert(rv != SECWouldBlock);
10209 if (rv != SECSuccess) {
10214 switch (ss->ssl3.hs.msg_type) {
10215 case hello_request:
10217 (void)ssl3_DecodeError(ss);
10218 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
10221 if (ss->sec.isServer) {
10222 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10223 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
10226 rv = ssl3_HandleHelloRequest(ss);
10229 if (!ss->sec.isServer) {
10230 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10231 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
10234 rv = ssl3_HandleClientHello(ss, b, length);
10237 if (ss->sec.isServer) {
10238 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10239 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
10242 rv = ssl3_HandleServerHello(ss, b, length);
10244 case hello_verify_request:
10245 if (!IS_DTLS(ss) || ss->sec.isServer) {
10246 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10247 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
10250 rv = dtls_HandleHelloVerifyRequest(ss, b, length);
10253 rv = ssl3_HandleCertificate(ss, b, length);
10255 case certificate_status:
10256 rv = ssl3_HandleCertificateStatus(ss, b, length);
10258 case server_key_exchange:
10259 if (ss->sec.isServer) {
10260 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10261 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
10264 rv = ssl3_HandleServerKeyExchange(ss, b, length);
10266 case certificate_request:
10267 if (ss->sec.isServer) {
10268 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10269 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
10272 rv = ssl3_HandleCertificateRequest(ss, b, length);
10274 case server_hello_done:
10276 (void)ssl3_DecodeError(ss);
10277 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
10280 if (ss->sec.isServer) {
10281 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10282 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
10285 rv = ssl3_HandleServerHelloDone(ss);
10287 case certificate_verify:
10288 if (!ss->sec.isServer) {
10289 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10290 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
10293 rv = ssl3_HandleCertificateVerify(ss, b, length, &hashes);
10295 case client_key_exchange:
10296 if (!ss->sec.isServer) {
10297 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10298 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
10301 rv = ssl3_HandleClientKeyExchange(ss, b, length);
10303 case new_session_ticket:
10304 if (ss->sec.isServer) {
10305 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10306 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
10309 rv = ssl3_HandleNewSessionTicket(ss, b, length);
10312 rv = ssl3_HandleFinished(ss, b, length, &hashes);
10315 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10316 PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
10320 if (IS_DTLS(ss) && (rv != SECFailure)) {
10321 /* Increment the expected sequence number */
10322 ss->ssl3.hs.recvMessageSeq++;
10328 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
10329 * origBuf is the decrypted ssl record content.
10330 * Caller must hold the handshake and RecvBuf locks.
10333 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
10336 * There may be a partial handshake message already in the handshake
10337 * state. The incoming buffer may contain another portion, or a
10338 * complete message or several messages followed by another portion.
10340 * Each message is made contiguous before being passed to the actual
10343 sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer pointer */
10346 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10347 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
10349 if (buf->buf == NULL) {
10352 while (buf->len > 0) {
10353 if (ss->ssl3.hs.header_bytes < 4) {
10357 if (ss->ssl3.hs.header_bytes++ == 0)
10358 ss->ssl3.hs.msg_type = (SSL3HandshakeType)t;
10360 ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
10361 if (ss->ssl3.hs.header_bytes < 4)
10364 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
10365 if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
10366 (void)ssl3_DecodeError(ss);
10367 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
10370 #undef MAX_HANDSHAKE_MSG_LEN
10372 /* If msg_len is zero, be sure we fall through,
10373 ** even if buf->len is zero.
10375 if (ss->ssl3.hs.msg_len > 0)
10380 * Header has been gathered and there is at least one byte of new
10381 * data available for this message. If it can be done right out
10382 * of the original buffer, then use it from there.
10384 if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) {
10385 /* handle it from input buffer */
10386 rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len);
10387 if (rv == SECFailure) {
10388 /* This test wants to fall through on either
10389 * SECSuccess or SECWouldBlock.
10390 * ssl3_HandleHandshakeMessage MUST set the error code.
10394 buf->buf += ss->ssl3.hs.msg_len;
10395 buf->len -= ss->ssl3.hs.msg_len;
10396 ss->ssl3.hs.msg_len = 0;
10397 ss->ssl3.hs.header_bytes = 0;
10398 if (rv != SECSuccess) { /* return if SECWouldBlock. */
10402 /* must be copied to msg_body and dealt with from there */
10403 unsigned int bytes;
10405 PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
10406 bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
10408 /* Grow the buffer if needed */
10409 rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
10410 if (rv != SECSuccess) {
10411 /* sslBuffer_Grow has set a memory error code. */
10415 PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
10417 ss->ssl3.hs.msg_body.len += bytes;
10421 PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
10423 /* if we have a whole message, do it */
10424 if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
10425 rv = ssl3_HandleHandshakeMessage(
10426 ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len);
10427 if (rv == SECFailure) {
10428 /* This test wants to fall through on either
10429 * SECSuccess or SECWouldBlock.
10430 * ssl3_HandleHandshakeMessage MUST set error code.
10434 ss->ssl3.hs.msg_body.len = 0;
10435 ss->ssl3.hs.msg_len = 0;
10436 ss->ssl3.hs.header_bytes = 0;
10437 if (rv != SECSuccess) { /* return if SECWouldBlock. */
10441 PORT_Assert(buf->len == 0);
10447 origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
10448 buf->buf = NULL; /* not a leak. */
10452 /* These macros return the given value with the MSB copied to all the other
10453 * bits. They use the fact that arithmetic shift shifts-in the sign bit.
10454 * However, this is not ensured by the C standard so you may need to replace
10455 * them with something else for odd compilers. */
10456 #define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) )
10457 #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x)))
10459 /* SECStatusToMask returns, in constant time, a mask value of all ones if
10460 * rv == SECSuccess. Otherwise it returns zero. */
10461 static unsigned int
10462 SECStatusToMask(SECStatus rv)
10465 /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results
10466 * in the MSB being set to one iff it was zero before. */
10467 good = rv ^ SECSuccess;
10469 return DUPLICATE_MSB_TO_ALL(good);
10472 /* ssl_ConstantTimeGE returns 0xff if a>=b and 0x00 otherwise. */
10473 static unsigned char
10474 ssl_ConstantTimeGE(unsigned int a, unsigned int b)
10477 return DUPLICATE_MSB_TO_ALL(~a);
10480 /* ssl_ConstantTimeEQ8 returns 0xff if a==b and 0x00 otherwise. */
10481 static unsigned char
10482 ssl_ConstantTimeEQ8(unsigned char a, unsigned char b)
10484 unsigned int c = a ^ b;
10486 return DUPLICATE_MSB_TO_ALL_8(c);
10490 ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
10491 unsigned int blockSize,
10492 unsigned int macSize)
10494 unsigned int paddingLength, good, t;
10495 const unsigned int overhead = 1 /* padding length byte */ + macSize;
10497 /* These lengths are all public so we can test them in non-constant
10499 if (overhead > plaintext->len) {
10503 paddingLength = plaintext->buf[plaintext->len-1];
10504 /* SSLv3 padding bytes are random and cannot be checked. */
10505 t = plaintext->len;
10506 t -= paddingLength+overhead;
10507 /* If len >= padding_length+overhead then the MSB of t is zero. */
10508 good = DUPLICATE_MSB_TO_ALL(~t);
10509 /* SSLv3 requires that the padding is minimal. */
10510 t = blockSize - (paddingLength+1);
10511 good &= DUPLICATE_MSB_TO_ALL(~t);
10512 plaintext->len -= good & (paddingLength+1);
10513 return (good & SECSuccess) | (~good & SECFailure);
10517 ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
10519 unsigned int paddingLength, good, t, toCheck, i;
10520 const unsigned int overhead = 1 /* padding length byte */ + macSize;
10522 /* These lengths are all public so we can test them in non-constant
10524 if (overhead > plaintext->len) {
10528 paddingLength = plaintext->buf[plaintext->len-1];
10529 t = plaintext->len;
10530 t -= paddingLength+overhead;
10531 /* If len >= paddingLength+overhead then the MSB of t is zero. */
10532 good = DUPLICATE_MSB_TO_ALL(~t);
10534 /* The padding consists of a length byte at the end of the record and then
10535 * that many bytes of padding, all with the same value as the length byte.
10536 * Thus, with the length byte included, there are paddingLength+1 bytes of
10539 * We can't check just |paddingLength+1| bytes because that leaks
10540 * decrypted information. Therefore we always have to check the maximum
10541 * amount of padding possible. (Again, the length of the record is
10542 * public information so we can use it.) */
10543 toCheck = 255; /* maximum amount of padding. */
10544 if (toCheck > plaintext->len-1) {
10545 toCheck = plaintext->len-1;
10548 for (i = 0; i < toCheck; i++) {
10549 unsigned int t = paddingLength - i;
10550 /* If i <= paddingLength then the MSB of t is zero and mask is
10551 * 0xff. Otherwise, mask is 0. */
10552 unsigned char mask = DUPLICATE_MSB_TO_ALL(~t);
10553 unsigned char b = plaintext->buf[plaintext->len-1-i];
10554 /* The final |paddingLength+1| bytes should all have the value
10555 * |paddingLength|. Therefore the XOR should be zero. */
10556 good &= ~(mask&(paddingLength ^ b));
10559 /* If any of the final |paddingLength+1| bytes had the wrong value,
10560 * one or more of the lower eight bits of |good| will be cleared. We
10561 * AND the bottom 8 bits together and duplicate the result to all the
10566 good <<= sizeof(good)*8-1;
10567 good = DUPLICATE_MSB_TO_ALL(good);
10569 plaintext->len -= good & (paddingLength+1);
10570 return (good & SECSuccess) | (~good & SECFailure);
10574 * originalLength >= macSize
10575 * macSize <= MAX_MAC_LENGTH
10576 * plaintext->len >= macSize
10579 ssl_CBCExtractMAC(sslBuffer *plaintext,
10580 unsigned int originalLength,
10582 unsigned int macSize)
10584 unsigned char rotatedMac[MAX_MAC_LENGTH];
10585 /* macEnd is the index of |plaintext->buf| just after the end of the
10587 unsigned macEnd = plaintext->len;
10588 unsigned macStart = macEnd - macSize;
10589 /* scanStart contains the number of bytes that we can ignore because
10590 * the MAC's position can only vary by 255 bytes. */
10591 unsigned scanStart = 0;
10592 unsigned i, j, divSpoiler;
10593 unsigned char rotateOffset;
10595 if (originalLength > macSize + 255 + 1)
10596 scanStart = originalLength - (macSize + 255 + 1);
10598 /* divSpoiler contains a multiple of macSize that is used to cause the
10599 * modulo operation to be constant time. Without this, the time varies
10600 * based on the amount of padding when running on Intel chips at least.
10602 * The aim of right-shifting macSize is so that the compiler doesn't
10603 * figure out that it can remove divSpoiler as that would require it
10604 * to prove that macSize is always even, which I hope is beyond it. */
10605 divSpoiler = macSize >> 1;
10606 divSpoiler <<= (sizeof(divSpoiler)-1)*8;
10607 rotateOffset = (divSpoiler + macStart - scanStart) % macSize;
10609 memset(rotatedMac, 0, macSize);
10610 for (i = scanStart; i < originalLength;) {
10611 for (j = 0; j < macSize && i < originalLength; i++, j++) {
10612 unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
10613 unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
10614 unsigned char b = 0;
10615 b = plaintext->buf[i];
10616 rotatedMac[j] |= b & macStarted & ~macEnded;
10620 /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
10621 * we could line-align |rotatedMac| and rotate in place. */
10622 memset(out, 0, macSize);
10623 for (i = 0; i < macSize; i++) {
10624 unsigned char offset =
10625 (divSpoiler + macSize - rotateOffset + i) % macSize;
10626 for (j = 0; j < macSize; j++) {
10627 out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset);
10632 /* if cText is non-null, then decipher, check MAC, and decompress the
10633 * SSL record from cText->buf (typically gs->inbuf)
10634 * into databuf (typically gs->buf), and any previous contents of databuf
10635 * is lost. Then handle databuf according to its SSL record type,
10636 * unless it's an application record.
10638 * If cText is NULL, then the ciphertext has previously been deciphered and
10639 * checked, and is already sitting in databuf. It is processed as an SSL
10640 * Handshake message.
10642 * DOES NOT process the decrypted/decompressed application data.
10643 * On return, databuf contains the decrypted/decompressed record.
10645 * Called from ssl3_GatherCompleteHandshake
10646 * ssl3_RestartHandshakeAfterCertReq
10648 * Caller must hold the RecvBufLock.
10650 * This function aquires and releases the SSL3Handshake Lock, holding the
10651 * lock around any calls to functions that handle records other than
10652 * Application Data records.
10655 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
10657 const ssl3BulkCipherDef *cipher_def;
10658 ssl3CipherSpec * crSpec;
10660 unsigned int hashBytes = MAX_MAC_LENGTH + 1;
10662 SSL3ContentType rType;
10663 SSL3Opaque hash[MAX_MAC_LENGTH];
10664 SSL3Opaque givenHashBuf[MAX_MAC_LENGTH];
10665 SSL3Opaque *givenHash;
10666 sslBuffer *plaintext;
10667 sslBuffer temp_buf;
10668 PRUint64 dtls_seq_num;
10669 unsigned int ivLen = 0;
10670 unsigned int originalLen = 0;
10672 unsigned int minLength;
10674 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
10676 if (!ss->ssl3.initialized) {
10677 ssl_GetSSL3HandshakeLock(ss);
10678 rv = ssl3_InitState(ss);
10679 ssl_ReleaseSSL3HandshakeLock(ss);
10680 if (rv != SECSuccess) {
10681 return rv; /* ssl3_InitState has set the error code. */
10685 /* check for Token Presence */
10686 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
10687 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
10691 /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX().
10692 * This implies that databuf holds a previously deciphered SSL Handshake
10695 if (cText == NULL) {
10696 SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake",
10697 SSL_GETPID(), ss->fd));
10698 rType = content_handshake;
10702 ssl_GetSpecReadLock(ss); /******************************************/
10704 crSpec = ss->ssl3.crSpec;
10705 cipher_def = crSpec->cipher_def;
10708 * DTLS relevance checks:
10709 * Note that this code currently ignores all out-of-epoch packets,
10710 * which means we lose some in the case of rehandshake +
10711 * loss/reordering. Since DTLS is explicitly unreliable, this
10712 * seems like a good tradeoff for implementation effort and is
10713 * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1
10716 DTLSEpoch epoch = (cText->seq_num.high >> 16) & 0xffff;
10718 if (crSpec->epoch != epoch) {
10719 ssl_ReleaseSpecReadLock(ss);
10720 SSL_DBG(("%d: SSL3[%d]: HandleRecord, received packet "
10721 "from irrelevant epoch %d", SSL_GETPID(), ss->fd, epoch));
10722 /* Silently drop the packet */
10723 databuf->len = 0; /* Needed to ensure data not left around */
10727 dtls_seq_num = (((PRUint64)(cText->seq_num.high & 0xffff)) << 32) |
10728 ((PRUint64)cText->seq_num.low);
10730 if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) {
10731 ssl_ReleaseSpecReadLock(ss);
10732 SSL_DBG(("%d: SSL3[%d]: HandleRecord, rejecting "
10733 "potentially replayed packet", SSL_GETPID(), ss->fd));
10734 /* Silently drop the packet */
10735 databuf->len = 0; /* Needed to ensure data not left around */
10740 good = (unsigned)-1;
10741 minLength = crSpec->mac_size;
10742 if (cipher_def->type == type_block) {
10743 /* CBC records have a padding length byte at the end. */
10745 if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
10746 /* With >= TLS 1.1, CBC records have an explicit IV. */
10747 minLength += cipher_def->iv_size;
10751 /* We can perform this test in variable time because the record's total
10752 * length and the ciphersuite are both public knowledge. */
10753 if (cText->buf->len < minLength) {
10754 SSL_DBG(("%d: SSL3[%d]: HandleRecord, record too small.",
10755 SSL_GETPID(), ss->fd));
10756 /* must not hold spec lock when calling SSL3_SendAlert. */
10757 ssl_ReleaseSpecReadLock(ss);
10758 SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
10759 /* always log mac error, in case attacker can read server logs. */
10760 PORT_SetError(SSL_ERROR_BAD_MAC_READ);
10764 if (cipher_def->type == type_block &&
10765 crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
10766 /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
10767 * "The receiver decrypts the entire GenericBlockCipher structure and
10768 * then discards the first cipher block corresponding to the IV
10769 * component." Instead, we decrypt the first cipher block and then
10770 * discard it before decrypting the rest.
10772 SSL3Opaque iv[MAX_IV_LENGTH];
10775 ivLen = cipher_def->iv_size;
10776 if (ivLen < 8 || ivLen > sizeof(iv)) {
10777 ssl_ReleaseSpecReadLock(ss);
10778 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10782 PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
10784 /* The decryption result is garbage, but since we just throw away
10785 * the block it doesn't matter. The decryption of the next block
10786 * depends only on the ciphertext of the IV block.
10788 rv = crSpec->decode(crSpec->decodeContext, iv, &decoded,
10789 sizeof(iv), cText->buf->buf, ivLen);
10791 good &= SECStatusToMask(rv);
10794 /* If we will be decompressing the buffer we need to decrypt somewhere
10795 * other than into databuf */
10796 if (crSpec->decompressor) {
10797 temp_buf.buf = NULL;
10798 temp_buf.space = 0;
10799 plaintext = &temp_buf;
10801 plaintext = databuf;
10804 plaintext->len = 0; /* filled in by decode call below. */
10805 if (plaintext->space < MAX_FRAGMENT_LENGTH) {
10806 rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048);
10807 if (rv != SECSuccess) {
10808 ssl_ReleaseSpecReadLock(ss);
10809 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
10810 SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048));
10811 /* sslBuffer_Grow has set a memory error code. */
10812 /* Perhaps we should send an alert. (but we have no memory!) */
10817 PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
10818 cText->buf->len - ivLen));
10820 isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0);
10822 if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) {
10823 ssl_ReleaseSpecReadLock(ss);
10824 SSL3_SendAlert(ss, alert_fatal, record_overflow);
10825 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
10829 /* decrypt from cText buf to plaintext. */
10830 rv = crSpec->decode(
10831 crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len,
10832 plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
10833 good &= SECStatusToMask(rv);
10835 PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
10837 originalLen = plaintext->len;
10839 /* If it's a block cipher, check and strip the padding. */
10840 if (cipher_def->type == type_block) {
10841 const unsigned int blockSize = cipher_def->iv_size;
10842 const unsigned int macSize = crSpec->mac_size;
10844 if (crSpec->version <= SSL_LIBRARY_VERSION_3_0) {
10845 good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
10846 plaintext, blockSize, macSize));
10848 good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
10849 plaintext, macSize));
10853 /* compute the MAC */
10854 rType = cText->type;
10855 if (cipher_def->type == type_block) {
10856 rv = ssl3_ComputeRecordMACConstantTime(
10857 crSpec, (PRBool)(!ss->sec.isServer),
10858 IS_DTLS(ss), rType, cText->version,
10859 IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
10860 plaintext->buf, plaintext->len, originalLen,
10863 ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
10865 givenHash = givenHashBuf;
10867 /* plaintext->len will always have enough space to remove the MAC
10868 * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
10869 * plaintext->len if the result has enough space for the MAC and we
10870 * tested the unadjusted size against minLength, above. */
10871 plaintext->len -= crSpec->mac_size;
10873 /* This is safe because we checked the minLength above. */
10874 plaintext->len -= crSpec->mac_size;
10876 rv = ssl3_ComputeRecordMAC(
10877 crSpec, (PRBool)(!ss->sec.isServer),
10878 IS_DTLS(ss), rType, cText->version,
10879 IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
10880 plaintext->buf, plaintext->len,
10883 /* We can read the MAC directly from the record because its location is
10884 * public when a stream cipher is used. */
10885 givenHash = plaintext->buf + plaintext->len;
10888 good &= SECStatusToMask(rv);
10890 if (hashBytes != (unsigned)crSpec->mac_size ||
10891 NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) {
10892 /* We're allowed to leak whether or not the MAC check was correct */
10897 /* must not hold spec lock when calling SSL3_SendAlert. */
10898 ssl_ReleaseSpecReadLock(ss);
10900 SSL_DBG(("%d: SSL3[%d]: mac check failed", SSL_GETPID(), ss->fd));
10902 if (!IS_DTLS(ss)) {
10903 SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
10904 /* always log mac error, in case attacker can read server logs. */
10905 PORT_SetError(SSL_ERROR_BAD_MAC_READ);
10908 /* Silently drop the packet */
10909 databuf->len = 0; /* Needed to ensure data not left around */
10914 if (!IS_DTLS(ss)) {
10915 ssl3_BumpSequenceNumber(&crSpec->read_seq_num);
10917 dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num);
10920 ssl_ReleaseSpecReadLock(ss); /*****************************************/
10923 * The decrypted data is now in plaintext.
10926 /* possibly decompress the record. If we aren't using compression then
10927 * plaintext == databuf and so the uncompressed data is already in
10929 if (crSpec->decompressor) {
10930 if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) {
10931 rv = sslBuffer_Grow(
10932 databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION);
10933 if (rv != SECSuccess) {
10934 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
10935 SSL_GETPID(), ss->fd,
10936 plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION));
10937 /* sslBuffer_Grow has set a memory error code. */
10938 /* Perhaps we should send an alert. (but we have no memory!) */
10939 PORT_Free(plaintext->buf);
10944 rv = crSpec->decompressor(crSpec->decompressContext,
10946 (int*) &databuf->len,
10951 if (rv != SECSuccess) {
10952 int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE);
10953 SSL3_SendAlert(ss, alert_fatal,
10954 isTLS ? decompression_failure : bad_record_mac);
10956 /* There appears to be a bug with (at least) Apache + OpenSSL where
10957 * resumed SSLv3 connections don't actually use compression. See
10958 * comments 93-95 of
10959 * https://bugzilla.mozilla.org/show_bug.cgi?id=275744
10961 * So, if we get a decompression error, and the record appears to
10962 * be already uncompressed, then we return a more specific error
10963 * code to hopefully save somebody some debugging time in the
10966 if (plaintext->len >= 4) {
10967 unsigned int len = ((unsigned int) plaintext->buf[1] << 16) |
10968 ((unsigned int) plaintext->buf[2] << 8) |
10969 (unsigned int) plaintext->buf[3];
10970 if (len == plaintext->len - 4) {
10971 /* This appears to be uncompressed already */
10972 err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD;
10976 PORT_Free(plaintext->buf);
10977 PORT_SetError(err);
10981 PORT_Free(plaintext->buf);
10985 ** Having completed the decompression, check the length again.
10987 if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) {
10988 SSL3_SendAlert(ss, alert_fatal, record_overflow);
10989 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
10993 /* Application data records are processed by the caller of this
10994 ** function, not by this function.
10996 if (rType == content_application_data) {
10997 if (ss->firstHsDone)
10999 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11000 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
11004 /* It's a record that must be handled by ssl itself, not the application.
11007 /* XXX Get the xmit lock here. Odds are very high that we'll be xmiting
11008 * data ang getting the xmit lock here prevents deadlocks.
11010 ssl_GetSSL3HandshakeLock(ss);
11012 /* All the functions called in this switch MUST set error code if
11013 ** they return SECFailure or SECWouldBlock.
11016 case content_change_cipher_spec:
11017 rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
11019 case content_alert:
11020 rv = ssl3_HandleAlert(ss, databuf);
11022 case content_handshake:
11023 if (!IS_DTLS(ss)) {
11024 rv = ssl3_HandleHandshake(ss, databuf);
11026 rv = dtls_HandleHandshake(ss, databuf);
11030 case content_application_data is handled before this switch
11033 SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
11034 SSL_GETPID(), ss->fd, cText->type));
11035 /* XXX Send an alert ??? */
11036 PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
11041 ssl_ReleaseSSL3HandshakeLock(ss);
11047 * Initialization functions
11050 /* Called from ssl3_InitState, immediately below. */
11051 /* Caller must hold the SpecWriteLock. */
11053 ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
11055 spec->cipher_def = &bulk_cipher_defs[cipher_null];
11056 PORT_Assert(spec->cipher_def->cipher == cipher_null);
11057 spec->mac_def = &mac_defs[mac_null];
11058 PORT_Assert(spec->mac_def->mac == mac_null);
11059 spec->encode = Null_Cipher;
11060 spec->decode = Null_Cipher;
11061 spec->destroy = NULL;
11062 spec->compressor = NULL;
11063 spec->decompressor = NULL;
11064 spec->destroyCompressContext = NULL;
11065 spec->destroyDecompressContext = NULL;
11066 spec->mac_size = 0;
11067 spec->master_secret = NULL;
11068 spec->bypassCiphers = PR_FALSE;
11070 spec->msItem.data = NULL;
11071 spec->msItem.len = 0;
11073 spec->client.write_key = NULL;
11074 spec->client.write_mac_key = NULL;
11075 spec->client.write_mac_context = NULL;
11077 spec->server.write_key = NULL;
11078 spec->server.write_mac_key = NULL;
11079 spec->server.write_mac_context = NULL;
11081 spec->write_seq_num.high = 0;
11082 spec->write_seq_num.low = 0;
11084 spec->read_seq_num.high = 0;
11085 spec->read_seq_num.low = 0;
11088 dtls_InitRecvdRecords(&spec->recvdRecords);
11090 spec->version = ss->vrange.max;
11093 /* Called from: ssl3_SendRecord
11094 ** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake()
11095 ** ssl3_SendClientHello()
11096 ** ssl3_HandleV2ClientHello()
11097 ** ssl3_HandleRecord()
11099 ** This function should perhaps acquire and release the SpecWriteLock.
11104 ssl3_InitState(sslSocket *ss)
11106 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11108 if (ss->ssl3.initialized)
11109 return SECSuccess; /* Function should be idempotent */
11111 ss->ssl3.policy = SSL_ALLOWED;
11113 ssl_GetSpecWriteLock(ss);
11114 ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0];
11115 ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1];
11116 ss->ssl3.hs.sendingSCSV = PR_FALSE;
11117 ssl3_InitCipherSpec(ss, ss->ssl3.crSpec);
11118 ssl3_InitCipherSpec(ss, ss->ssl3.prSpec);
11120 ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello;
11121 #ifdef NSS_ENABLE_ECC
11122 ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss);
11124 ssl_ReleaseSpecWriteLock(ss);
11126 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
11129 ss->ssl3.hs.sendMessageSeq = 0;
11130 ss->ssl3.hs.recvMessageSeq = 0;
11131 ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS;
11132 ss->ssl3.hs.rtRetries = 0;
11133 ss->ssl3.hs.recvdHighWater = -1;
11134 PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
11135 dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
11138 PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
11139 ss->ssl3.hs.messages.buf = NULL;
11140 ss->ssl3.hs.messages.space = 0;
11142 ss->ssl3.initialized = PR_TRUE;
11146 /* Returns a reference counted object that contains a key pair.
11147 * Or NULL on failure. Initial ref count is 1.
11148 * Uses the keys in the pair as input.
11151 ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey)
11153 ssl3KeyPair * pair;
11155 if (!privKey || !pubKey) {
11156 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
11159 pair = PORT_ZNew(ssl3KeyPair);
11161 return NULL; /* error code is set. */
11162 pair->refCount = 1;
11163 pair->privKey = privKey;
11164 pair->pubKey = pubKey;
11165 return pair; /* success */
11169 ssl3_GetKeyPairRef(ssl3KeyPair * keyPair)
11171 PR_ATOMIC_INCREMENT(&keyPair->refCount);
11176 ssl3_FreeKeyPair(ssl3KeyPair * keyPair)
11178 PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount);
11180 if (keyPair->privKey)
11181 SECKEY_DestroyPrivateKey(keyPair->privKey);
11182 if (keyPair->pubKey)
11183 SECKEY_DestroyPublicKey( keyPair->pubKey);
11184 PORT_Free(keyPair);
11191 * Creates the public and private RSA keys for SSL Step down.
11192 * Called from SSL_ConfigSecureServer in sslsecur.c
11195 ssl3_CreateRSAStepDownKeys(sslSocket *ss)
11197 SECStatus rv = SECSuccess;
11198 SECKEYPrivateKey * privKey; /* RSA step down key */
11199 SECKEYPublicKey * pubKey; /* RSA step down key */
11201 if (ss->stepDownKeyPair)
11202 ssl3_FreeKeyPair(ss->stepDownKeyPair);
11203 ss->stepDownKeyPair = NULL;
11204 #ifndef HACKED_EXPORT_SERVER
11205 /* Sigh, should have a get key strength call for private keys */
11206 if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) >
11207 EXPORT_RSA_KEY_LENGTH) {
11208 /* need to ask for the key size in bits */
11209 privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB,
11211 if (!privKey || !pubKey ||
11212 !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) {
11213 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
11222 /* record the export policy for this cipher suite */
11224 ssl3_SetPolicy(ssl3CipherSuite which, int policy)
11226 ssl3CipherSuiteCfg *suite;
11228 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
11229 if (suite == NULL) {
11230 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
11232 suite->policy = policy;
11238 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
11240 ssl3CipherSuiteCfg *suite;
11244 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
11246 policy = suite->policy;
11249 policy = SSL_NOT_ALLOWED;
11250 rv = SECFailure; /* err code was set by Lookup. */
11256 /* record the user preference for this suite */
11258 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
11260 ssl3CipherSuiteCfg *suite;
11262 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
11263 if (suite == NULL) {
11264 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
11266 suite->enabled = enabled;
11270 /* return the user preference for this suite */
11272 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
11274 ssl3CipherSuiteCfg *suite;
11278 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
11280 pref = suite->enabled;
11283 pref = SSL_NOT_ALLOWED;
11284 rv = SECFailure; /* err code was set by Lookup. */
11291 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
11293 ssl3CipherSuiteCfg *suite;
11295 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
11296 if (suite == NULL) {
11297 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
11299 suite->enabled = enabled;
11304 ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
11306 ssl3CipherSuiteCfg *suite;
11310 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
11312 pref = suite->enabled;
11315 pref = SSL_NOT_ALLOWED;
11316 rv = SECFailure; /* err code was set by Lookup. */
11322 /* copy global default policy into socket. */
11324 ssl3_InitSocketPolicy(sslSocket *ss)
11326 PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites);
11329 /* ssl3_config_match_init must have already been called by
11330 * the caller of this function.
11333 ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size)
11337 PORT_Assert(ss != 0);
11339 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
11342 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
11347 *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE);
11351 /* ssl3_config_match_init was called by the caller of this function. */
11352 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
11353 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
11354 if (config_match(suite, SSL_ALLOWED, PR_TRUE)) {
11357 *cs++ = (suite->cipher_suite >> 8) & 0xFF;
11358 *cs++ = suite->cipher_suite & 0xFF;
11368 ** If ssl3 socket has completed the first handshake, and is in idle state,
11369 ** then start a new handshake.
11370 ** If flushCache is true, the SID cache will be flushed first, forcing a
11371 ** "Full" handshake (not a session restart handshake), to be done.
11373 ** called from SSL_RedoHandshake(), which already holds the handshake locks.
11376 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
11378 sslSessionID * sid = ss->sec.ci.sid;
11381 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
11383 if (!ss->firstHsDone ||
11384 ((ss->version >= SSL_LIBRARY_VERSION_3_0) &&
11385 ss->ssl3.initialized &&
11386 (ss->ssl3.hs.ws != idle_handshake))) {
11387 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
11392 dtls_RehandshakeCleanup(ss);
11395 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
11396 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
11399 if (sid && flushCache) {
11400 if (ss->sec.uncache)
11401 ss->sec.uncache(sid); /* remove it from whichever cache it's in. */
11402 ssl_FreeSID(sid); /* dec ref count and free if zero. */
11403 ss->sec.ci.sid = NULL;
11406 ssl_GetXmitBufLock(ss); /**************************************/
11408 /* start off a new handshake. */
11409 rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss)
11410 : ssl3_SendClientHello(ss, PR_FALSE);
11412 ssl_ReleaseXmitBufLock(ss); /**************************************/
11416 /* Called from ssl_DestroySocketContents() in sslsock.c */
11418 ssl3_DestroySSL3Info(sslSocket *ss)
11421 if (ss->ssl3.clientCertificate != NULL)
11422 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
11424 if (ss->ssl3.clientPrivateKey != NULL)
11425 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
11427 if (ss->ssl3.peerCertArena != NULL)
11428 ssl3_CleanupPeerCerts(ss);
11430 if (ss->ssl3.clientCertChain != NULL) {
11431 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
11432 ss->ssl3.clientCertChain = NULL;
11435 /* clean up handshake */
11436 #ifndef NO_PKCS11_BYPASS
11437 if (ss->opt.bypassPKCS11) {
11438 if (ss->ssl3.hs.hashType == handshake_hash_combo) {
11439 SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE);
11440 MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE);
11441 } else if (ss->ssl3.hs.hashType == handshake_hash_single) {
11442 ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE);
11446 if (ss->ssl3.hs.md5) {
11447 PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
11449 if (ss->ssl3.hs.sha) {
11450 PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
11452 if (ss->ssl3.hs.clientSigAndHash) {
11453 PORT_Free(ss->ssl3.hs.clientSigAndHash);
11455 if (ss->ssl3.hs.messages.buf) {
11456 PORT_Free(ss->ssl3.hs.messages.buf);
11457 ss->ssl3.hs.messages.buf = NULL;
11458 ss->ssl3.hs.messages.len = 0;
11459 ss->ssl3.hs.messages.space = 0;
11462 /* free the SSL3Buffer (msg_body) */
11463 PORT_Free(ss->ssl3.hs.msg_body.buf);
11465 /* free up the CipherSpecs */
11466 ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE/*freeSrvName*/);
11467 ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE/*freeSrvName*/);
11469 /* Destroy the DTLS data */
11471 dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
11472 if (ss->ssl3.hs.recvdFragments.buf) {
11473 PORT_Free(ss->ssl3.hs.recvdFragments.buf);
11477 ss->ssl3.initialized = PR_FALSE;
11479 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
11482 /* End of ssl3con.c */