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. */
14 #include "cryptohi.h" /* for DSAU_ stuff */
31 #ifndef NO_PKCS11_BYPASS
35 /* This is a bodge to allow this code to be compiled against older NSS headers
36 * that don't contain the TLS 1.2 changes. */
37 #ifndef CKM_NSS_TLS_PRF_GENERAL_SHA256
38 #define CKM_NSS_TLS_PRF_GENERAL_SHA256 (CKM_NSS + 21)
39 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256 (CKM_NSS + 22)
40 #define CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256 (CKM_NSS + 23)
41 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
44 /* This is a bodge to allow this code to be compiled against older NSS
46 #ifndef CKM_NSS_CHACHA20_POLY1305
47 #define CKM_NSS_CHACHA20_POLY1305 (CKM_NSS + 26)
49 typedef struct CK_NSS_AEAD_PARAMS
{
50 CK_BYTE_PTR pIv
; /* This is the nonce. */
60 #ifdef NSS_ENABLE_ZLIB
68 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
69 (x)->pValue=(v); (x)->ulValueLen = (l);
72 static SECStatus
ssl3_AuthCertificate(sslSocket
*ss
);
73 static void ssl3_CleanupPeerCerts(sslSocket
*ss
);
74 static void ssl3_CopyPeerCertsFromSID(sslSocket
*ss
, sslSessionID
*sid
);
75 static PK11SymKey
*ssl3_GenerateRSAPMS(sslSocket
*ss
, ssl3CipherSpec
*spec
,
76 PK11SlotInfo
* serverKeySlot
);
77 static SECStatus
ssl3_DeriveMasterSecret(sslSocket
*ss
, PK11SymKey
*pms
);
78 static SECStatus
ssl3_DeriveConnectionKeysPKCS11(sslSocket
*ss
);
79 static SECStatus
ssl3_HandshakeFailure( sslSocket
*ss
);
80 static SECStatus
ssl3_InitState( sslSocket
*ss
);
81 static SECStatus
ssl3_SendCertificate( sslSocket
*ss
);
82 static SECStatus
ssl3_SendCertificateStatus( sslSocket
*ss
);
83 static SECStatus
ssl3_SendEmptyCertificate( sslSocket
*ss
);
84 static SECStatus
ssl3_SendCertificateRequest(sslSocket
*ss
);
85 static SECStatus
ssl3_SendNextProto( sslSocket
*ss
);
86 static SECStatus
ssl3_SendEncryptedExtensions(sslSocket
*ss
);
87 static SECStatus
ssl3_SendFinished( sslSocket
*ss
, PRInt32 flags
);
88 static SECStatus
ssl3_SendServerHello( sslSocket
*ss
);
89 static SECStatus
ssl3_SendServerHelloDone( sslSocket
*ss
);
90 static SECStatus
ssl3_SendServerKeyExchange( sslSocket
*ss
);
91 static SECStatus
ssl3_UpdateHandshakeHashes( sslSocket
*ss
,
92 const unsigned char *b
,
94 static SECStatus
ssl3_FlushHandshakeMessages(sslSocket
*ss
, PRInt32 flags
);
95 static int ssl3_OIDToTLSHashAlgorithm(SECOidTag oid
);
97 static SECStatus
Null_Cipher(void *ctx
, unsigned char *output
, int *outputLen
,
98 int maxOutputLen
, const unsigned char *input
,
100 #ifndef NO_PKCS11_BYPASS
101 static SECStatus
ssl3_AESGCMBypass(ssl3KeyMaterial
*keys
, PRBool doDecrypt
,
102 unsigned char *out
, int *outlen
, int maxout
,
103 const unsigned char *in
, int inlen
,
104 const unsigned char *additionalData
,
105 int additionalDataLen
);
108 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */
109 #define MIN_SEND_BUF_LENGTH 4000
111 /* This list of SSL3 cipher suites is sorted in descending order of
112 * precedence (desirability). It only includes cipher suites we implement.
113 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
114 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
116 * Important: See bug 946147 before enabling, reordering, or adding any cipher
117 * suites to this list.
119 static ssl3CipherSuiteCfg cipherSuites
[ssl_V3_SUITES_IMPLEMENTED
] = {
120 /* cipher_suite policy enabled isPresent */
122 #ifndef NSS_DISABLE_ECC
123 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
124 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
125 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
126 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
127 /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around
130 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
131 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
132 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
133 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
134 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
135 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
136 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
137 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
138 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
139 { TLS_ECDHE_RSA_WITH_RC4_128_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
140 #endif /* NSS_DISABLE_ECC */
142 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
143 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
144 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
145 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
146 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
147 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
148 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
149 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
150 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
151 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
152 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
153 { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
154 { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
155 { TLS_DHE_DSS_WITH_RC4_128_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
157 #ifndef NSS_DISABLE_ECC
158 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
159 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
160 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
161 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
162 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
163 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
164 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
165 { TLS_ECDH_RSA_WITH_RC4_128_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
166 #endif /* NSS_DISABLE_ECC */
169 { TLS_RSA_WITH_AES_128_GCM_SHA256
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
170 { TLS_RSA_WITH_AES_128_CBC_SHA
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
171 { TLS_RSA_WITH_AES_128_CBC_SHA256
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
172 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
173 { TLS_RSA_WITH_AES_256_CBC_SHA
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
174 { TLS_RSA_WITH_AES_256_CBC_SHA256
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
175 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
176 { TLS_RSA_WITH_SEED_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
177 { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
178 { TLS_RSA_WITH_3DES_EDE_CBC_SHA
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
179 { TLS_RSA_WITH_RC4_128_SHA
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
180 { TLS_RSA_WITH_RC4_128_MD5
, SSL_ALLOWED
, PR_TRUE
, PR_FALSE
},
182 /* 56-bit DES "domestic" cipher suites */
183 { TLS_DHE_RSA_WITH_DES_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
184 { TLS_DHE_DSS_WITH_DES_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
185 { SSL_RSA_FIPS_WITH_DES_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
186 { TLS_RSA_WITH_DES_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
188 /* export ciphersuites with 1024-bit public key exchange keys */
189 { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
190 { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
192 /* export ciphersuites with 512-bit public key exchange keys */
193 { TLS_RSA_EXPORT_WITH_RC4_40_MD5
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
194 { TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
196 /* ciphersuites with no encryption */
197 #ifndef NSS_DISABLE_ECC
198 { TLS_ECDHE_ECDSA_WITH_NULL_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
199 { TLS_ECDHE_RSA_WITH_NULL_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
200 { TLS_ECDH_RSA_WITH_NULL_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
201 { TLS_ECDH_ECDSA_WITH_NULL_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
202 #endif /* NSS_DISABLE_ECC */
203 { TLS_RSA_WITH_NULL_SHA
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
204 { TLS_RSA_WITH_NULL_SHA256
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
205 { TLS_RSA_WITH_NULL_MD5
, SSL_ALLOWED
, PR_FALSE
, PR_FALSE
},
208 /* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order.
211 void ssl3_CheckCipherSuiteOrderConsistency()
215 /* Note that SSL_ImplementedCiphers has more elements than cipherSuites
216 * because it SSL_ImplementedCiphers includes SSL 2.0 cipher suites.
218 PORT_Assert(SSL_NumImplementedCiphers
>= PR_ARRAY_SIZE(cipherSuites
));
220 for (i
= 0; i
< PR_ARRAY_SIZE(cipherSuites
); ++i
) {
221 PORT_Assert(SSL_ImplementedCiphers
[i
] == cipherSuites
[i
].cipher_suite
);
226 /* This list of SSL3 compression methods is sorted in descending order of
227 * precedence (desirability). It only includes compression methods we
230 static const /*SSLCompressionMethod*/ PRUint8 compressions
[] = {
231 #ifdef NSS_ENABLE_ZLIB
232 ssl_compression_deflate
,
237 static const int compressionMethodsCount
=
238 sizeof(compressions
) / sizeof(compressions
[0]);
240 /* compressionEnabled returns true iff the compression algorithm is enabled
241 * for the given SSL socket. */
243 compressionEnabled(sslSocket
*ss
, SSLCompressionMethod compression
)
245 switch (compression
) {
246 case ssl_compression_null
:
247 return PR_TRUE
; /* Always enabled */
248 #ifdef NSS_ENABLE_ZLIB
249 case ssl_compression_deflate
:
250 if (ss
->version
< SSL_LIBRARY_VERSION_TLS_1_3
) {
251 return ss
->opt
.enableDeflate
;
260 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types
[] = {
262 #ifndef NSS_DISABLE_ECC
264 #endif /* NSS_DISABLE_ECC */
268 /* This block is the contents of the supported_signature_algorithms field of
269 * our TLS 1.2 CertificateRequest message, in wire format. See
270 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
272 * This block contains only sha256 entries because we only support TLS 1.2
273 * CertificateVerify messages that use the handshake hash. */
274 static const PRUint8 supported_signature_algorithms
[] = {
275 tls_hash_sha256
, tls_sig_rsa
,
276 #ifndef NSS_DISABLE_ECC
277 tls_hash_sha256
, tls_sig_ecdsa
,
279 tls_hash_sha256
, tls_sig_dsa
,
282 #define EXPORT_RSA_KEY_LENGTH 64 /* bytes */
285 /* This global item is used only in servers. It is is initialized by
286 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
288 CERTDistNames
*ssl3_server_ca_list
= NULL
;
289 static SSL3Statistics ssl3stats
;
291 /* indexed by SSL3BulkCipher */
292 static const ssl3BulkCipherDef bulk_cipher_defs
[] = {
293 /* |--------- Lengths --------| */
294 /* cipher calg k s type i b t n */
300 {cipher_null
, calg_null
, 0, 0, type_stream
, 0, 0, 0, 0},
301 {cipher_rc4
, calg_rc4
, 16,16, type_stream
, 0, 0, 0, 0},
302 {cipher_rc4_40
, calg_rc4
, 16, 5, type_stream
, 0, 0, 0, 0},
303 {cipher_rc4_56
, calg_rc4
, 16, 7, type_stream
, 0, 0, 0, 0},
304 {cipher_rc2
, calg_rc2
, 16,16, type_block
, 8, 8, 0, 0},
305 {cipher_rc2_40
, calg_rc2
, 16, 5, type_block
, 8, 8, 0, 0},
306 {cipher_des
, calg_des
, 8, 8, type_block
, 8, 8, 0, 0},
307 {cipher_3des
, calg_3des
, 24,24, type_block
, 8, 8, 0, 0},
308 {cipher_des40
, calg_des
, 8, 5, type_block
, 8, 8, 0, 0},
309 {cipher_idea
, calg_idea
, 16,16, type_block
, 8, 8, 0, 0},
310 {cipher_aes_128
, calg_aes
, 16,16, type_block
, 16,16, 0, 0},
311 {cipher_aes_256
, calg_aes
, 32,32, type_block
, 16,16, 0, 0},
312 {cipher_camellia_128
, calg_camellia
, 16,16, type_block
, 16,16, 0, 0},
313 {cipher_camellia_256
, calg_camellia
, 32,32, type_block
, 16,16, 0, 0},
314 {cipher_seed
, calg_seed
, 16,16, type_block
, 16,16, 0, 0},
315 {cipher_aes_128_gcm
, calg_aes_gcm
, 16,16, type_aead
, 4, 0,16, 8},
316 {cipher_chacha20
, calg_chacha20
, 32,32, type_aead
, 0, 0,16, 0},
317 {cipher_missing
, calg_null
, 0, 0, type_stream
, 0, 0, 0, 0},
320 static const ssl3KEADef kea_defs
[] =
321 { /* indexed by SSL3KeyExchangeAlgorithm */
322 /* kea exchKeyType signKeyType is_limited limit tls_keygen ephemeral */
323 {kea_null
, kt_null
, sign_null
, PR_FALSE
, 0, PR_FALSE
, PR_FALSE
},
324 {kea_rsa
, kt_rsa
, sign_rsa
, PR_FALSE
, 0, PR_FALSE
, PR_FALSE
},
325 {kea_rsa_export
, kt_rsa
, sign_rsa
, PR_TRUE
, 512, PR_FALSE
, PR_TRUE
},
326 {kea_rsa_export_1024
,kt_rsa
, sign_rsa
, PR_TRUE
, 1024, PR_FALSE
, PR_TRUE
},
327 {kea_dh_dss
, kt_dh
, sign_dsa
, PR_FALSE
, 0, PR_FALSE
, PR_FALSE
},
328 {kea_dh_dss_export
, kt_dh
, sign_dsa
, PR_TRUE
, 512, PR_FALSE
, PR_FALSE
},
329 {kea_dh_rsa
, kt_dh
, sign_rsa
, PR_FALSE
, 0, PR_FALSE
, PR_FALSE
},
330 {kea_dh_rsa_export
, kt_dh
, sign_rsa
, PR_TRUE
, 512, PR_FALSE
, PR_FALSE
},
331 {kea_dhe_dss
, kt_dh
, sign_dsa
, PR_FALSE
, 0, PR_FALSE
, PR_TRUE
},
332 {kea_dhe_dss_export
, kt_dh
, sign_dsa
, PR_TRUE
, 512, PR_FALSE
, PR_TRUE
},
333 {kea_dhe_rsa
, kt_dh
, sign_rsa
, PR_FALSE
, 0, PR_FALSE
, PR_TRUE
},
334 {kea_dhe_rsa_export
, kt_dh
, sign_rsa
, PR_TRUE
, 512, PR_FALSE
, PR_TRUE
},
335 {kea_dh_anon
, kt_dh
, sign_null
, PR_FALSE
, 0, PR_FALSE
, PR_TRUE
},
336 {kea_dh_anon_export
, kt_dh
, sign_null
, PR_TRUE
, 512, PR_FALSE
, PR_TRUE
},
337 {kea_rsa_fips
, kt_rsa
, sign_rsa
, PR_FALSE
, 0, PR_TRUE
, PR_FALSE
},
338 #ifndef NSS_DISABLE_ECC
339 {kea_ecdh_ecdsa
, kt_ecdh
, sign_ecdsa
, PR_FALSE
, 0, PR_FALSE
, PR_FALSE
},
340 {kea_ecdhe_ecdsa
, kt_ecdh
, sign_ecdsa
, PR_FALSE
, 0, PR_FALSE
, PR_TRUE
},
341 {kea_ecdh_rsa
, kt_ecdh
, sign_rsa
, PR_FALSE
, 0, PR_FALSE
, PR_FALSE
},
342 {kea_ecdhe_rsa
, kt_ecdh
, sign_rsa
, PR_FALSE
, 0, PR_FALSE
, PR_TRUE
},
343 {kea_ecdh_anon
, kt_ecdh
, sign_null
, PR_FALSE
, 0, PR_FALSE
, PR_TRUE
},
344 #endif /* NSS_DISABLE_ECC */
347 /* must use ssl_LookupCipherSuiteDef to access */
348 static const ssl3CipherSuiteDef cipher_suite_defs
[] =
350 /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg */
352 {TLS_NULL_WITH_NULL_NULL
, cipher_null
, mac_null
, kea_null
},
353 {TLS_RSA_WITH_NULL_MD5
, cipher_null
, mac_md5
, kea_rsa
},
354 {TLS_RSA_WITH_NULL_SHA
, cipher_null
, mac_sha
, kea_rsa
},
355 {TLS_RSA_WITH_NULL_SHA256
, cipher_null
, hmac_sha256
, kea_rsa
},
356 {TLS_RSA_EXPORT_WITH_RC4_40_MD5
,cipher_rc4_40
, mac_md5
, kea_rsa_export
},
357 {TLS_RSA_WITH_RC4_128_MD5
, cipher_rc4
, mac_md5
, kea_rsa
},
358 {TLS_RSA_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_rsa
},
359 {TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5
,
360 cipher_rc2_40
, mac_md5
, kea_rsa_export
},
361 #if 0 /* not implemented */
362 {TLS_RSA_WITH_IDEA_CBC_SHA
, cipher_idea
, mac_sha
, kea_rsa
},
363 {TLS_RSA_EXPORT_WITH_DES40_CBC_SHA
,
364 cipher_des40
, mac_sha
, kea_rsa_export
},
366 {TLS_RSA_WITH_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_rsa
},
367 {TLS_RSA_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_rsa
},
368 {TLS_DHE_DSS_WITH_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_dhe_dss
},
369 {TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA
,
370 cipher_3des
, mac_sha
, kea_dhe_dss
},
371 {TLS_DHE_DSS_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_dhe_dss
},
372 #if 0 /* not implemented */
373 {TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA
,
374 cipher_des40
, mac_sha
, kea_dh_dss_export
},
375 {TLS_DH_DSS_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_dh_dss
},
376 {TLS_DH_DSS_3DES_CBC_SHA
, cipher_3des
, mac_sha
, kea_dh_dss
},
377 {TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA
,
378 cipher_des40
, mac_sha
, kea_dh_rsa_export
},
379 {TLS_DH_RSA_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_dh_rsa
},
380 {TLS_DH_RSA_3DES_CBC_SHA
, cipher_3des
, mac_sha
, kea_dh_rsa
},
381 {TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
,
382 cipher_des40
, mac_sha
, kea_dh_dss_export
},
383 {TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
,
384 cipher_des40
, mac_sha
, kea_dh_rsa_export
},
386 {TLS_DHE_RSA_WITH_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_dhe_rsa
},
387 {TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
,
388 cipher_3des
, mac_sha
, kea_dhe_rsa
},
390 {SSL_DH_ANON_EXPORT_RC4_40_MD5
, cipher_rc4_40
, mac_md5
, kea_dh_anon_export
},
391 {TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA
,
392 cipher_des40
, mac_sha
, kea_dh_anon_export
},
393 {TLS_DH_anon_WITH_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_dh_anon
},
394 {TLS_DH_anon_WITH_3DES_CBC_SHA
, cipher_3des
, mac_sha
, kea_dh_anon
},
398 /* New TLS cipher suites */
399 {TLS_RSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_rsa
},
400 {TLS_RSA_WITH_AES_128_CBC_SHA256
, cipher_aes_128
, hmac_sha256
, kea_rsa
},
401 {TLS_DHE_DSS_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_dhe_dss
},
402 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_dhe_rsa
},
403 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
, cipher_aes_128
, hmac_sha256
, kea_dhe_rsa
},
404 {TLS_RSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_rsa
},
405 {TLS_RSA_WITH_AES_256_CBC_SHA256
, cipher_aes_256
, hmac_sha256
, kea_rsa
},
406 {TLS_DHE_DSS_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_dhe_dss
},
407 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_dhe_rsa
},
408 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
, cipher_aes_256
, hmac_sha256
, kea_dhe_rsa
},
410 {TLS_DH_DSS_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_dh_dss
},
411 {TLS_DH_RSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_dh_rsa
},
412 {TLS_DH_anon_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_dh_anon
},
413 {TLS_DH_DSS_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_dh_dss
},
414 {TLS_DH_RSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_dh_rsa
},
415 {TLS_DH_anon_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_dh_anon
},
418 {TLS_RSA_WITH_SEED_CBC_SHA
, cipher_seed
, mac_sha
, kea_rsa
},
420 {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
, cipher_camellia_128
, mac_sha
, kea_rsa
},
421 {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA
,
422 cipher_camellia_128
, mac_sha
, kea_dhe_dss
},
423 {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
,
424 cipher_camellia_128
, mac_sha
, kea_dhe_rsa
},
425 {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
, cipher_camellia_256
, mac_sha
, kea_rsa
},
426 {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA
,
427 cipher_camellia_256
, mac_sha
, kea_dhe_dss
},
428 {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
,
429 cipher_camellia_256
, mac_sha
, kea_dhe_rsa
},
431 {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA
,
432 cipher_des
, mac_sha
,kea_rsa_export_1024
},
433 {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA
,
434 cipher_rc4_56
, mac_sha
,kea_rsa_export_1024
},
436 {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_rsa_fips
},
437 {SSL_RSA_FIPS_WITH_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_rsa_fips
},
439 {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
, cipher_aes_128_gcm
, mac_aead
, kea_dhe_rsa
},
440 {TLS_RSA_WITH_AES_128_GCM_SHA256
, cipher_aes_128_gcm
, mac_aead
, kea_rsa
},
441 {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
, cipher_aes_128_gcm
, mac_aead
, kea_ecdhe_rsa
},
442 {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
, cipher_aes_128_gcm
, mac_aead
, kea_ecdhe_ecdsa
},
443 {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305
, cipher_chacha20
, mac_aead
, kea_ecdhe_rsa
},
444 {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
, cipher_chacha20
, mac_aead
, kea_ecdhe_ecdsa
},
446 #ifndef NSS_DISABLE_ECC
447 {TLS_ECDH_ECDSA_WITH_NULL_SHA
, cipher_null
, mac_sha
, kea_ecdh_ecdsa
},
448 {TLS_ECDH_ECDSA_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_ecdh_ecdsa
},
449 {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_ecdh_ecdsa
},
450 {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_ecdh_ecdsa
},
451 {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_ecdh_ecdsa
},
453 {TLS_ECDHE_ECDSA_WITH_NULL_SHA
, cipher_null
, mac_sha
, kea_ecdhe_ecdsa
},
454 {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_ecdhe_ecdsa
},
455 {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_ecdhe_ecdsa
},
456 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_ecdhe_ecdsa
},
457 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
, cipher_aes_128
, hmac_sha256
, kea_ecdhe_ecdsa
},
458 {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_ecdhe_ecdsa
},
460 {TLS_ECDH_RSA_WITH_NULL_SHA
, cipher_null
, mac_sha
, kea_ecdh_rsa
},
461 {TLS_ECDH_RSA_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_ecdh_rsa
},
462 {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_ecdh_rsa
},
463 {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_ecdh_rsa
},
464 {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_ecdh_rsa
},
466 {TLS_ECDHE_RSA_WITH_NULL_SHA
, cipher_null
, mac_sha
, kea_ecdhe_rsa
},
467 {TLS_ECDHE_RSA_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_ecdhe_rsa
},
468 {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_ecdhe_rsa
},
469 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_ecdhe_rsa
},
470 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
, cipher_aes_128
, hmac_sha256
, kea_ecdhe_rsa
},
471 {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_ecdhe_rsa
},
474 {TLS_ECDH_anon_WITH_NULL_SHA
, cipher_null
, mac_sha
, kea_ecdh_anon
},
475 {TLS_ECDH_anon_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_ecdh_anon
},
476 {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_ecdh_anon
},
477 {TLS_ECDH_anon_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_ecdh_anon
},
478 {TLS_ECDH_anon_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_ecdh_anon
},
480 #endif /* NSS_DISABLE_ECC */
483 static const CK_MECHANISM_TYPE kea_alg_defs
[] = {
491 typedef struct SSLCipher2MechStr
{
492 SSLCipherAlgorithm calg
;
493 CK_MECHANISM_TYPE cmech
;
496 /* indexed by type SSLCipherAlgorithm */
497 static const SSLCipher2Mech alg2Mech
[] = {
499 { calg_null
, (CK_MECHANISM_TYPE
)0x80000000L
},
500 { calg_rc4
, CKM_RC4
},
501 { calg_rc2
, CKM_RC2_CBC
},
502 { calg_des
, CKM_DES_CBC
},
503 { calg_3des
, CKM_DES3_CBC
},
504 { calg_idea
, CKM_IDEA_CBC
},
505 { calg_fortezza
, CKM_SKIPJACK_CBC64
},
506 { calg_aes
, CKM_AES_CBC
},
507 { calg_camellia
, CKM_CAMELLIA_CBC
},
508 { calg_seed
, CKM_SEED_CBC
},
509 { calg_aes_gcm
, CKM_AES_GCM
},
510 { calg_chacha20
, CKM_NSS_CHACHA20_POLY1305
},
511 /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */
514 #define mmech_invalid (CK_MECHANISM_TYPE)0x80000000L
515 #define mmech_md5 CKM_SSL3_MD5_MAC
516 #define mmech_sha CKM_SSL3_SHA1_MAC
517 #define mmech_md5_hmac CKM_MD5_HMAC
518 #define mmech_sha_hmac CKM_SHA_1_HMAC
519 #define mmech_sha256_hmac CKM_SHA256_HMAC
521 static const ssl3MACDef mac_defs
[] = { /* indexed by SSL3MACAlgorithm */
522 /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */
523 /* mac mmech pad_size mac_size */
524 { mac_null
, mmech_invalid
, 0, 0 },
525 { mac_md5
, mmech_md5
, 48, MD5_LENGTH
},
526 { mac_sha
, mmech_sha
, 40, SHA1_LENGTH
},
527 {hmac_md5
, mmech_md5_hmac
, 0, MD5_LENGTH
},
528 {hmac_sha
, mmech_sha_hmac
, 0, SHA1_LENGTH
},
529 {hmac_sha256
, mmech_sha256_hmac
, 0, SHA256_LENGTH
},
530 { mac_aead
, mmech_invalid
, 0, 0 },
533 /* indexed by SSL3BulkCipher */
534 const char * const ssl3_cipherName
[] = {
554 #ifndef NSS_DISABLE_ECC
555 /* The ECCWrappedKeyInfo structure defines how various pieces of
556 * information are laid out within wrappedSymmetricWrappingkey
557 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
558 * a 512-byte buffer (see sslimpl.h), the variable length field
559 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
561 * XXX For now, NSS only supports named elliptic curves of size 571 bits
562 * or smaller. The public value will fit within 145 bytes and EC params
563 * will fit within 12 bytes. We'll need to revisit this when NSS
564 * supports arbitrary curves.
566 #define MAX_EC_WRAPPED_KEY_BUFLEN 504
568 typedef struct ECCWrappedKeyInfoStr
{
569 PRUint16 size
; /* EC public key size in bits */
570 PRUint16 encodedParamLen
; /* length (in bytes) of DER encoded EC params */
571 PRUint16 pubValueLen
; /* length (in bytes) of EC public value */
572 PRUint16 wrappedKeyLen
; /* length (in bytes) of the wrapped key */
573 PRUint8 var
[MAX_EC_WRAPPED_KEY_BUFLEN
]; /* this buffer contains the */
574 /* EC public-key params, the EC public value and the wrapped key */
576 #endif /* NSS_DISABLE_ECC */
581 ssl3_DecodeHandshakeType(int msgType
)
584 static char line
[40];
587 case hello_request
: rv
= "hello_request (0)"; break;
588 case client_hello
: rv
= "client_hello (1)"; break;
589 case server_hello
: rv
= "server_hello (2)"; break;
590 case hello_verify_request
: rv
= "hello_verify_request (3)"; break;
591 case certificate
: rv
= "certificate (11)"; break;
592 case server_key_exchange
: rv
= "server_key_exchange (12)"; break;
593 case certificate_request
: rv
= "certificate_request (13)"; break;
594 case server_hello_done
: rv
= "server_hello_done (14)"; break;
595 case certificate_verify
: rv
= "certificate_verify (15)"; break;
596 case client_key_exchange
: rv
= "client_key_exchange (16)"; break;
597 case finished
: rv
= "finished (20)"; break;
599 sprintf(line
, "*UNKNOWN* handshake type! (%d)", msgType
);
606 ssl3_DecodeContentType(int msgType
)
609 static char line
[40];
612 case content_change_cipher_spec
:
613 rv
= "change_cipher_spec (20)"; break;
614 case content_alert
: rv
= "alert (21)"; break;
615 case content_handshake
: rv
= "handshake (22)"; break;
616 case content_application_data
:
617 rv
= "application_data (23)"; break;
619 sprintf(line
, "*UNKNOWN* record type! (%d)", msgType
);
628 SSL_GetStatistics(void)
633 typedef struct tooLongStr
{
634 #if defined(IS_LITTLE_ENDIAN)
643 void SSL_AtomicIncrementLong(long * x
)
645 if ((sizeof *x
) == sizeof(PRInt32
)) {
646 PR_ATOMIC_INCREMENT((PRInt32
*)x
);
648 tooLong
* tl
= (tooLong
*)x
;
649 if (PR_ATOMIC_INCREMENT(&tl
->low
) == 0)
650 PR_ATOMIC_INCREMENT(&tl
->high
);
655 ssl3_CipherSuiteAllowedForVersionRange(
656 ssl3CipherSuite cipherSuite
,
657 const SSLVersionRange
*vrange
)
659 switch (cipherSuite
) {
660 /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or
661 * later. This set of cipher suites is similar to, but different from, the
662 * set of cipher suites considered exportable by SSL_IsExportCipherSuite.
664 case TLS_RSA_EXPORT_WITH_RC4_40_MD5
:
665 case TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5
:
666 /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
667 * TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented
668 * TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
669 * TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented
670 * TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
671 * TLS_DH_anon_EXPORT_WITH_RC4_40_MD5: never implemented
672 * TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA: never implemented
674 return vrange
->min
<= SSL_LIBRARY_VERSION_TLS_1_0
;
676 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
:
677 case TLS_RSA_WITH_AES_256_CBC_SHA256
:
678 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
:
679 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
:
680 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
:
681 case TLS_RSA_WITH_AES_128_CBC_SHA256
:
682 case TLS_RSA_WITH_AES_128_GCM_SHA256
:
683 case TLS_RSA_WITH_NULL_SHA256
:
684 return vrange
->max
== SSL_LIBRARY_VERSION_TLS_1_2
;
686 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305
:
687 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
:
688 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
:
689 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
:
690 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
:
691 return vrange
->max
>= SSL_LIBRARY_VERSION_TLS_1_2
;
693 /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and
695 case TLS_ECDH_ECDSA_WITH_NULL_SHA
:
696 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA
:
697 case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
:
698 case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
:
699 case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
:
700 case TLS_ECDHE_ECDSA_WITH_NULL_SHA
:
701 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
:
702 case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
:
703 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
:
704 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
:
705 case TLS_ECDH_RSA_WITH_NULL_SHA
:
706 case TLS_ECDH_RSA_WITH_RC4_128_SHA
:
707 case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
:
708 case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
:
709 case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
:
710 case TLS_ECDHE_RSA_WITH_NULL_SHA
:
711 case TLS_ECDHE_RSA_WITH_RC4_128_SHA
:
712 case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
:
713 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
:
714 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
:
715 return vrange
->max
>= SSL_LIBRARY_VERSION_TLS_1_0
&&
716 vrange
->min
< SSL_LIBRARY_VERSION_TLS_1_3
;
719 return vrange
->min
< SSL_LIBRARY_VERSION_TLS_1_3
;
723 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */
724 /* XXX This does a linear search. A binary search would be better. */
725 static const ssl3CipherSuiteDef
*
726 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite
)
728 int cipher_suite_def_len
=
729 sizeof(cipher_suite_defs
) / sizeof(cipher_suite_defs
[0]);
732 for (i
= 0; i
< cipher_suite_def_len
; i
++) {
733 if (cipher_suite_defs
[i
].cipher_suite
== suite
)
734 return &cipher_suite_defs
[i
];
736 PORT_Assert(PR_FALSE
); /* We should never get here. */
737 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE
);
741 /* Find the cipher configuration struct associate with suite */
742 /* XXX This does a linear search. A binary search would be better. */
743 static ssl3CipherSuiteCfg
*
744 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite
, ssl3CipherSuiteCfg
*suites
)
748 for (i
= 0; i
< ssl_V3_SUITES_IMPLEMENTED
; i
++) {
749 if (suites
[i
].cipher_suite
== suite
)
752 /* return NULL and let the caller handle it. */
753 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE
);
758 /* Initialize the suite->isPresent value for config_match
759 * Returns count of enabled ciphers supported by extant tokens,
760 * regardless of policy or user preference.
761 * If this returns zero, the user cannot do SSL v3.
764 ssl3_config_match_init(sslSocket
*ss
)
766 ssl3CipherSuiteCfg
* suite
;
767 const ssl3CipherSuiteDef
*cipher_def
;
768 SSLCipherAlgorithm cipher_alg
;
769 CK_MECHANISM_TYPE cipher_mech
;
770 SSL3KEAType exchKeyType
;
775 sslServerCerts
*svrAuth
;
779 PORT_SetError(SEC_ERROR_INVALID_ARGS
);
782 if (SSL3_ALL_VERSIONS_DISABLED(&ss
->vrange
)) {
785 isServer
= (PRBool
)(ss
->sec
.isServer
!= 0);
787 for (i
= 0; i
< ssl_V3_SUITES_IMPLEMENTED
; i
++) {
788 suite
= &ss
->cipherSuites
[i
];
789 if (suite
->enabled
) {
791 /* We need the cipher defs to see if we have a token that can handle
792 * this cipher. It isn't part of the static definition.
794 cipher_def
= ssl_LookupCipherSuiteDef(suite
->cipher_suite
);
796 suite
->isPresent
= PR_FALSE
;
799 cipher_alg
= bulk_cipher_defs
[cipher_def
->bulk_cipher_alg
].calg
;
800 PORT_Assert( alg2Mech
[cipher_alg
].calg
== cipher_alg
);
801 cipher_mech
= alg2Mech
[cipher_alg
].cmech
;
803 kea_defs
[cipher_def
->key_exchange_alg
].exchKeyType
;
804 #ifdef NSS_DISABLE_ECC
805 svrAuth
= ss
->serverCerts
+ exchKeyType
;
807 /* XXX SSLKEAType isn't really a good choice for
808 * indexing certificates. It doesn't work for
809 * (EC)DHE-* ciphers. Here we use a hack to ensure
810 * that the server uses an RSA cert for (EC)DHE-RSA.
812 switch (cipher_def
->key_exchange_alg
) {
814 #if NSS_SERVER_DHE_IMPLEMENTED
815 /* XXX NSS does not yet implement the server side of _DHE_
816 * cipher suites. Correcting the computation for svrAuth,
817 * as the case below does, causes NSS SSL servers to begin to
818 * negotiate cipher suites they do not implement. So, until
819 * server side _DHE_ is implemented, keep this disabled.
823 svrAuth
= ss
->serverCerts
+ kt_rsa
;
828 * XXX We ought to have different indices for
829 * ECDSA- and RSA-signed EC certificates so
830 * we could support both key exchange mechanisms
831 * simultaneously. For now, both of them use
832 * whatever is in the certificate slot for kt_ecdh
835 svrAuth
= ss
->serverCerts
+ exchKeyType
;
838 #endif /* NSS_DISABLE_ECC */
840 /* Mark the suites that are backed by real tokens, certs and keys */
841 suite
->isPresent
= (PRBool
)
842 (((exchKeyType
== kt_null
) ||
843 ((!isServer
|| (svrAuth
->serverKeyPair
&&
844 svrAuth
->SERVERKEY
&&
845 svrAuth
->serverCertChain
)) &&
846 PK11_TokenExists(kea_alg_defs
[exchKeyType
]))) &&
847 ((cipher_alg
== calg_null
) || PK11_TokenExists(cipher_mech
)));
848 if (suite
->isPresent
)
852 PORT_Assert(numPresent
> 0 || numEnabled
== 0);
853 if (numPresent
<= 0) {
854 PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED
);
860 /* return PR_TRUE if suite matches policy, enabled state and is applicable to
861 * the given version range. */
862 /* It would be a REALLY BAD THING (tm) if we ever permitted the use
863 ** of a cipher that was NOT_ALLOWED. So, if this is ever called with
864 ** policy == SSL_NOT_ALLOWED, report no match.
866 /* adjust suite enabled to the availability of a token that can do the
869 config_match(ssl3CipherSuiteCfg
*suite
, int policy
, PRBool enabled
,
870 const SSLVersionRange
*vrange
)
872 PORT_Assert(policy
!= SSL_NOT_ALLOWED
&& enabled
!= PR_FALSE
);
873 if (policy
== SSL_NOT_ALLOWED
|| !enabled
)
875 return (PRBool
)(suite
->enabled
&&
877 suite
->policy
!= SSL_NOT_ALLOWED
&&
878 suite
->policy
<= policy
&&
879 ssl3_CipherSuiteAllowedForVersionRange(
880 suite
->cipher_suite
, vrange
));
883 /* return number of cipher suites that match policy, enabled state and are
884 * applicable for the configured protocol version range. */
885 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */
887 count_cipher_suites(sslSocket
*ss
, int policy
, PRBool enabled
)
891 if (SSL3_ALL_VERSIONS_DISABLED(&ss
->vrange
)) {
894 for (i
= 0; i
< ssl_V3_SUITES_IMPLEMENTED
; i
++) {
895 if (config_match(&ss
->cipherSuites
[i
], policy
, enabled
, &ss
->vrange
))
899 PORT_SetError(SSL_ERROR_SSL_DISABLED
);
905 * Null compression, mac and encryption functions
909 Null_Cipher(void *ctx
, unsigned char *output
, int *outputLen
, int maxOutputLen
,
910 const unsigned char *input
, int inputLen
)
912 if (inputLen
> maxOutputLen
) {
913 *outputLen
= 0; /* Match PK11_CipherOp in setting outputLen */
914 PORT_SetError(SEC_ERROR_OUTPUT_LEN
);
917 *outputLen
= inputLen
;
919 PORT_Memcpy(output
, input
, inputLen
);
924 * SSL3 Utility functions
927 /* allowLargerPeerVersion controls whether the function will select the
928 * highest enabled SSL version or fail when peerVersion is greater than the
929 * highest enabled version.
931 * If allowLargerPeerVersion is true, peerVersion is the peer's highest
932 * enabled version rather than the peer's selected version.
935 ssl3_NegotiateVersion(sslSocket
*ss
, SSL3ProtocolVersion peerVersion
,
936 PRBool allowLargerPeerVersion
)
938 if (SSL3_ALL_VERSIONS_DISABLED(&ss
->vrange
)) {
939 PORT_SetError(SSL_ERROR_SSL_DISABLED
);
943 if (peerVersion
< ss
->vrange
.min
||
944 (peerVersion
> ss
->vrange
.max
&& !allowLargerPeerVersion
)) {
945 PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION
);
949 ss
->version
= PR_MIN(peerVersion
, ss
->vrange
.max
);
950 PORT_Assert(ssl3_VersionIsSupported(ss
->protocolVariant
, ss
->version
));
956 ssl3_GetNewRandom(SSL3Random
*random
)
960 /* first 4 bytes are reserverd for time */
961 rv
= PK11_GenerateRandom(random
->rand
, SSL3_RANDOM_LENGTH
);
962 if (rv
!= SECSuccess
) {
963 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE
);
968 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
970 ssl3_SignHashes(SSL3Hashes
*hash
, SECKEYPrivateKey
*key
, SECItem
*buf
,
973 SECStatus rv
= SECFailure
;
974 PRBool doDerEncode
= PR_FALSE
;
980 switch (key
->keyType
) {
982 hashItem
.data
= hash
->u
.raw
;
983 hashItem
.len
= hash
->len
;
987 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
988 * In that case, we use just the SHA1 part. */
989 if (hash
->hashAlg
== SEC_OID_UNKNOWN
) {
990 hashItem
.data
= hash
->u
.s
.sha
;
991 hashItem
.len
= sizeof(hash
->u
.s
.sha
);
993 hashItem
.data
= hash
->u
.raw
;
994 hashItem
.len
= hash
->len
;
997 #ifndef NSS_DISABLE_ECC
999 doDerEncode
= PR_TRUE
;
1000 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
1001 * In that case, we use just the SHA1 part. */
1002 if (hash
->hashAlg
== SEC_OID_UNKNOWN
) {
1003 hashItem
.data
= hash
->u
.s
.sha
;
1004 hashItem
.len
= sizeof(hash
->u
.s
.sha
);
1006 hashItem
.data
= hash
->u
.raw
;
1007 hashItem
.len
= hash
->len
;
1010 #endif /* NSS_DISABLE_ECC */
1012 PORT_SetError(SEC_ERROR_INVALID_KEY
);
1015 PRINT_BUF(60, (NULL
, "hash(es) to be signed", hashItem
.data
, hashItem
.len
));
1017 if (hash
->hashAlg
== SEC_OID_UNKNOWN
) {
1018 signatureLen
= PK11_SignatureLen(key
);
1019 if (signatureLen
<= 0) {
1020 PORT_SetError(SEC_ERROR_INVALID_KEY
);
1024 buf
->len
= (unsigned)signatureLen
;
1025 buf
->data
= (unsigned char *)PORT_Alloc(signatureLen
);
1027 goto done
; /* error code was set. */
1029 rv
= PK11_Sign(key
, buf
, &hashItem
);
1031 rv
= SGN_Digest(key
, hash
->hashAlg
, buf
, &hashItem
);
1033 if (rv
!= SECSuccess
) {
1034 ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE
);
1035 } else if (doDerEncode
) {
1036 SECItem derSig
= {siBuffer
, NULL
, 0};
1038 /* This also works for an ECDSA signature */
1039 rv
= DSAU_EncodeDerSigWithLen(&derSig
, buf
, buf
->len
);
1040 if (rv
== SECSuccess
) {
1041 PORT_Free(buf
->data
); /* discard unencoded signature. */
1042 *buf
= derSig
; /* give caller encoded signature. */
1043 } else if (derSig
.data
) {
1044 PORT_Free(derSig
.data
);
1048 PRINT_BUF(60, (NULL
, "signed hashes", (unsigned char*)buf
->data
, buf
->len
));
1050 if (rv
!= SECSuccess
&& buf
->data
) {
1051 PORT_Free(buf
->data
);
1057 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
1059 ssl3_VerifySignedHashes(SSL3Hashes
*hash
, CERTCertificate
*cert
,
1060 SECItem
*buf
, PRBool isTLS
, void *pwArg
)
1062 SECKEYPublicKey
* key
;
1063 SECItem
* signature
= NULL
;
1070 PRINT_BUF(60, (NULL
, "check signed hashes",
1071 buf
->data
, buf
->len
));
1073 key
= CERT_ExtractPublicKey(cert
);
1075 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE
);
1079 hashAlg
= hash
->hashAlg
;
1080 switch (key
->keyType
) {
1082 encAlg
= SEC_OID_PKCS1_RSA_ENCRYPTION
;
1083 hashItem
.data
= hash
->u
.raw
;
1084 hashItem
.len
= hash
->len
;
1087 encAlg
= SEC_OID_ANSIX9_DSA_SIGNATURE
;
1088 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
1089 * In that case, we use just the SHA1 part. */
1090 if (hash
->hashAlg
== SEC_OID_UNKNOWN
) {
1091 hashItem
.data
= hash
->u
.s
.sha
;
1092 hashItem
.len
= sizeof(hash
->u
.s
.sha
);
1094 hashItem
.data
= hash
->u
.raw
;
1095 hashItem
.len
= hash
->len
;
1097 /* Allow DER encoded DSA signatures in SSL 3.0 */
1098 if (isTLS
|| buf
->len
!= SECKEY_SignatureLen(key
)) {
1099 signature
= DSAU_DecodeDerSigToLen(buf
, SECKEY_SignatureLen(key
));
1101 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
);
1108 #ifndef NSS_DISABLE_ECC
1110 encAlg
= SEC_OID_ANSIX962_EC_PUBLIC_KEY
;
1111 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
1112 * In that case, we use just the SHA1 part.
1113 * ECDSA signatures always encode the integers r and s using ASN.1
1114 * (unlike DSA where ASN.1 encoding is used with TLS but not with
1115 * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
1117 if (hash
->hashAlg
== SEC_OID_UNKNOWN
) {
1118 hashAlg
= SEC_OID_SHA1
;
1119 hashItem
.data
= hash
->u
.s
.sha
;
1120 hashItem
.len
= sizeof(hash
->u
.s
.sha
);
1122 hashItem
.data
= hash
->u
.raw
;
1123 hashItem
.len
= hash
->len
;
1126 #endif /* NSS_DISABLE_ECC */
1129 SECKEY_DestroyPublicKey(key
);
1130 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG
);
1134 PRINT_BUF(60, (NULL
, "hash(es) to be verified",
1135 hashItem
.data
, hashItem
.len
));
1137 if (hashAlg
== SEC_OID_UNKNOWN
|| key
->keyType
== dsaKey
) {
1138 /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1139 * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1140 * above always removes the DER encoding of DSA signatures when
1141 * present. Thus DSA signatures are always verified with PK11_Verify.
1143 rv
= PK11_Verify(key
, buf
, &hashItem
, pwArg
);
1145 rv
= VFY_VerifyDigestDirect(&hashItem
, key
, buf
, encAlg
, hashAlg
,
1148 SECKEY_DestroyPublicKey(key
);
1150 SECITEM_FreeItem(signature
, PR_TRUE
);
1152 if (rv
!= SECSuccess
) {
1153 ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
);
1159 /* Caller must set hiLevel error code. */
1160 /* Called from ssl3_ComputeExportRSAKeyHash
1161 * ssl3_ComputeDHKeyHash
1162 * which are called from ssl3_HandleServerKeyExchange.
1164 * hashAlg: either the OID for a hash algorithm or SEC_OID_UNKNOWN to specify
1165 * the pre-1.2, MD5/SHA1 combination hash.
1168 ssl3_ComputeCommonKeyHash(SECOidTag hashAlg
,
1169 PRUint8
* hashBuf
, unsigned int bufLen
,
1170 SSL3Hashes
*hashes
, PRBool bypassPKCS11
)
1172 SECStatus rv
= SECSuccess
;
1174 #ifndef NO_PKCS11_BYPASS
1176 if (hashAlg
== SEC_OID_UNKNOWN
) {
1177 MD5_HashBuf (hashes
->u
.s
.md5
, hashBuf
, bufLen
);
1178 SHA1_HashBuf(hashes
->u
.s
.sha
, hashBuf
, bufLen
);
1179 hashes
->len
= MD5_LENGTH
+ SHA1_LENGTH
;
1180 } else if (hashAlg
== SEC_OID_SHA1
) {
1181 SHA1_HashBuf(hashes
->u
.raw
, hashBuf
, bufLen
);
1182 hashes
->len
= SHA1_LENGTH
;
1183 } else if (hashAlg
== SEC_OID_SHA256
) {
1184 SHA256_HashBuf(hashes
->u
.raw
, hashBuf
, bufLen
);
1185 hashes
->len
= SHA256_LENGTH
;
1186 } else if (hashAlg
== SEC_OID_SHA384
) {
1187 SHA384_HashBuf(hashes
->u
.raw
, hashBuf
, bufLen
);
1188 hashes
->len
= SHA384_LENGTH
;
1189 } else if (hashAlg
== SEC_OID_SHA512
) {
1190 SHA512_HashBuf(hashes
->u
.raw
, hashBuf
, bufLen
);
1191 hashes
->len
= SHA512_LENGTH
;
1193 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM
);
1199 if (hashAlg
== SEC_OID_UNKNOWN
) {
1200 rv
= PK11_HashBuf(SEC_OID_MD5
, hashes
->u
.s
.md5
, hashBuf
, bufLen
);
1201 if (rv
!= SECSuccess
) {
1202 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
1207 rv
= PK11_HashBuf(SEC_OID_SHA1
, hashes
->u
.s
.sha
, hashBuf
, bufLen
);
1208 if (rv
!= SECSuccess
) {
1209 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
1212 hashes
->len
= MD5_LENGTH
+ SHA1_LENGTH
;
1214 hashes
->len
= HASH_ResultLenByOidTag(hashAlg
);
1215 if (hashes
->len
> sizeof(hashes
->u
.raw
)) {
1216 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM
);
1220 rv
= PK11_HashBuf(hashAlg
, hashes
->u
.raw
, hashBuf
, bufLen
);
1221 if (rv
!= SECSuccess
) {
1222 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE
);
1227 hashes
->hashAlg
= hashAlg
;
1233 /* Caller must set hiLevel error code.
1234 ** Called from ssl3_SendServerKeyExchange and
1235 ** ssl3_HandleServerKeyExchange.
1238 ssl3_ComputeExportRSAKeyHash(SECOidTag hashAlg
,
1239 SECItem modulus
, SECItem publicExponent
,
1240 SSL3Random
*client_rand
, SSL3Random
*server_rand
,
1241 SSL3Hashes
*hashes
, PRBool bypassPKCS11
)
1245 SECStatus rv
= SECSuccess
;
1246 unsigned int bufLen
;
1247 PRUint8 buf
[2*SSL3_RANDOM_LENGTH
+ 2 + 4096/8 + 2 + 4096/8];
1249 bufLen
= 2*SSL3_RANDOM_LENGTH
+ 2 + modulus
.len
+ 2 + publicExponent
.len
;
1250 if (bufLen
<= sizeof buf
) {
1253 hashBuf
= PORT_Alloc(bufLen
);
1259 memcpy(hashBuf
, client_rand
, SSL3_RANDOM_LENGTH
);
1260 pBuf
= hashBuf
+ SSL3_RANDOM_LENGTH
;
1261 memcpy(pBuf
, server_rand
, SSL3_RANDOM_LENGTH
);
1262 pBuf
+= SSL3_RANDOM_LENGTH
;
1263 pBuf
[0] = (PRUint8
)(modulus
.len
>> 8);
1264 pBuf
[1] = (PRUint8
)(modulus
.len
);
1266 memcpy(pBuf
, modulus
.data
, modulus
.len
);
1267 pBuf
+= modulus
.len
;
1268 pBuf
[0] = (PRUint8
)(publicExponent
.len
>> 8);
1269 pBuf
[1] = (PRUint8
)(publicExponent
.len
);
1271 memcpy(pBuf
, publicExponent
.data
, publicExponent
.len
);
1272 pBuf
+= publicExponent
.len
;
1273 PORT_Assert((unsigned int)(pBuf
- hashBuf
) == bufLen
);
1275 rv
= ssl3_ComputeCommonKeyHash(hashAlg
, hashBuf
, bufLen
, hashes
,
1278 PRINT_BUF(95, (NULL
, "RSAkey hash: ", hashBuf
, bufLen
));
1279 if (hashAlg
== SEC_OID_UNKNOWN
) {
1280 PRINT_BUF(95, (NULL
, "RSAkey hash: MD5 result",
1281 hashes
->u
.s
.md5
, MD5_LENGTH
));
1282 PRINT_BUF(95, (NULL
, "RSAkey hash: SHA1 result",
1283 hashes
->u
.s
.sha
, SHA1_LENGTH
));
1285 PRINT_BUF(95, (NULL
, "RSAkey hash: result",
1286 hashes
->u
.raw
, hashes
->len
));
1289 if (hashBuf
!= buf
&& hashBuf
!= NULL
)
1294 /* Caller must set hiLevel error code. */
1295 /* Called from ssl3_HandleServerKeyExchange. */
1297 ssl3_ComputeDHKeyHash(SECOidTag hashAlg
,
1298 SECItem dh_p
, SECItem dh_g
, SECItem dh_Ys
,
1299 SSL3Random
*client_rand
, SSL3Random
*server_rand
,
1300 SSL3Hashes
*hashes
, PRBool bypassPKCS11
)
1304 SECStatus rv
= SECSuccess
;
1305 unsigned int bufLen
;
1306 PRUint8 buf
[2*SSL3_RANDOM_LENGTH
+ 2 + 4096/8 + 2 + 4096/8];
1308 bufLen
= 2*SSL3_RANDOM_LENGTH
+ 2 + dh_p
.len
+ 2 + dh_g
.len
+ 2 + dh_Ys
.len
;
1309 if (bufLen
<= sizeof buf
) {
1312 hashBuf
= PORT_Alloc(bufLen
);
1318 memcpy(hashBuf
, client_rand
, SSL3_RANDOM_LENGTH
);
1319 pBuf
= hashBuf
+ SSL3_RANDOM_LENGTH
;
1320 memcpy(pBuf
, server_rand
, SSL3_RANDOM_LENGTH
);
1321 pBuf
+= SSL3_RANDOM_LENGTH
;
1322 pBuf
[0] = (PRUint8
)(dh_p
.len
>> 8);
1323 pBuf
[1] = (PRUint8
)(dh_p
.len
);
1325 memcpy(pBuf
, dh_p
.data
, dh_p
.len
);
1327 pBuf
[0] = (PRUint8
)(dh_g
.len
>> 8);
1328 pBuf
[1] = (PRUint8
)(dh_g
.len
);
1330 memcpy(pBuf
, dh_g
.data
, dh_g
.len
);
1332 pBuf
[0] = (PRUint8
)(dh_Ys
.len
>> 8);
1333 pBuf
[1] = (PRUint8
)(dh_Ys
.len
);
1335 memcpy(pBuf
, dh_Ys
.data
, dh_Ys
.len
);
1337 PORT_Assert((unsigned int)(pBuf
- hashBuf
) == bufLen
);
1339 rv
= ssl3_ComputeCommonKeyHash(hashAlg
, hashBuf
, bufLen
, hashes
,
1342 PRINT_BUF(95, (NULL
, "DHkey hash: ", hashBuf
, bufLen
));
1343 if (hashAlg
== SEC_OID_UNKNOWN
) {
1344 PRINT_BUF(95, (NULL
, "DHkey hash: MD5 result",
1345 hashes
->u
.s
.md5
, MD5_LENGTH
));
1346 PRINT_BUF(95, (NULL
, "DHkey hash: SHA1 result",
1347 hashes
->u
.s
.sha
, SHA1_LENGTH
));
1349 PRINT_BUF(95, (NULL
, "DHkey hash: result",
1350 hashes
->u
.raw
, hashes
->len
));
1353 if (hashBuf
!= buf
&& hashBuf
!= NULL
)
1359 ssl3_BumpSequenceNumber(SSL3SequenceNumber
*num
)
1366 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */
1368 ssl3_CleanupKeyMaterial(ssl3KeyMaterial
*mat
)
1370 if (mat
->write_key
!= NULL
) {
1371 PK11_FreeSymKey(mat
->write_key
);
1372 mat
->write_key
= NULL
;
1374 if (mat
->write_mac_key
!= NULL
) {
1375 PK11_FreeSymKey(mat
->write_mac_key
);
1376 mat
->write_mac_key
= NULL
;
1378 if (mat
->write_mac_context
!= NULL
) {
1379 PK11_DestroyContext(mat
->write_mac_context
, PR_TRUE
);
1380 mat
->write_mac_context
= NULL
;
1384 /* Called from ssl3_SendChangeCipherSpecs() and
1385 ** ssl3_HandleChangeCipherSpecs()
1386 ** ssl3_DestroySSL3Info
1387 ** Caller must hold SpecWriteLock.
1390 ssl3_DestroyCipherSpec(ssl3CipherSpec
*spec
, PRBool freeSrvName
)
1392 PRBool freeit
= (PRBool
)(!spec
->bypassCiphers
);
1393 /* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */
1394 if (spec
->destroy
) {
1395 spec
->destroy(spec
->encodeContext
, freeit
);
1396 spec
->destroy(spec
->decodeContext
, freeit
);
1397 spec
->encodeContext
= NULL
; /* paranoia */
1398 spec
->decodeContext
= NULL
;
1400 if (spec
->destroyCompressContext
&& spec
->compressContext
) {
1401 spec
->destroyCompressContext(spec
->compressContext
, 1);
1402 spec
->compressContext
= NULL
;
1404 if (spec
->destroyDecompressContext
&& spec
->decompressContext
) {
1405 spec
->destroyDecompressContext(spec
->decompressContext
, 1);
1406 spec
->decompressContext
= NULL
;
1408 if (freeSrvName
&& spec
->srvVirtName
.data
) {
1409 SECITEM_FreeItem(&spec
->srvVirtName
, PR_FALSE
);
1411 if (spec
->master_secret
!= NULL
) {
1412 PK11_FreeSymKey(spec
->master_secret
);
1413 spec
->master_secret
= NULL
;
1415 spec
->msItem
.data
= NULL
;
1416 spec
->msItem
.len
= 0;
1417 ssl3_CleanupKeyMaterial(&spec
->client
);
1418 ssl3_CleanupKeyMaterial(&spec
->server
);
1419 spec
->bypassCiphers
= PR_FALSE
;
1421 spec
->destroyCompressContext
= NULL
;
1422 spec
->destroyDecompressContext
= NULL
;
1425 /* Fill in the pending cipher spec with info from the selected ciphersuite.
1426 ** This is as much initialization as we can do without having key material.
1427 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1428 ** Caller must hold the ssl3 handshake lock.
1429 ** Acquires & releases SpecWriteLock.
1432 ssl3_SetupPendingCipherSpec(sslSocket
*ss
)
1434 ssl3CipherSpec
* pwSpec
;
1435 ssl3CipherSpec
* cwSpec
;
1436 ssl3CipherSuite suite
= ss
->ssl3
.hs
.cipher_suite
;
1437 SSL3MACAlgorithm mac
;
1438 SSL3BulkCipher cipher
;
1439 SSL3KeyExchangeAlgorithm kea
;
1440 const ssl3CipherSuiteDef
*suite_def
;
1443 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
1445 ssl_GetSpecWriteLock(ss
); /*******************************/
1447 pwSpec
= ss
->ssl3
.pwSpec
;
1448 PORT_Assert(pwSpec
== ss
->ssl3
.prSpec
);
1450 /* This hack provides maximal interoperability with SSL 3 servers. */
1451 cwSpec
= ss
->ssl3
.cwSpec
;
1452 if (cwSpec
->mac_def
->mac
== mac_null
) {
1453 /* SSL records are not being MACed. */
1454 cwSpec
->version
= ss
->version
;
1457 pwSpec
->version
= ss
->version
;
1458 isTLS
= (PRBool
)(pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
1460 SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1461 SSL_GETPID(), ss
->fd
, suite
));
1463 suite_def
= ssl_LookupCipherSuiteDef(suite
);
1464 if (suite_def
== NULL
) {
1465 ssl_ReleaseSpecWriteLock(ss
);
1466 return SECFailure
; /* error code set by ssl_LookupCipherSuiteDef */
1470 /* Double-check that we did not pick an RC4 suite */
1471 PORT_Assert((suite_def
->bulk_cipher_alg
!= cipher_rc4
) &&
1472 (suite_def
->bulk_cipher_alg
!= cipher_rc4_40
) &&
1473 (suite_def
->bulk_cipher_alg
!= cipher_rc4_56
));
1476 cipher
= suite_def
->bulk_cipher_alg
;
1477 kea
= suite_def
->key_exchange_alg
;
1478 mac
= suite_def
->mac_alg
;
1479 if (mac
<= ssl_mac_sha
&& mac
!= ssl_mac_null
&& isTLS
)
1482 ss
->ssl3
.hs
.suite_def
= suite_def
;
1483 ss
->ssl3
.hs
.kea_def
= &kea_defs
[kea
];
1484 PORT_Assert(ss
->ssl3
.hs
.kea_def
->kea
== kea
);
1486 pwSpec
->cipher_def
= &bulk_cipher_defs
[cipher
];
1487 PORT_Assert(pwSpec
->cipher_def
->cipher
== cipher
);
1489 pwSpec
->mac_def
= &mac_defs
[mac
];
1490 PORT_Assert(pwSpec
->mac_def
->mac
== mac
);
1492 ss
->sec
.keyBits
= pwSpec
->cipher_def
->key_size
* BPB
;
1493 ss
->sec
.secretKeyBits
= pwSpec
->cipher_def
->secret_key_size
* BPB
;
1494 ss
->sec
.cipherType
= cipher
;
1496 pwSpec
->encodeContext
= NULL
;
1497 pwSpec
->decodeContext
= NULL
;
1499 pwSpec
->mac_size
= pwSpec
->mac_def
->mac_size
;
1501 pwSpec
->compression_method
= ss
->ssl3
.hs
.compression
;
1502 pwSpec
->compressContext
= NULL
;
1503 pwSpec
->decompressContext
= NULL
;
1505 ssl_ReleaseSpecWriteLock(ss
); /*******************************/
1509 #ifdef NSS_ENABLE_ZLIB
1510 #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream)
1513 ssl3_MapZlibError(int zlib_error
)
1515 switch (zlib_error
) {
1524 ssl3_DeflateInit(void *void_context
)
1526 z_stream
*context
= void_context
;
1527 context
->zalloc
= NULL
;
1528 context
->zfree
= NULL
;
1529 context
->opaque
= NULL
;
1531 return ssl3_MapZlibError(deflateInit(context
, Z_DEFAULT_COMPRESSION
));
1535 ssl3_InflateInit(void *void_context
)
1537 z_stream
*context
= void_context
;
1538 context
->zalloc
= NULL
;
1539 context
->zfree
= NULL
;
1540 context
->opaque
= NULL
;
1541 context
->next_in
= NULL
;
1542 context
->avail_in
= 0;
1544 return ssl3_MapZlibError(inflateInit(context
));
1548 ssl3_DeflateCompress(void *void_context
, unsigned char *out
, int *out_len
,
1549 int maxout
, const unsigned char *in
, int inlen
)
1551 z_stream
*context
= void_context
;
1558 context
->next_in
= (unsigned char*) in
;
1559 context
->avail_in
= inlen
;
1560 context
->next_out
= out
;
1561 context
->avail_out
= maxout
;
1562 if (deflate(context
, Z_SYNC_FLUSH
) != Z_OK
) {
1565 if (context
->avail_out
== 0) {
1566 /* We ran out of space! */
1567 SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing",
1572 *out_len
= maxout
- context
->avail_out
;
1577 ssl3_DeflateDecompress(void *void_context
, unsigned char *out
, int *out_len
,
1578 int maxout
, const unsigned char *in
, int inlen
)
1580 z_stream
*context
= void_context
;
1587 context
->next_in
= (unsigned char*) in
;
1588 context
->avail_in
= inlen
;
1589 context
->next_out
= out
;
1590 context
->avail_out
= maxout
;
1591 if (inflate(context
, Z_SYNC_FLUSH
) != Z_OK
) {
1592 PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE
);
1596 *out_len
= maxout
- context
->avail_out
;
1601 ssl3_DestroyCompressContext(void *void_context
, PRBool unused
)
1603 deflateEnd(void_context
);
1604 PORT_Free(void_context
);
1609 ssl3_DestroyDecompressContext(void *void_context
, PRBool unused
)
1611 inflateEnd(void_context
);
1612 PORT_Free(void_context
);
1616 #endif /* NSS_ENABLE_ZLIB */
1618 /* Initialize the compression functions and contexts for the given
1621 ssl3_InitCompressionContext(ssl3CipherSpec
*pwSpec
)
1623 /* Setup the compression functions */
1624 switch (pwSpec
->compression_method
) {
1625 case ssl_compression_null
:
1626 pwSpec
->compressor
= NULL
;
1627 pwSpec
->decompressor
= NULL
;
1628 pwSpec
->compressContext
= NULL
;
1629 pwSpec
->decompressContext
= NULL
;
1630 pwSpec
->destroyCompressContext
= NULL
;
1631 pwSpec
->destroyDecompressContext
= NULL
;
1633 #ifdef NSS_ENABLE_ZLIB
1634 case ssl_compression_deflate
:
1635 pwSpec
->compressor
= ssl3_DeflateCompress
;
1636 pwSpec
->decompressor
= ssl3_DeflateDecompress
;
1637 pwSpec
->compressContext
= PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE
);
1638 pwSpec
->decompressContext
= PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE
);
1639 pwSpec
->destroyCompressContext
= ssl3_DestroyCompressContext
;
1640 pwSpec
->destroyDecompressContext
= ssl3_DestroyDecompressContext
;
1641 ssl3_DeflateInit(pwSpec
->compressContext
);
1642 ssl3_InflateInit(pwSpec
->decompressContext
);
1644 #endif /* NSS_ENABLE_ZLIB */
1647 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
1654 #ifndef NO_PKCS11_BYPASS
1655 /* Initialize encryption contexts for pending spec.
1656 * MAC contexts are set up when computing the mac, not here.
1657 * Master Secret already is derived in spec->msItem
1658 * Caller holds Spec write lock.
1661 ssl3_InitPendingContextsBypass(sslSocket
*ss
)
1663 ssl3CipherSpec
* pwSpec
;
1664 const ssl3BulkCipherDef
*cipher_def
;
1665 void * serverContext
= NULL
;
1666 void * clientContext
= NULL
;
1667 BLapiInitContextFunc initFn
= (BLapiInitContextFunc
)NULL
;
1669 unsigned int optArg1
= 0;
1670 unsigned int optArg2
= 0;
1671 PRBool server_encrypts
= ss
->sec
.isServer
;
1672 SSLCipherAlgorithm calg
;
1675 PORT_Assert(ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
1676 PORT_Assert(ss
->opt
.noLocks
|| ssl_HaveSpecWriteLock(ss
));
1677 PORT_Assert(ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
);
1679 pwSpec
= ss
->ssl3
.pwSpec
;
1680 cipher_def
= pwSpec
->cipher_def
;
1682 calg
= cipher_def
->calg
;
1684 if (calg
== ssl_calg_aes_gcm
) {
1685 pwSpec
->encode
= NULL
;
1686 pwSpec
->decode
= NULL
;
1687 pwSpec
->destroy
= NULL
;
1688 pwSpec
->encodeContext
= NULL
;
1689 pwSpec
->decodeContext
= NULL
;
1690 pwSpec
->aead
= ssl3_AESGCMBypass
;
1691 ssl3_InitCompressionContext(pwSpec
);
1695 serverContext
= pwSpec
->server
.cipher_context
;
1696 clientContext
= pwSpec
->client
.cipher_context
;
1700 pwSpec
->encode
= Null_Cipher
;
1701 pwSpec
->decode
= Null_Cipher
;
1702 pwSpec
->destroy
= NULL
;
1706 initFn
= (BLapiInitContextFunc
)RC4_InitContext
;
1707 pwSpec
->encode
= (SSLCipher
) RC4_Encrypt
;
1708 pwSpec
->decode
= (SSLCipher
) RC4_Decrypt
;
1709 pwSpec
->destroy
= (SSLDestroy
) RC4_DestroyContext
;
1712 initFn
= (BLapiInitContextFunc
)RC2_InitContext
;
1714 optArg1
= cipher_def
->key_size
;
1715 pwSpec
->encode
= (SSLCipher
) RC2_Encrypt
;
1716 pwSpec
->decode
= (SSLCipher
) RC2_Decrypt
;
1717 pwSpec
->destroy
= (SSLDestroy
) RC2_DestroyContext
;
1720 initFn
= (BLapiInitContextFunc
)DES_InitContext
;
1722 optArg1
= server_encrypts
;
1723 pwSpec
->encode
= (SSLCipher
) DES_Encrypt
;
1724 pwSpec
->decode
= (SSLCipher
) DES_Decrypt
;
1725 pwSpec
->destroy
= (SSLDestroy
) DES_DestroyContext
;
1728 initFn
= (BLapiInitContextFunc
)DES_InitContext
;
1729 mode
= NSS_DES_EDE3_CBC
;
1730 optArg1
= server_encrypts
;
1731 pwSpec
->encode
= (SSLCipher
) DES_Encrypt
;
1732 pwSpec
->decode
= (SSLCipher
) DES_Decrypt
;
1733 pwSpec
->destroy
= (SSLDestroy
) DES_DestroyContext
;
1736 initFn
= (BLapiInitContextFunc
)AES_InitContext
;
1738 optArg1
= server_encrypts
;
1739 optArg2
= AES_BLOCK_SIZE
;
1740 pwSpec
->encode
= (SSLCipher
) AES_Encrypt
;
1741 pwSpec
->decode
= (SSLCipher
) AES_Decrypt
;
1742 pwSpec
->destroy
= (SSLDestroy
) AES_DestroyContext
;
1745 case ssl_calg_camellia
:
1746 initFn
= (BLapiInitContextFunc
)Camellia_InitContext
;
1747 mode
= NSS_CAMELLIA_CBC
;
1748 optArg1
= server_encrypts
;
1749 optArg2
= CAMELLIA_BLOCK_SIZE
;
1750 pwSpec
->encode
= (SSLCipher
) Camellia_Encrypt
;
1751 pwSpec
->decode
= (SSLCipher
) Camellia_Decrypt
;
1752 pwSpec
->destroy
= (SSLDestroy
) Camellia_DestroyContext
;
1756 initFn
= (BLapiInitContextFunc
)SEED_InitContext
;
1757 mode
= NSS_SEED_CBC
;
1758 optArg1
= server_encrypts
;
1759 optArg2
= SEED_BLOCK_SIZE
;
1760 pwSpec
->encode
= (SSLCipher
) SEED_Encrypt
;
1761 pwSpec
->decode
= (SSLCipher
) SEED_Decrypt
;
1762 pwSpec
->destroy
= (SSLDestroy
) SEED_DestroyContext
;
1766 case ssl_calg_fortezza
:
1769 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
1772 rv
= (*initFn
)(serverContext
,
1773 pwSpec
->server
.write_key_item
.data
,
1774 pwSpec
->server
.write_key_item
.len
,
1775 pwSpec
->server
.write_iv_item
.data
,
1776 mode
, optArg1
, optArg2
);
1777 if (rv
!= SECSuccess
) {
1779 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
1787 case ssl_calg_camellia
:
1789 /* For block ciphers, if the server is encrypting, then the client
1790 * is decrypting, and vice versa.
1794 /* kill warnings. */
1799 case ssl_calg_fortezza
:
1800 case ssl_calg_aes_gcm
:
1804 rv
= (*initFn
)(clientContext
,
1805 pwSpec
->client
.write_key_item
.data
,
1806 pwSpec
->client
.write_key_item
.len
,
1807 pwSpec
->client
.write_iv_item
.data
,
1808 mode
, optArg1
, optArg2
);
1809 if (rv
!= SECSuccess
) {
1811 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
1815 pwSpec
->encodeContext
= (ss
->sec
.isServer
) ? serverContext
: clientContext
;
1816 pwSpec
->decodeContext
= (ss
->sec
.isServer
) ? clientContext
: serverContext
;
1818 ssl3_InitCompressionContext(pwSpec
);
1828 /* This function should probably be moved to pk11wrap and be named
1829 * PK11_ParamFromIVAndEffectiveKeyBits
1832 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype
, SECItem
*iv
, CK_ULONG ulEffectiveBits
)
1834 SECItem
* param
= PK11_ParamFromIV(mtype
, iv
);
1835 if (param
&& param
->data
&& param
->len
>= sizeof(CK_RC2_PARAMS
)) {
1837 case CKM_RC2_KEY_GEN
:
1841 case CKM_RC2_MAC_GENERAL
:
1842 case CKM_RC2_CBC_PAD
:
1843 *(CK_RC2_PARAMS
*)param
->data
= ulEffectiveBits
;
1850 /* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data
1851 * which is included in the MAC or AEAD additional data) to |out| and returns
1852 * its length. See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the
1853 * definition of the AEAD additional data.
1855 * TLS pseudo-header includes the record's version field, SSL's doesn't. Which
1856 * pseudo-header defintiion to use should be decided based on the version of
1857 * the protocol that was negotiated when the cipher spec became current, NOT
1858 * based on the version value in the record itself, and the decision is passed
1859 * to this function as the |includesVersion| argument. But, the |version|
1860 * argument should be the record's version value.
1863 ssl3_BuildRecordPseudoHeader(unsigned char *out
,
1864 SSL3SequenceNumber seq_num
,
1865 SSL3ContentType type
,
1866 PRBool includesVersion
,
1867 SSL3ProtocolVersion version
,
1871 out
[0] = (unsigned char)(seq_num
.high
>> 24);
1872 out
[1] = (unsigned char)(seq_num
.high
>> 16);
1873 out
[2] = (unsigned char)(seq_num
.high
>> 8);
1874 out
[3] = (unsigned char)(seq_num
.high
>> 0);
1875 out
[4] = (unsigned char)(seq_num
.low
>> 24);
1876 out
[5] = (unsigned char)(seq_num
.low
>> 16);
1877 out
[6] = (unsigned char)(seq_num
.low
>> 8);
1878 out
[7] = (unsigned char)(seq_num
.low
>> 0);
1881 /* SSL3 MAC doesn't include the record's version field. */
1882 if (!includesVersion
) {
1883 out
[9] = MSB(length
);
1884 out
[10] = LSB(length
);
1888 /* TLS MAC and AEAD additional data include version. */
1890 SSL3ProtocolVersion dtls_version
;
1892 dtls_version
= dtls_TLSVersionToDTLSVersion(version
);
1893 out
[9] = MSB(dtls_version
);
1894 out
[10] = LSB(dtls_version
);
1896 out
[9] = MSB(version
);
1897 out
[10] = LSB(version
);
1899 out
[11] = MSB(length
);
1900 out
[12] = LSB(length
);
1904 typedef SECStatus (*PK11CryptFcn
)(
1905 PK11SymKey
*symKey
, CK_MECHANISM_TYPE mechanism
, SECItem
*param
,
1906 unsigned char *out
, unsigned int *outLen
, unsigned int maxLen
,
1907 const unsigned char *in
, unsigned int inLen
);
1909 static PK11CryptFcn pk11_encrypt
= NULL
;
1910 static PK11CryptFcn pk11_decrypt
= NULL
;
1912 static PRCallOnceType resolvePK11CryptOnce
;
1915 ssl3_ResolvePK11CryptFunctions(void)
1918 /* On Linux we use the system NSS libraries. Look up the PK11_Encrypt and
1919 * PK11_Decrypt functions at run time. */
1920 pk11_encrypt
= (PK11CryptFcn
)dlsym(RTLD_DEFAULT
, "PK11_Encrypt");
1921 pk11_decrypt
= (PK11CryptFcn
)dlsym(RTLD_DEFAULT
, "PK11_Decrypt");
1924 /* On other platforms we use our own copy of NSS. PK11_Encrypt and
1925 * PK11_Decrypt are known to be available. */
1926 pk11_encrypt
= PK11_Encrypt
;
1927 pk11_decrypt
= PK11_Decrypt
;
1933 * In NSS 3.15, PK11_Encrypt and PK11_Decrypt were added to provide access
1934 * to the AES GCM implementation in the NSS softoken. So the presence of
1935 * these two functions implies the NSS version supports AES GCM.
1938 ssl3_HasGCMSupport(void)
1940 (void)PR_CallOnce(&resolvePK11CryptOnce
, ssl3_ResolvePK11CryptFunctions
);
1941 return pk11_encrypt
!= NULL
;
1944 /* On this socket, disable the GCM cipher suites */
1946 ssl3_DisableGCMSuites(sslSocket
* ss
)
1950 for (i
= 0; i
< PR_ARRAY_SIZE(cipher_suite_defs
); i
++) {
1951 const ssl3CipherSuiteDef
*cipher_def
= &cipher_suite_defs
[i
];
1952 if (cipher_def
->bulk_cipher_alg
== cipher_aes_128_gcm
) {
1953 SECStatus rv
= ssl3_CipherPrefSet(ss
, cipher_def
->cipher_suite
,
1955 PORT_Assert(rv
== SECSuccess
); /* else is coding error */
1962 ssl3_AESGCM(ssl3KeyMaterial
*keys
,
1967 const unsigned char *in
,
1969 const unsigned char *additionalData
,
1970 int additionalDataLen
)
1973 SECStatus rv
= SECFailure
;
1974 unsigned char nonce
[12];
1975 unsigned int uOutLen
;
1976 CK_GCM_PARAMS gcmParams
;
1978 static const int tagSize
= 16;
1979 static const int explicitNonceLen
= 8;
1981 /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the
1982 * nonce is formed. */
1983 memcpy(nonce
, keys
->write_iv
, 4);
1985 memcpy(nonce
+ 4, in
, explicitNonceLen
);
1986 in
+= explicitNonceLen
;
1987 inlen
-= explicitNonceLen
;
1990 if (maxout
< explicitNonceLen
) {
1991 PORT_SetError(SEC_ERROR_INPUT_LEN
);
1994 /* Use the 64-bit sequence number as the explicit nonce. */
1995 memcpy(nonce
+ 4, additionalData
, explicitNonceLen
);
1996 memcpy(out
, additionalData
, explicitNonceLen
);
1997 out
+= explicitNonceLen
;
1998 maxout
-= explicitNonceLen
;
1999 *outlen
= explicitNonceLen
;
2002 param
.type
= siBuffer
;
2003 param
.data
= (unsigned char *) &gcmParams
;
2004 param
.len
= sizeof(gcmParams
);
2005 gcmParams
.pIv
= nonce
;
2006 gcmParams
.ulIvLen
= sizeof(nonce
);
2007 gcmParams
.pAAD
= (unsigned char *)additionalData
; /* const cast */
2008 gcmParams
.ulAADLen
= additionalDataLen
;
2009 gcmParams
.ulTagBits
= tagSize
* 8;
2012 rv
= pk11_decrypt(keys
->write_key
, CKM_AES_GCM
, ¶m
, out
, &uOutLen
,
2015 rv
= pk11_encrypt(keys
->write_key
, CKM_AES_GCM
, ¶m
, out
, &uOutLen
,
2018 *outlen
+= (int) uOutLen
;
2023 #ifndef NO_PKCS11_BYPASS
2025 ssl3_AESGCMBypass(ssl3KeyMaterial
*keys
,
2030 const unsigned char *in
,
2032 const unsigned char *additionalData
,
2033 int additionalDataLen
)
2035 SECStatus rv
= SECFailure
;
2036 unsigned char nonce
[12];
2037 unsigned int uOutLen
;
2039 CK_GCM_PARAMS gcmParams
;
2041 static const int tagSize
= 16;
2042 static const int explicitNonceLen
= 8;
2044 /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the
2045 * nonce is formed. */
2046 PORT_Assert(keys
->write_iv_item
.len
== 4);
2047 if (keys
->write_iv_item
.len
!= 4) {
2048 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
2051 memcpy(nonce
, keys
->write_iv_item
.data
, 4);
2053 memcpy(nonce
+ 4, in
, explicitNonceLen
);
2054 in
+= explicitNonceLen
;
2055 inlen
-= explicitNonceLen
;
2058 if (maxout
< explicitNonceLen
) {
2059 PORT_SetError(SEC_ERROR_INPUT_LEN
);
2062 /* Use the 64-bit sequence number as the explicit nonce. */
2063 memcpy(nonce
+ 4, additionalData
, explicitNonceLen
);
2064 memcpy(out
, additionalData
, explicitNonceLen
);
2065 out
+= explicitNonceLen
;
2066 maxout
-= explicitNonceLen
;
2067 *outlen
= explicitNonceLen
;
2070 gcmParams
.pIv
= nonce
;
2071 gcmParams
.ulIvLen
= sizeof(nonce
);
2072 gcmParams
.pAAD
= (unsigned char *)additionalData
; /* const cast */
2073 gcmParams
.ulAADLen
= additionalDataLen
;
2074 gcmParams
.ulTagBits
= tagSize
* 8;
2076 cx
= (AESContext
*)keys
->cipher_context
;
2077 rv
= AES_InitContext(cx
, keys
->write_key_item
.data
,
2078 keys
->write_key_item
.len
,
2079 (unsigned char *)&gcmParams
, NSS_AES_GCM
, !doDecrypt
,
2081 if (rv
!= SECSuccess
) {
2085 rv
= AES_Decrypt(cx
, out
, &uOutLen
, maxout
, in
, inlen
);
2087 rv
= AES_Encrypt(cx
, out
, &uOutLen
, maxout
, in
, inlen
);
2089 AES_DestroyContext(cx
, PR_FALSE
);
2090 *outlen
+= (int) uOutLen
;
2097 ssl3_ChaCha20Poly1305(
2098 ssl3KeyMaterial
*keys
,
2103 const unsigned char *in
,
2105 const unsigned char *additionalData
,
2106 int additionalDataLen
)
2109 SECStatus rv
= SECFailure
;
2110 unsigned int uOutLen
;
2111 CK_NSS_AEAD_PARAMS aeadParams
;
2112 static const int tagSize
= 16;
2114 param
.type
= siBuffer
;
2115 param
.len
= sizeof(aeadParams
);
2116 param
.data
= (unsigned char *) &aeadParams
;
2117 memset(&aeadParams
, 0, sizeof(aeadParams
));
2118 aeadParams
.pIv
= (unsigned char *) additionalData
;
2119 aeadParams
.ulIvLen
= 8;
2120 aeadParams
.pAAD
= (unsigned char *) additionalData
;
2121 aeadParams
.ulAADLen
= additionalDataLen
;
2122 aeadParams
.ulTagLen
= tagSize
;
2125 rv
= pk11_decrypt(keys
->write_key
, CKM_NSS_CHACHA20_POLY1305
, ¶m
,
2126 out
, &uOutLen
, maxout
, in
, inlen
);
2128 rv
= pk11_encrypt(keys
->write_key
, CKM_NSS_CHACHA20_POLY1305
, ¶m
,
2129 out
, &uOutLen
, maxout
, in
, inlen
);
2131 *outlen
= (int) uOutLen
;
2136 /* Initialize encryption and MAC contexts for pending spec.
2137 * Master Secret already is derived.
2138 * Caller holds Spec write lock.
2141 ssl3_InitPendingContextsPKCS11(sslSocket
*ss
)
2143 ssl3CipherSpec
* pwSpec
;
2144 const ssl3BulkCipherDef
*cipher_def
;
2145 PK11Context
* serverContext
= NULL
;
2146 PK11Context
* clientContext
= NULL
;
2148 CK_MECHANISM_TYPE mechanism
;
2149 CK_MECHANISM_TYPE mac_mech
;
2151 CK_ULONG effKeyBits
;
2154 SSLCipherAlgorithm calg
;
2156 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
2157 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSpecWriteLock(ss
));
2158 PORT_Assert(ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
);
2160 pwSpec
= ss
->ssl3
.pwSpec
;
2161 cipher_def
= pwSpec
->cipher_def
;
2162 macLength
= pwSpec
->mac_size
;
2163 calg
= cipher_def
->calg
;
2164 PORT_Assert(alg2Mech
[calg
].calg
== calg
);
2166 pwSpec
->client
.write_mac_context
= NULL
;
2167 pwSpec
->server
.write_mac_context
= NULL
;
2169 if (calg
== calg_aes_gcm
|| calg
== calg_chacha20
) {
2170 pwSpec
->encode
= NULL
;
2171 pwSpec
->decode
= NULL
;
2172 pwSpec
->destroy
= NULL
;
2173 pwSpec
->encodeContext
= NULL
;
2174 pwSpec
->decodeContext
= NULL
;
2175 if (calg
== calg_aes_gcm
) {
2176 pwSpec
->aead
= ssl3_AESGCM
;
2178 pwSpec
->aead
= ssl3_ChaCha20Poly1305
;
2184 ** Now setup the MAC contexts,
2185 ** crypto contexts are setup below.
2188 mac_mech
= pwSpec
->mac_def
->mmech
;
2189 mac_param
.data
= (unsigned char *)&macLength
;
2190 mac_param
.len
= sizeof(macLength
);
2193 pwSpec
->client
.write_mac_context
= PK11_CreateContextBySymKey(
2194 mac_mech
, CKA_SIGN
, pwSpec
->client
.write_mac_key
, &mac_param
);
2195 if (pwSpec
->client
.write_mac_context
== NULL
) {
2196 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE
);
2199 pwSpec
->server
.write_mac_context
= PK11_CreateContextBySymKey(
2200 mac_mech
, CKA_SIGN
, pwSpec
->server
.write_mac_key
, &mac_param
);
2201 if (pwSpec
->server
.write_mac_context
== NULL
) {
2202 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE
);
2207 ** Now setup the crypto contexts.
2210 if (calg
== calg_null
) {
2211 pwSpec
->encode
= Null_Cipher
;
2212 pwSpec
->decode
= Null_Cipher
;
2213 pwSpec
->destroy
= NULL
;
2216 mechanism
= alg2Mech
[calg
].cmech
;
2217 effKeyBits
= cipher_def
->key_size
* BPB
;
2220 * build the server context
2222 iv
.data
= pwSpec
->server
.write_iv
;
2223 iv
.len
= cipher_def
->iv_size
;
2224 param
= ssl3_ParamFromIV(mechanism
, &iv
, effKeyBits
);
2225 if (param
== NULL
) {
2226 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE
);
2229 serverContext
= PK11_CreateContextBySymKey(mechanism
,
2230 (ss
->sec
.isServer
? CKA_ENCRYPT
: CKA_DECRYPT
),
2231 pwSpec
->server
.write_key
, param
);
2232 iv
.data
= PK11_IVFromParam(mechanism
, param
, (int *)&iv
.len
);
2234 PORT_Memcpy(pwSpec
->server
.write_iv
, iv
.data
, iv
.len
);
2235 SECITEM_FreeItem(param
, PR_TRUE
);
2236 if (serverContext
== NULL
) {
2237 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE
);
2242 * build the client context
2244 iv
.data
= pwSpec
->client
.write_iv
;
2245 iv
.len
= cipher_def
->iv_size
;
2247 param
= ssl3_ParamFromIV(mechanism
, &iv
, effKeyBits
);
2248 if (param
== NULL
) {
2249 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE
);
2252 clientContext
= PK11_CreateContextBySymKey(mechanism
,
2253 (ss
->sec
.isServer
? CKA_DECRYPT
: CKA_ENCRYPT
),
2254 pwSpec
->client
.write_key
, param
);
2255 iv
.data
= PK11_IVFromParam(mechanism
, param
, (int *)&iv
.len
);
2257 PORT_Memcpy(pwSpec
->client
.write_iv
, iv
.data
, iv
.len
);
2258 SECITEM_FreeItem(param
,PR_TRUE
);
2259 if (clientContext
== NULL
) {
2260 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE
);
2263 pwSpec
->encode
= (SSLCipher
) PK11_CipherOp
;
2264 pwSpec
->decode
= (SSLCipher
) PK11_CipherOp
;
2265 pwSpec
->destroy
= (SSLDestroy
) PK11_DestroyContext
;
2267 pwSpec
->encodeContext
= (ss
->sec
.isServer
) ? serverContext
: clientContext
;
2268 pwSpec
->decodeContext
= (ss
->sec
.isServer
) ? clientContext
: serverContext
;
2270 serverContext
= NULL
;
2271 clientContext
= NULL
;
2273 ssl3_InitCompressionContext(pwSpec
);
2278 if (serverContext
!= NULL
) PK11_DestroyContext(serverContext
, PR_TRUE
);
2279 if (clientContext
!= NULL
) PK11_DestroyContext(clientContext
, PR_TRUE
);
2280 if (pwSpec
->client
.write_mac_context
!= NULL
) {
2281 PK11_DestroyContext(pwSpec
->client
.write_mac_context
,PR_TRUE
);
2282 pwSpec
->client
.write_mac_context
= NULL
;
2284 if (pwSpec
->server
.write_mac_context
!= NULL
) {
2285 PK11_DestroyContext(pwSpec
->server
.write_mac_context
,PR_TRUE
);
2286 pwSpec
->server
.write_mac_context
= NULL
;
2292 /* Complete the initialization of all keys, ciphers, MACs and their contexts
2293 * for the pending Cipher Spec.
2294 * Called from: ssl3_SendClientKeyExchange (for Full handshake)
2295 * ssl3_HandleRSAClientKeyExchange (for Full handshake)
2296 * ssl3_HandleServerHello (for session restart)
2297 * ssl3_HandleClientHello (for session restart)
2298 * Sets error code, but caller probably should override to disambiguate.
2299 * NULL pms means re-use old master_secret.
2301 * This code is common to the bypass and PKCS11 execution paths.
2302 * For the bypass case, pms is NULL.
2305 ssl3_InitPendingCipherSpec(sslSocket
*ss
, PK11SymKey
*pms
)
2307 ssl3CipherSpec
* pwSpec
;
2308 ssl3CipherSpec
* cwSpec
;
2311 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
2313 ssl_GetSpecWriteLock(ss
); /**************************************/
2315 PORT_Assert(ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
);
2317 pwSpec
= ss
->ssl3
.pwSpec
;
2318 cwSpec
= ss
->ssl3
.cwSpec
;
2320 if (pms
|| (!pwSpec
->msItem
.len
&& !pwSpec
->master_secret
)) {
2321 rv
= ssl3_DeriveMasterSecret(ss
, pms
);
2322 if (rv
!= SECSuccess
) {
2323 goto done
; /* err code set by ssl3_DeriveMasterSecret */
2326 #ifndef NO_PKCS11_BYPASS
2327 if (ss
->opt
.bypassPKCS11
&& pwSpec
->msItem
.len
&& pwSpec
->msItem
.data
) {
2328 /* Double Bypass succeeded in extracting the master_secret */
2329 const ssl3KEADef
* kea_def
= ss
->ssl3
.hs
.kea_def
;
2330 PRBool isTLS
= (PRBool
)(kea_def
->tls_keygen
||
2331 (pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
));
2332 pwSpec
->bypassCiphers
= PR_TRUE
;
2333 rv
= ssl3_KeyAndMacDeriveBypass( pwSpec
,
2334 (const unsigned char *)&ss
->ssl3
.hs
.client_random
,
2335 (const unsigned char *)&ss
->ssl3
.hs
.server_random
,
2337 (PRBool
)(kea_def
->is_limited
));
2338 if (rv
== SECSuccess
) {
2339 rv
= ssl3_InitPendingContextsBypass(ss
);
2343 if (pwSpec
->master_secret
) {
2344 rv
= ssl3_DeriveConnectionKeysPKCS11(ss
);
2345 if (rv
== SECSuccess
) {
2346 rv
= ssl3_InitPendingContextsPKCS11(ss
);
2349 PORT_Assert(pwSpec
->master_secret
);
2350 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
2353 if (rv
!= SECSuccess
) {
2357 /* Generic behaviors -- common to all crypto methods */
2359 pwSpec
->read_seq_num
.high
= pwSpec
->write_seq_num
.high
= 0;
2361 if (cwSpec
->epoch
== PR_UINT16_MAX
) {
2362 /* The problem here is that we have rehandshaked too many
2363 * times (you are not allowed to wrap the epoch). The
2364 * spec says you should be discarding the connection
2365 * and start over, so not much we can do here. */
2366 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
2370 /* The sequence number has the high 16 bits as the epoch. */
2371 pwSpec
->epoch
= cwSpec
->epoch
+ 1;
2372 pwSpec
->read_seq_num
.high
= pwSpec
->write_seq_num
.high
=
2373 pwSpec
->epoch
<< 16;
2375 dtls_InitRecvdRecords(&pwSpec
->recvdRecords
);
2377 pwSpec
->read_seq_num
.low
= pwSpec
->write_seq_num
.low
= 0;
2380 ssl_ReleaseSpecWriteLock(ss
); /******************************/
2381 if (rv
!= SECSuccess
)
2382 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE
);
2387 * 60 bytes is 3 times the maximum length MAC size that is supported.
2389 static const unsigned char mac_pad_1
[60] = {
2390 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2391 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2392 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2393 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2394 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2395 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2396 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2397 0x36, 0x36, 0x36, 0x36
2399 static const unsigned char mac_pad_2
[60] = {
2400 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2401 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2402 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2403 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2404 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2405 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2406 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2407 0x5c, 0x5c, 0x5c, 0x5c
2410 /* Called from: ssl3_SendRecord()
2411 ** Caller must already hold the SpecReadLock. (wish we could assert that!)
2414 ssl3_ComputeRecordMAC(
2415 ssl3CipherSpec
* spec
,
2416 PRBool useServerMacKey
,
2417 const unsigned char *header
,
2418 unsigned int headerLen
,
2419 const SSL3Opaque
* input
,
2421 unsigned char * outbuf
,
2422 unsigned int * outLength
)
2424 const ssl3MACDef
* mac_def
;
2427 PRINT_BUF(95, (NULL
, "frag hash1: header", header
, headerLen
));
2428 PRINT_BUF(95, (NULL
, "frag hash1: input", input
, inputLength
));
2430 mac_def
= spec
->mac_def
;
2431 if (mac_def
->mac
== mac_null
) {
2435 #ifndef NO_PKCS11_BYPASS
2436 if (spec
->bypassCiphers
) {
2437 /* bypass version */
2438 const SECHashObject
*hashObj
= NULL
;
2439 unsigned int pad_bytes
= 0;
2440 PRUint64 write_mac_context
[MAX_MAC_CONTEXT_LLONGS
];
2442 switch (mac_def
->mac
) {
2448 hashObj
= HASH_GetRawHashObject(HASH_AlgMD5
);
2452 hashObj
= HASH_GetRawHashObject(HASH_AlgSHA1
);
2454 case ssl_hmac_md5
: /* used with TLS */
2455 hashObj
= HASH_GetRawHashObject(HASH_AlgMD5
);
2457 case ssl_hmac_sha
: /* used with TLS */
2458 hashObj
= HASH_GetRawHashObject(HASH_AlgSHA1
);
2460 case ssl_hmac_sha256
: /* used with TLS */
2461 hashObj
= HASH_GetRawHashObject(HASH_AlgSHA256
);
2468 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
2472 if (spec
->version
<= SSL_LIBRARY_VERSION_3_0
) {
2473 unsigned int tempLen
;
2474 unsigned char temp
[MAX_MAC_LENGTH
];
2476 /* compute "inner" part of SSL3 MAC */
2477 hashObj
->begin(write_mac_context
);
2478 if (useServerMacKey
)
2479 hashObj
->update(write_mac_context
,
2480 spec
->server
.write_mac_key_item
.data
,
2481 spec
->server
.write_mac_key_item
.len
);
2483 hashObj
->update(write_mac_context
,
2484 spec
->client
.write_mac_key_item
.data
,
2485 spec
->client
.write_mac_key_item
.len
);
2486 hashObj
->update(write_mac_context
, mac_pad_1
, pad_bytes
);
2487 hashObj
->update(write_mac_context
, header
, headerLen
);
2488 hashObj
->update(write_mac_context
, input
, inputLength
);
2489 hashObj
->end(write_mac_context
, temp
, &tempLen
, sizeof temp
);
2491 /* compute "outer" part of SSL3 MAC */
2492 hashObj
->begin(write_mac_context
);
2493 if (useServerMacKey
)
2494 hashObj
->update(write_mac_context
,
2495 spec
->server
.write_mac_key_item
.data
,
2496 spec
->server
.write_mac_key_item
.len
);
2498 hashObj
->update(write_mac_context
,
2499 spec
->client
.write_mac_key_item
.data
,
2500 spec
->client
.write_mac_key_item
.len
);
2501 hashObj
->update(write_mac_context
, mac_pad_2
, pad_bytes
);
2502 hashObj
->update(write_mac_context
, temp
, tempLen
);
2503 hashObj
->end(write_mac_context
, outbuf
, outLength
, spec
->mac_size
);
2505 } else { /* is TLS */
2506 #define cx ((HMACContext *)write_mac_context)
2507 if (useServerMacKey
) {
2508 rv
= HMAC_Init(cx
, hashObj
,
2509 spec
->server
.write_mac_key_item
.data
,
2510 spec
->server
.write_mac_key_item
.len
, PR_FALSE
);
2512 rv
= HMAC_Init(cx
, hashObj
,
2513 spec
->client
.write_mac_key_item
.data
,
2514 spec
->client
.write_mac_key_item
.len
, PR_FALSE
);
2516 if (rv
== SECSuccess
) {
2518 HMAC_Update(cx
, header
, headerLen
);
2519 HMAC_Update(cx
, input
, inputLength
);
2520 rv
= HMAC_Finish(cx
, outbuf
, outLength
, spec
->mac_size
);
2521 HMAC_Destroy(cx
, PR_FALSE
);
2528 PK11Context
*mac_context
=
2529 (useServerMacKey
? spec
->server
.write_mac_context
2530 : spec
->client
.write_mac_context
);
2531 rv
= PK11_DigestBegin(mac_context
);
2532 rv
|= PK11_DigestOp(mac_context
, header
, headerLen
);
2533 rv
|= PK11_DigestOp(mac_context
, input
, inputLength
);
2534 rv
|= PK11_DigestFinal(mac_context
, outbuf
, outLength
, spec
->mac_size
);
2537 PORT_Assert(rv
!= SECSuccess
|| *outLength
== (unsigned)spec
->mac_size
);
2539 PRINT_BUF(95, (NULL
, "frag hash2: result", outbuf
, *outLength
));
2541 if (rv
!= SECSuccess
) {
2543 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE
);
2548 /* Called from: ssl3_HandleRecord()
2549 * Caller must already hold the SpecReadLock. (wish we could assert that!)
2552 * originalLen >= inputLen >= MAC size
2555 ssl3_ComputeRecordMACConstantTime(
2556 ssl3CipherSpec
* spec
,
2557 PRBool useServerMacKey
,
2558 const unsigned char *header
,
2559 unsigned int headerLen
,
2560 const SSL3Opaque
* input
,
2563 unsigned char * outbuf
,
2564 unsigned int * outLen
)
2566 CK_MECHANISM_TYPE macType
;
2567 CK_NSS_MAC_CONSTANT_TIME_PARAMS params
;
2568 SECItem param
, inputItem
, outputItem
;
2572 PORT_Assert(inputLen
>= spec
->mac_size
);
2573 PORT_Assert(originalLen
>= inputLen
);
2575 if (spec
->bypassCiphers
) {
2576 /* This function doesn't support PKCS#11 bypass. We fallback on the
2577 * non-constant time version. */
2581 if (spec
->mac_def
->mac
== mac_null
) {
2586 macType
= CKM_NSS_HMAC_CONSTANT_TIME
;
2587 if (spec
->version
<= SSL_LIBRARY_VERSION_3_0
) {
2588 macType
= CKM_NSS_SSL3_MAC_CONSTANT_TIME
;
2591 params
.macAlg
= spec
->mac_def
->mmech
;
2592 params
.ulBodyTotalLen
= originalLen
;
2593 params
.pHeader
= (unsigned char *) header
; /* const cast */
2594 params
.ulHeaderLen
= headerLen
;
2596 param
.data
= (unsigned char*) ¶ms
;
2597 param
.len
= sizeof(params
);
2600 inputItem
.data
= (unsigned char *) input
;
2601 inputItem
.len
= inputLen
;
2604 outputItem
.data
= outbuf
;
2605 outputItem
.len
= *outLen
;
2606 outputItem
.type
= 0;
2608 key
= spec
->server
.write_mac_key
;
2609 if (!useServerMacKey
) {
2610 key
= spec
->client
.write_mac_key
;
2613 rv
= PK11_SignWithSymKey(key
, macType
, ¶m
, &outputItem
, &inputItem
);
2614 if (rv
!= SECSuccess
) {
2615 if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM
) {
2621 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE
);
2625 PORT_Assert(outputItem
.len
== (unsigned)spec
->mac_size
);
2626 *outLen
= outputItem
.len
;
2631 /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the
2632 * length already. */
2633 inputLen
-= spec
->mac_size
;
2634 return ssl3_ComputeRecordMAC(spec
, useServerMacKey
, header
, headerLen
,
2635 input
, inputLen
, outbuf
, outLen
);
2639 ssl3_ClientAuthTokenPresent(sslSessionID
*sid
) {
2640 PK11SlotInfo
*slot
= NULL
;
2641 PRBool isPresent
= PR_TRUE
;
2643 /* we only care if we are doing client auth */
2644 /* If NSS_PLATFORM_CLIENT_AUTH is defined and a platformClientKey is being
2645 * used, u.ssl3.clAuthValid will be false and this function will always
2646 * return PR_TRUE. */
2647 if (!sid
|| !sid
->u
.ssl3
.clAuthValid
) {
2652 slot
= SECMOD_LookupSlot(sid
->u
.ssl3
.clAuthModuleID
,
2653 sid
->u
.ssl3
.clAuthSlotID
);
2655 !PK11_IsPresent(slot
) ||
2656 sid
->u
.ssl3
.clAuthSeries
!= PK11_GetSlotSeries(slot
) ||
2657 sid
->u
.ssl3
.clAuthSlotID
!= PK11_GetSlotID(slot
) ||
2658 sid
->u
.ssl3
.clAuthModuleID
!= PK11_GetModuleID(slot
) ||
2659 (PK11_NeedLogin(slot
) && !PK11_IsLoggedIn(slot
, NULL
))) {
2660 isPresent
= PR_FALSE
;
2663 PK11_FreeSlot(slot
);
2668 /* Caller must hold the spec read lock. */
2670 ssl3_CompressMACEncryptRecord(ssl3CipherSpec
* cwSpec
,
2673 PRBool capRecordVersion
,
2674 SSL3ContentType type
,
2675 const SSL3Opaque
* pIn
,
2676 PRUint32 contentLen
,
2679 const ssl3BulkCipherDef
* cipher_def
;
2681 PRUint32 macLen
= 0;
2683 PRUint32 p1Len
, p2Len
, oddLen
= 0;
2686 int cipherBytes
= 0;
2687 unsigned char pseudoHeader
[13];
2688 unsigned int pseudoHeaderLen
;
2690 cipher_def
= cwSpec
->cipher_def
;
2691 headerLen
= isDTLS
? DTLS_RECORD_HEADER_LENGTH
: SSL3_RECORD_HEADER_LENGTH
;
2693 if (cipher_def
->type
== type_block
&&
2694 cwSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_1
) {
2695 /* Prepend the per-record explicit IV using technique 2b from
2696 * RFC 4346 section 6.2.3.2: The IV is a cryptographically
2697 * strong random number XORed with the CBC residue from the previous
2700 ivLen
= cipher_def
->iv_size
;
2701 if (ivLen
> wrBuf
->space
- headerLen
) {
2702 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
2705 rv
= PK11_GenerateRandom(wrBuf
->buf
+ headerLen
, ivLen
);
2706 if (rv
!= SECSuccess
) {
2707 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE
);
2710 rv
= cwSpec
->encode( cwSpec
->encodeContext
,
2711 wrBuf
->buf
+ headerLen
,
2712 &cipherBytes
, /* output and actual outLen */
2713 ivLen
, /* max outlen */
2714 wrBuf
->buf
+ headerLen
,
2715 ivLen
); /* input and inputLen*/
2716 if (rv
!= SECSuccess
|| cipherBytes
!= ivLen
) {
2717 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE
);
2722 if (cwSpec
->compressor
) {
2724 rv
= cwSpec
->compressor(
2725 cwSpec
->compressContext
,
2726 wrBuf
->buf
+ headerLen
+ ivLen
, &outlen
,
2727 wrBuf
->space
- headerLen
- ivLen
, pIn
, contentLen
);
2728 if (rv
!= SECSuccess
)
2730 pIn
= wrBuf
->buf
+ headerLen
+ ivLen
;
2731 contentLen
= outlen
;
2734 pseudoHeaderLen
= ssl3_BuildRecordPseudoHeader(
2735 pseudoHeader
, cwSpec
->write_seq_num
, type
,
2736 cwSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_0
, cwSpec
->version
,
2737 isDTLS
, contentLen
);
2738 PORT_Assert(pseudoHeaderLen
<= sizeof(pseudoHeader
));
2739 if (cipher_def
->type
== type_aead
) {
2740 const int nonceLen
= cipher_def
->explicit_nonce_size
;
2741 const int tagLen
= cipher_def
->tag_size
;
2743 if (headerLen
+ nonceLen
+ contentLen
+ tagLen
> wrBuf
->space
) {
2744 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
2748 cipherBytes
= contentLen
;
2750 isServer
? &cwSpec
->server
: &cwSpec
->client
,
2751 PR_FALSE
, /* do encrypt */
2752 wrBuf
->buf
+ headerLen
, /* output */
2753 &cipherBytes
, /* out len */
2754 wrBuf
->space
- headerLen
, /* max out */
2755 pIn
, contentLen
, /* input */
2756 pseudoHeader
, pseudoHeaderLen
);
2757 if (rv
!= SECSuccess
) {
2758 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE
);
2765 rv
= ssl3_ComputeRecordMAC(cwSpec
, isServer
,
2766 pseudoHeader
, pseudoHeaderLen
, pIn
, contentLen
,
2767 wrBuf
->buf
+ headerLen
+ ivLen
+ contentLen
, &macLen
);
2768 if (rv
!= SECSuccess
) {
2769 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE
);
2774 fragLen
= contentLen
+ macLen
; /* needs to be encrypted */
2775 PORT_Assert(fragLen
<= MAX_FRAGMENT_LENGTH
+ 1024);
2778 * Pad the text (if we're doing a block cipher)
2781 if (cipher_def
->type
== type_block
) {
2782 unsigned char * pBuf
;
2786 oddLen
= contentLen
% cipher_def
->block_size
;
2787 /* Assume blockSize is a power of two */
2788 padding_length
= cipher_def
->block_size
- 1 -
2789 ((fragLen
) & (cipher_def
->block_size
- 1));
2790 fragLen
+= padding_length
+ 1;
2791 PORT_Assert((fragLen
% cipher_def
->block_size
) == 0);
2793 /* Pad according to TLS rules (also acceptable to SSL3). */
2794 pBuf
= &wrBuf
->buf
[headerLen
+ ivLen
+ fragLen
- 1];
2795 for (i
= padding_length
+ 1; i
> 0; --i
) {
2796 *pBuf
-- = padding_length
;
2798 /* now, if contentLen is not a multiple of block size, fix it */
2799 p2Len
= fragLen
- p1Len
;
2809 PORT_Assert( (cipher_def
->block_size
< 2) || \
2810 (p2Len
% cipher_def
->block_size
) == 0);
2811 memmove(wrBuf
->buf
+ headerLen
+ ivLen
+ p1Len
, pIn
+ p1Len
,
2815 int cipherBytesPart1
= -1;
2816 rv
= cwSpec
->encode( cwSpec
->encodeContext
,
2817 wrBuf
->buf
+ headerLen
+ ivLen
, /* output */
2818 &cipherBytesPart1
, /* actual outlen */
2819 p1Len
, /* max outlen */
2820 pIn
, p1Len
); /* input, and inputlen */
2821 PORT_Assert(rv
== SECSuccess
&& cipherBytesPart1
== (int) p1Len
);
2822 if (rv
!= SECSuccess
|| cipherBytesPart1
!= (int) p1Len
) {
2823 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE
);
2826 cipherBytes
+= cipherBytesPart1
;
2829 int cipherBytesPart2
= -1;
2830 rv
= cwSpec
->encode( cwSpec
->encodeContext
,
2831 wrBuf
->buf
+ headerLen
+ ivLen
+ p1Len
,
2832 &cipherBytesPart2
, /* output and actual outLen */
2833 p2Len
, /* max outlen */
2834 wrBuf
->buf
+ headerLen
+ ivLen
+ p1Len
,
2835 p2Len
); /* input and inputLen*/
2836 PORT_Assert(rv
== SECSuccess
&& cipherBytesPart2
== (int) p2Len
);
2837 if (rv
!= SECSuccess
|| cipherBytesPart2
!= (int) p2Len
) {
2838 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE
);
2841 cipherBytes
+= cipherBytesPart2
;
2845 PORT_Assert(cipherBytes
<= MAX_FRAGMENT_LENGTH
+ 1024);
2847 wrBuf
->len
= cipherBytes
+ headerLen
;
2848 wrBuf
->buf
[0] = type
;
2850 SSL3ProtocolVersion version
;
2852 version
= dtls_TLSVersionToDTLSVersion(cwSpec
->version
);
2853 wrBuf
->buf
[1] = MSB(version
);
2854 wrBuf
->buf
[2] = LSB(version
);
2855 wrBuf
->buf
[3] = (unsigned char)(cwSpec
->write_seq_num
.high
>> 24);
2856 wrBuf
->buf
[4] = (unsigned char)(cwSpec
->write_seq_num
.high
>> 16);
2857 wrBuf
->buf
[5] = (unsigned char)(cwSpec
->write_seq_num
.high
>> 8);
2858 wrBuf
->buf
[6] = (unsigned char)(cwSpec
->write_seq_num
.high
>> 0);
2859 wrBuf
->buf
[7] = (unsigned char)(cwSpec
->write_seq_num
.low
>> 24);
2860 wrBuf
->buf
[8] = (unsigned char)(cwSpec
->write_seq_num
.low
>> 16);
2861 wrBuf
->buf
[9] = (unsigned char)(cwSpec
->write_seq_num
.low
>> 8);
2862 wrBuf
->buf
[10] = (unsigned char)(cwSpec
->write_seq_num
.low
>> 0);
2863 wrBuf
->buf
[11] = MSB(cipherBytes
);
2864 wrBuf
->buf
[12] = LSB(cipherBytes
);
2866 SSL3ProtocolVersion version
= cwSpec
->version
;
2868 if (capRecordVersion
) {
2869 version
= PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0
, version
);
2871 wrBuf
->buf
[1] = MSB(version
);
2872 wrBuf
->buf
[2] = LSB(version
);
2873 wrBuf
->buf
[3] = MSB(cipherBytes
);
2874 wrBuf
->buf
[4] = LSB(cipherBytes
);
2877 ssl3_BumpSequenceNumber(&cwSpec
->write_seq_num
);
2882 /* Process the plain text before sending it.
2883 * Returns the number of bytes of plaintext that were successfully sent
2884 * plus the number of bytes of plaintext that were copied into the
2885 * output (write) buffer.
2886 * Returns SECFailure on a hard IO error, memory error, or crypto error.
2887 * Does NOT return SECWouldBlock.
2889 * Notes on the use of the private ssl flags:
2890 * (no private SSL flags)
2891 * Attempt to make and send SSL records for all plaintext
2892 * If non-blocking and a send gets WOULD_BLOCK,
2893 * or if the pending (ciphertext) buffer is not empty,
2894 * then buffer remaining bytes of ciphertext into pending buf,
2895 * and continue to do that for all succssive records until all
2897 * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2898 * As above, except this suppresses all write attempts, and forces
2899 * all ciphertext into the pending ciphertext buffer.
2900 * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
2901 * Forces the use of the provided epoch
2902 * ssl_SEND_FLAG_CAP_RECORD_VERSION
2903 * Caps the record layer version number of TLS ClientHello to { 3, 1 }
2904 * (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore
2905 * ClientHello.client_version and use the record layer version number
2906 * (TLSPlaintext.version) instead when negotiating protocol versions. In
2907 * addition, if the record layer version number of ClientHello is { 3, 2 }
2908 * (TLS 1.1) or higher, these servers reset the TCP connections. Lastly,
2909 * some F5 BIG-IP servers hang if a record containing a ClientHello has a
2910 * version greater than { 3, 1 } and a length greater than 255. Set this
2911 * flag to work around such servers.
2914 ssl3_SendRecord( sslSocket
* ss
,
2915 DTLSEpoch epoch
, /* DTLS only */
2916 SSL3ContentType type
,
2917 const SSL3Opaque
* pIn
, /* input buffer */
2918 PRInt32 nIn
, /* bytes of input */
2921 sslBuffer
* wrBuf
= &ss
->sec
.writeBuf
;
2923 PRInt32 totalSent
= 0;
2924 PRBool capRecordVersion
;
2926 SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
2927 SSL_GETPID(), ss
->fd
, ssl3_DecodeContentType(type
),
2929 PRINT_BUF(50, (ss
, "Send record (plain text)", pIn
, nIn
));
2931 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
2933 if (ss
->ssl3
.fatalAlertSent
) {
2934 SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent",
2935 SSL_GETPID(), ss
->fd
));
2939 capRecordVersion
= ((flags
& ssl_SEND_FLAG_CAP_RECORD_VERSION
) != 0);
2941 if (capRecordVersion
) {
2942 /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the
2943 * TLS initial ClientHello. */
2944 PORT_Assert(!IS_DTLS(ss
));
2945 PORT_Assert(!ss
->firstHsDone
);
2946 PORT_Assert(type
== content_handshake
);
2947 PORT_Assert(ss
->ssl3
.hs
.ws
== wait_server_hello
);
2950 if (ss
->ssl3
.initialized
== PR_FALSE
) {
2951 /* This can happen on a server if the very first incoming record
2952 ** looks like a defective ssl3 record (e.g. too long), and we're
2953 ** trying to send an alert.
2955 PR_ASSERT(type
== content_alert
);
2956 rv
= ssl3_InitState(ss
);
2957 if (rv
!= SECSuccess
) {
2958 return SECFailure
; /* ssl3_InitState has set the error code. */
2962 /* check for Token Presence */
2963 if (!ssl3_ClientAuthTokenPresent(ss
->sec
.ci
.sid
)) {
2964 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL
);
2969 PRUint32 contentLen
= PR_MIN(nIn
, MAX_FRAGMENT_LENGTH
);
2970 unsigned int spaceNeeded
;
2971 unsigned int numRecords
;
2973 ssl_GetSpecReadLock(ss
); /********************************/
2975 if (nIn
> 1 && ss
->opt
.cbcRandomIV
&&
2976 ss
->ssl3
.cwSpec
->version
< SSL_LIBRARY_VERSION_TLS_1_1
&&
2977 type
== content_application_data
&&
2978 ss
->ssl3
.cwSpec
->cipher_def
->type
== type_block
/* CBC mode */) {
2979 /* We will split the first byte of the record into its own record,
2980 * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h
2987 spaceNeeded
= contentLen
+ (numRecords
* SSL3_BUFFER_FUDGE
);
2988 if (ss
->ssl3
.cwSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_1
&&
2989 ss
->ssl3
.cwSpec
->cipher_def
->type
== type_block
) {
2990 spaceNeeded
+= ss
->ssl3
.cwSpec
->cipher_def
->iv_size
;
2992 if (spaceNeeded
> wrBuf
->space
) {
2993 rv
= sslBuffer_Grow(wrBuf
, spaceNeeded
);
2994 if (rv
!= SECSuccess
) {
2995 SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes",
2996 SSL_GETPID(), ss
->fd
, spaceNeeded
));
2997 goto spec_locked_loser
; /* sslBuffer_Grow set error code. */
3001 if (numRecords
== 2) {
3002 sslBuffer secondRecord
;
3004 rv
= ssl3_CompressMACEncryptRecord(ss
->ssl3
.cwSpec
,
3005 ss
->sec
.isServer
, IS_DTLS(ss
),
3006 capRecordVersion
, type
, pIn
,
3008 if (rv
!= SECSuccess
)
3009 goto spec_locked_loser
;
3011 PRINT_BUF(50, (ss
, "send (encrypted) record data [1/2]:",
3012 wrBuf
->buf
, wrBuf
->len
));
3014 secondRecord
.buf
= wrBuf
->buf
+ wrBuf
->len
;
3015 secondRecord
.len
= 0;
3016 secondRecord
.space
= wrBuf
->space
- wrBuf
->len
;
3018 rv
= ssl3_CompressMACEncryptRecord(ss
->ssl3
.cwSpec
,
3019 ss
->sec
.isServer
, IS_DTLS(ss
),
3020 capRecordVersion
, type
,
3021 pIn
+ 1, contentLen
- 1,
3023 if (rv
== SECSuccess
) {
3024 PRINT_BUF(50, (ss
, "send (encrypted) record data [2/2]:",
3025 secondRecord
.buf
, secondRecord
.len
));
3026 wrBuf
->len
+= secondRecord
.len
;
3030 rv
= ssl3_CompressMACEncryptRecord(ss
->ssl3
.cwSpec
,
3037 rv
= dtls_CompressMACEncryptRecord(ss
, epoch
,
3038 !!(flags
& ssl_SEND_FLAG_USE_EPOCH
),
3043 if (rv
== SECSuccess
) {
3044 PRINT_BUF(50, (ss
, "send (encrypted) record data:",
3045 wrBuf
->buf
, wrBuf
->len
));
3050 ssl_ReleaseSpecReadLock(ss
); /************************************/
3052 if (rv
!= SECSuccess
)
3057 PORT_Assert( nIn
>= 0 );
3059 /* If there's still some previously saved ciphertext,
3060 * or the caller doesn't want us to send the data yet,
3061 * then add all our new ciphertext to the amount previously saved.
3063 if ((ss
->pendingBuf
.len
> 0) ||
3064 (flags
& ssl_SEND_FLAG_FORCE_INTO_BUFFER
)) {
3066 rv
= ssl_SaveWriteData(ss
, wrBuf
->buf
, wrBuf
->len
);
3067 if (rv
!= SECSuccess
) {
3068 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
3071 wrBuf
->len
= 0; /* All cipher text is saved away. */
3073 if (!(flags
& ssl_SEND_FLAG_FORCE_INTO_BUFFER
)) {
3075 ss
->handshakeBegun
= 1;
3076 sent
= ssl_SendSavedWriteData(ss
);
3077 if (sent
< 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR
) {
3078 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE
);
3081 if (ss
->pendingBuf
.len
) {
3082 flags
|= ssl_SEND_FLAG_FORCE_INTO_BUFFER
;
3085 } else if (wrBuf
->len
> 0) {
3087 ss
->handshakeBegun
= 1;
3088 sent
= ssl_DefSend(ss
, wrBuf
->buf
, wrBuf
->len
,
3089 flags
& ~ssl_SEND_FLAG_MASK
);
3091 if (PR_GetError() != PR_WOULD_BLOCK_ERROR
) {
3092 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE
);
3095 /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
3101 /* DTLS just says no in this case. No buffering */
3102 PR_SetError(PR_WOULD_BLOCK_ERROR
, 0);
3105 /* now take all the remaining unsent new ciphertext and
3106 * append it to the buffer of previously unsent ciphertext.
3108 rv
= ssl_SaveWriteData(ss
, wrBuf
->buf
+ sent
, wrBuf
->len
);
3109 if (rv
!= SECSuccess
) {
3110 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
3115 totalSent
+= contentLen
;
3120 #define SSL3_PENDING_HIGH_WATER 1024
3122 /* Attempt to send the content of "in" in an SSL application_data record.
3123 * Returns "len" or SECFailure, never SECWouldBlock, nor SECSuccess.
3126 ssl3_SendApplicationData(sslSocket
*ss
, const unsigned char *in
,
3127 PRInt32 len
, PRInt32 flags
)
3129 PRInt32 totalSent
= 0;
3130 PRInt32 discarded
= 0;
3132 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
3133 /* These flags for internal use only */
3134 PORT_Assert(!(flags
& (ssl_SEND_FLAG_USE_EPOCH
|
3135 ssl_SEND_FLAG_NO_RETRANSMIT
)));
3136 if (len
< 0 || !in
) {
3137 PORT_SetError(PR_INVALID_ARGUMENT_ERROR
);
3141 if (ss
->pendingBuf
.len
> SSL3_PENDING_HIGH_WATER
&&
3142 !ssl_SocketIsBlocking(ss
)) {
3143 PORT_Assert(!ssl_SocketIsBlocking(ss
));
3144 PORT_SetError(PR_WOULD_BLOCK_ERROR
);
3148 if (ss
->appDataBuffered
&& len
) {
3149 PORT_Assert (in
[0] == (unsigned char)(ss
->appDataBuffered
));
3150 if (in
[0] != (unsigned char)(ss
->appDataBuffered
)) {
3151 PORT_SetError(PR_INVALID_ARGUMENT_ERROR
);
3158 while (len
> totalSent
) {
3159 PRInt32 sent
, toSend
;
3161 if (totalSent
> 0) {
3163 * The thread yield is intended to give the reader thread a
3164 * chance to get some cycles while the writer thread is in
3165 * the middle of a large application data write. (See
3166 * Bugzilla bug 127740, comment #1.)
3168 ssl_ReleaseXmitBufLock(ss
);
3169 PR_Sleep(PR_INTERVAL_NO_WAIT
); /* PR_Yield(); */
3170 ssl_GetXmitBufLock(ss
);
3172 toSend
= PR_MIN(len
- totalSent
, MAX_FRAGMENT_LENGTH
);
3174 * Note that the 0 epoch is OK because flags will never require
3175 * its use, as guaranteed by the PORT_Assert above.
3177 sent
= ssl3_SendRecord(ss
, 0, content_application_data
,
3178 in
+ totalSent
, toSend
, flags
);
3180 if (totalSent
> 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR
) {
3181 PORT_Assert(ss
->lastWriteBlocked
);
3184 return SECFailure
; /* error code set by ssl3_SendRecord */
3187 if (ss
->pendingBuf
.len
) {
3188 /* must be a non-blocking socket */
3189 PORT_Assert(!ssl_SocketIsBlocking(ss
));
3190 PORT_Assert(ss
->lastWriteBlocked
);
3194 if (ss
->pendingBuf
.len
) {
3195 /* Must be non-blocking. */
3196 PORT_Assert(!ssl_SocketIsBlocking(ss
));
3197 if (totalSent
> 0) {
3198 ss
->appDataBuffered
= 0x100 | in
[totalSent
- 1];
3201 totalSent
= totalSent
+ discarded
- 1;
3202 if (totalSent
<= 0) {
3203 PORT_SetError(PR_WOULD_BLOCK_ERROR
);
3204 totalSent
= SECFailure
;
3208 ss
->appDataBuffered
= 0;
3209 return totalSent
+ discarded
;
3212 /* Attempt to send buffered handshake messages.
3213 * This function returns SECSuccess or SECFailure, never SECWouldBlock.
3214 * Always set sendBuf.len to 0, even when returning SECFailure.
3216 * Depending on whether we are doing DTLS or not, this either calls
3218 * - ssl3_FlushHandshakeMessages if non-DTLS
3219 * - dtls_FlushHandshakeMessages if DTLS
3221 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
3222 * ssl3_AppendHandshake(), ssl3_SendClientHello(),
3223 * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
3224 * ssl3_SendFinished(),
3227 ssl3_FlushHandshake(sslSocket
*ss
, PRInt32 flags
)
3230 return dtls_FlushHandshakeMessages(ss
, flags
);
3232 return ssl3_FlushHandshakeMessages(ss
, flags
);
3236 /* Attempt to send the content of sendBuf buffer in an SSL handshake record.
3237 * This function returns SECSuccess or SECFailure, never SECWouldBlock.
3238 * Always set sendBuf.len to 0, even when returning SECFailure.
3240 * Called from ssl3_FlushHandshake
3243 ssl3_FlushHandshakeMessages(sslSocket
*ss
, PRInt32 flags
)
3245 static const PRInt32 allowedFlags
= ssl_SEND_FLAG_FORCE_INTO_BUFFER
|
3246 ssl_SEND_FLAG_CAP_RECORD_VERSION
;
3247 PRInt32 rv
= SECSuccess
;
3249 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
3250 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
3252 if (!ss
->sec
.ci
.sendBuf
.buf
|| !ss
->sec
.ci
.sendBuf
.len
)
3255 /* only these flags are allowed */
3256 PORT_Assert(!(flags
& ~allowedFlags
));
3257 if ((flags
& ~allowedFlags
) != 0) {
3258 PORT_SetError(SEC_ERROR_INVALID_ARGS
);
3261 rv
= ssl3_SendRecord(ss
, 0, content_handshake
, ss
->sec
.ci
.sendBuf
.buf
,
3262 ss
->sec
.ci
.sendBuf
.len
, flags
);
3265 int err
= PORT_GetError();
3266 PORT_Assert(err
!= PR_WOULD_BLOCK_ERROR
);
3267 if (err
== PR_WOULD_BLOCK_ERROR
) {
3268 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
3270 } else if (rv
< ss
->sec
.ci
.sendBuf
.len
) {
3271 /* short write should never happen */
3272 PORT_Assert(rv
>= ss
->sec
.ci
.sendBuf
.len
);
3273 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
3279 /* Whether we succeeded or failed, toss the old handshake data. */
3280 ss
->sec
.ci
.sendBuf
.len
= 0;
3285 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
3286 * the remote client sends a negative response to our certificate request.
3287 * Returns SECFailure if the application has required client auth.
3288 * SECSuccess otherwise.
3291 ssl3_HandleNoCertificate(sslSocket
*ss
)
3293 if (ss
->sec
.peerCert
!= NULL
) {
3294 if (ss
->sec
.peerKey
!= NULL
) {
3295 SECKEY_DestroyPublicKey(ss
->sec
.peerKey
);
3296 ss
->sec
.peerKey
= NULL
;
3298 CERT_DestroyCertificate(ss
->sec
.peerCert
);
3299 ss
->sec
.peerCert
= NULL
;
3301 ssl3_CleanupPeerCerts(ss
);
3303 /* If the server has required client-auth blindly but doesn't
3304 * actually look at the certificate it won't know that no
3305 * certificate was presented so we shutdown the socket to ensure
3306 * an error. We only do this if we haven't already completed the
3307 * first handshake because if we're redoing the handshake we
3308 * know the server is paying attention to the certificate.
3310 if ((ss
->opt
.requireCertificate
== SSL_REQUIRE_ALWAYS
) ||
3311 (!ss
->firstHsDone
&&
3312 (ss
->opt
.requireCertificate
== SSL_REQUIRE_FIRST_HANDSHAKE
))) {
3315 if (ss
->sec
.uncache
)
3316 ss
->sec
.uncache(ss
->sec
.ci
.sid
);
3317 SSL3_SendAlert(ss
, alert_fatal
, bad_certificate
);
3319 lower
= ss
->fd
->lower
;
3321 lower
->methods
->shutdown(lower
, PR_SHUTDOWN_SEND
);
3323 lower
->methods
->shutdown(lower
, PR_SHUTDOWN_BOTH
);
3325 PORT_SetError(SSL_ERROR_NO_CERTIFICATE
);
3331 /************************************************************************
3336 ** Acquires both handshake and XmitBuf locks.
3337 ** Called from: ssl3_IllegalParameter <-
3338 ** ssl3_HandshakeFailure <-
3339 ** ssl3_HandleAlert <- ssl3_HandleRecord.
3340 ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
3341 ** ssl3_ConsumeHandshakeVariable <-
3342 ** ssl3_HandleHelloRequest <-
3343 ** ssl3_HandleServerHello <-
3344 ** ssl3_HandleServerKeyExchange <-
3345 ** ssl3_HandleCertificateRequest <-
3346 ** ssl3_HandleServerHelloDone <-
3347 ** ssl3_HandleClientHello <-
3348 ** ssl3_HandleV2ClientHello <-
3349 ** ssl3_HandleCertificateVerify <-
3350 ** ssl3_HandleClientKeyExchange <-
3351 ** ssl3_HandleCertificate <-
3352 ** ssl3_HandleFinished <-
3353 ** ssl3_HandleHandshakeMessage <-
3354 ** ssl3_HandleRecord <-
3358 SSL3_SendAlert(sslSocket
*ss
, SSL3AlertLevel level
, SSL3AlertDescription desc
)
3363 SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
3364 SSL_GETPID(), ss
->fd
, level
, desc
));
3369 ssl_GetSSL3HandshakeLock(ss
);
3370 if (level
== alert_fatal
) {
3371 if (!ss
->opt
.noCache
&& ss
->sec
.ci
.sid
&& ss
->sec
.uncache
) {
3372 ss
->sec
.uncache(ss
->sec
.ci
.sid
);
3375 ssl_GetXmitBufLock(ss
);
3376 rv
= ssl3_FlushHandshake(ss
, ssl_SEND_FLAG_FORCE_INTO_BUFFER
);
3377 if (rv
== SECSuccess
) {
3379 sent
= ssl3_SendRecord(ss
, 0, content_alert
, bytes
, 2,
3380 desc
== no_certificate
3381 ? ssl_SEND_FLAG_FORCE_INTO_BUFFER
: 0);
3382 rv
= (sent
>= 0) ? SECSuccess
: (SECStatus
)sent
;
3384 if (level
== alert_fatal
) {
3385 ss
->ssl3
.fatalAlertSent
= PR_TRUE
;
3387 ssl_ReleaseXmitBufLock(ss
);
3388 ssl_ReleaseSSL3HandshakeLock(ss
);
3389 return rv
; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
3393 * Send illegal_parameter alert. Set generic error number.
3396 ssl3_IllegalParameter(sslSocket
*ss
)
3398 (void)SSL3_SendAlert(ss
, alert_fatal
, illegal_parameter
);
3399 PORT_SetError(ss
->sec
.isServer
? SSL_ERROR_BAD_CLIENT
3400 : SSL_ERROR_BAD_SERVER
);
3405 * Send handshake_Failure alert. Set generic error number.
3408 ssl3_HandshakeFailure(sslSocket
*ss
)
3410 (void)SSL3_SendAlert(ss
, alert_fatal
, handshake_failure
);
3411 PORT_SetError( ss
->sec
.isServer
? SSL_ERROR_BAD_CLIENT
3412 : SSL_ERROR_BAD_SERVER
);
3417 ssl3_SendAlertForCertError(sslSocket
* ss
, PRErrorCode errCode
)
3419 SSL3AlertDescription desc
= bad_certificate
;
3420 PRBool isTLS
= ss
->version
>= SSL_LIBRARY_VERSION_3_1_TLS
;
3423 case SEC_ERROR_LIBRARY_FAILURE
: desc
= unsupported_certificate
; break;
3424 case SEC_ERROR_EXPIRED_CERTIFICATE
: desc
= certificate_expired
; break;
3425 case SEC_ERROR_REVOKED_CERTIFICATE
: desc
= certificate_revoked
; break;
3426 case SEC_ERROR_INADEQUATE_KEY_USAGE
:
3427 case SEC_ERROR_INADEQUATE_CERT_TYPE
:
3428 desc
= certificate_unknown
; break;
3429 case SEC_ERROR_UNTRUSTED_CERT
:
3430 desc
= isTLS
? access_denied
: certificate_unknown
; break;
3431 case SEC_ERROR_UNKNOWN_ISSUER
:
3432 case SEC_ERROR_UNTRUSTED_ISSUER
:
3433 desc
= isTLS
? unknown_ca
: certificate_unknown
; break;
3434 case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE
:
3435 desc
= isTLS
? unknown_ca
: certificate_expired
; break;
3437 case SEC_ERROR_CERT_NOT_IN_NAME_SPACE
:
3438 case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID
:
3439 case SEC_ERROR_CA_CERT_INVALID
:
3440 case SEC_ERROR_BAD_SIGNATURE
:
3441 default: desc
= bad_certificate
; break;
3443 SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
3444 SSL_GETPID(), ss
->fd
, errCode
));
3446 (void) SSL3_SendAlert(ss
, alert_fatal
, desc
);
3451 * Send decode_error alert. Set generic error number.
3454 ssl3_DecodeError(sslSocket
*ss
)
3456 (void)SSL3_SendAlert(ss
, alert_fatal
,
3457 ss
->version
> SSL_LIBRARY_VERSION_3_0
? decode_error
3458 : illegal_parameter
);
3459 PORT_SetError( ss
->sec
.isServer
? SSL_ERROR_BAD_CLIENT
3460 : SSL_ERROR_BAD_SERVER
);
3464 /* Called from ssl3_HandleRecord.
3465 ** Caller must hold both RecvBuf and Handshake locks.
3468 ssl3_HandleAlert(sslSocket
*ss
, sslBuffer
*buf
)
3470 SSL3AlertLevel level
;
3471 SSL3AlertDescription desc
;
3474 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
3475 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
3477 SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss
->fd
));
3479 if (buf
->len
!= 2) {
3480 (void)ssl3_DecodeError(ss
);
3481 PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT
);
3484 level
= (SSL3AlertLevel
)buf
->buf
[0];
3485 desc
= (SSL3AlertDescription
)buf
->buf
[1];
3487 SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
3488 SSL_GETPID(), ss
->fd
, level
, desc
));
3491 case close_notify
: ss
->recvdCloseNotify
= 1;
3492 error
= SSL_ERROR_CLOSE_NOTIFY_ALERT
; break;
3493 case unexpected_message
: error
= SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT
;
3495 case bad_record_mac
: error
= SSL_ERROR_BAD_MAC_ALERT
; break;
3496 case decryption_failed_RESERVED
:
3497 error
= SSL_ERROR_DECRYPTION_FAILED_ALERT
;
3499 case record_overflow
: error
= SSL_ERROR_RECORD_OVERFLOW_ALERT
; break;
3500 case decompression_failure
: error
= SSL_ERROR_DECOMPRESSION_FAILURE_ALERT
;
3502 case handshake_failure
: error
= SSL_ERROR_HANDSHAKE_FAILURE_ALERT
;
3504 case no_certificate
: error
= SSL_ERROR_NO_CERTIFICATE
; break;
3505 case bad_certificate
: error
= SSL_ERROR_BAD_CERT_ALERT
; break;
3506 case unsupported_certificate
:error
= SSL_ERROR_UNSUPPORTED_CERT_ALERT
;break;
3507 case certificate_revoked
: error
= SSL_ERROR_REVOKED_CERT_ALERT
; break;
3508 case certificate_expired
: error
= SSL_ERROR_EXPIRED_CERT_ALERT
; break;
3509 case certificate_unknown
: error
= SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT
;
3511 case illegal_parameter
: error
= SSL_ERROR_ILLEGAL_PARAMETER_ALERT
;break;
3512 case inappropriate_fallback
:
3513 error
= SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT
;
3516 /* All alerts below are TLS only. */
3517 case unknown_ca
: error
= SSL_ERROR_UNKNOWN_CA_ALERT
; break;
3518 case access_denied
: error
= SSL_ERROR_ACCESS_DENIED_ALERT
; break;
3519 case decode_error
: error
= SSL_ERROR_DECODE_ERROR_ALERT
; break;
3520 case decrypt_error
: error
= SSL_ERROR_DECRYPT_ERROR_ALERT
; break;
3521 case export_restriction
: error
= SSL_ERROR_EXPORT_RESTRICTION_ALERT
;
3523 case protocol_version
: error
= SSL_ERROR_PROTOCOL_VERSION_ALERT
; break;
3524 case insufficient_security
: error
= SSL_ERROR_INSUFFICIENT_SECURITY_ALERT
;
3526 case internal_error
: error
= SSL_ERROR_INTERNAL_ERROR_ALERT
; break;
3527 case user_canceled
: error
= SSL_ERROR_USER_CANCELED_ALERT
; break;
3528 case no_renegotiation
: error
= SSL_ERROR_NO_RENEGOTIATION_ALERT
; break;
3530 /* Alerts for TLS client hello extensions */
3531 case unsupported_extension
:
3532 error
= SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT
; break;
3533 case certificate_unobtainable
:
3534 error
= SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT
; break;
3535 case unrecognized_name
:
3536 error
= SSL_ERROR_UNRECOGNIZED_NAME_ALERT
; break;
3537 case bad_certificate_status_response
:
3538 error
= SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT
; break;
3539 case bad_certificate_hash_value
:
3540 error
= SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT
; break;
3541 default: error
= SSL_ERROR_RX_UNKNOWN_ALERT
; break;
3543 if (level
== alert_fatal
) {
3544 if (!ss
->opt
.noCache
) {
3545 if (ss
->sec
.uncache
)
3546 ss
->sec
.uncache(ss
->sec
.ci
.sid
);
3548 if ((ss
->ssl3
.hs
.ws
== wait_server_hello
) &&
3549 (desc
== handshake_failure
)) {
3550 /* XXX This is a hack. We're assuming that any handshake failure
3551 * XXX on the client hello is a failure to match ciphers.
3553 error
= SSL_ERROR_NO_CYPHER_OVERLAP
;
3555 PORT_SetError(error
);
3558 if ((desc
== no_certificate
) && (ss
->ssl3
.hs
.ws
== wait_client_cert
)) {
3559 /* I'm a server. I've requested a client cert. He hasn't got one. */
3562 PORT_Assert(ss
->sec
.isServer
);
3563 ss
->ssl3
.hs
.ws
= wait_client_key
;
3564 rv
= ssl3_HandleNoCertificate(ss
);
3571 * Change Cipher Specs
3572 * Called from ssl3_HandleServerHelloDone,
3573 * ssl3_HandleClientHello,
3574 * and ssl3_HandleFinished
3576 * Acquires and releases spec write lock, to protect switching the current
3577 * and pending write spec pointers.
3581 ssl3_SendChangeCipherSpecs(sslSocket
*ss
)
3583 PRUint8 change
= change_cipher_spec_choice
;
3584 ssl3CipherSpec
* pwSpec
;
3588 SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
3589 SSL_GETPID(), ss
->fd
));
3591 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
3592 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
3594 rv
= ssl3_FlushHandshake(ss
, ssl_SEND_FLAG_FORCE_INTO_BUFFER
);
3595 if (rv
!= SECSuccess
) {
3596 return rv
; /* error code set by ssl3_FlushHandshake */
3599 sent
= ssl3_SendRecord(ss
, 0, content_change_cipher_spec
, &change
, 1,
3600 ssl_SEND_FLAG_FORCE_INTO_BUFFER
);
3602 return (SECStatus
)sent
; /* error code set by ssl3_SendRecord */
3605 rv
= dtls_QueueMessage(ss
, content_change_cipher_spec
, &change
, 1);
3606 if (rv
!= SECSuccess
) {
3611 /* swap the pending and current write specs. */
3612 ssl_GetSpecWriteLock(ss
); /**************************************/
3613 pwSpec
= ss
->ssl3
.pwSpec
;
3615 ss
->ssl3
.pwSpec
= ss
->ssl3
.cwSpec
;
3616 ss
->ssl3
.cwSpec
= pwSpec
;
3618 SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
3619 SSL_GETPID(), ss
->fd
));
3621 /* We need to free up the contexts, keys and certs ! */
3622 /* If we are really through with the old cipher spec
3623 * (Both the read and write sides have changed) destroy it.
3625 if (ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
) {
3627 ssl3_DestroyCipherSpec(ss
->ssl3
.pwSpec
, PR_FALSE
/*freeSrvName*/);
3629 /* With DTLS, we need to set a holddown timer in case the final
3630 * message got lost */
3631 ss
->ssl3
.hs
.rtTimeoutMs
= DTLS_FINISHED_TIMER_MS
;
3632 dtls_StartTimer(ss
, dtls_FinishedTimerCb
);
3635 ssl_ReleaseSpecWriteLock(ss
); /**************************************/
3640 /* Called from ssl3_HandleRecord.
3641 ** Caller must hold both RecvBuf and Handshake locks.
3643 * Acquires and releases spec write lock, to protect switching the current
3644 * and pending write spec pointers.
3647 ssl3_HandleChangeCipherSpecs(sslSocket
*ss
, sslBuffer
*buf
)
3649 ssl3CipherSpec
* prSpec
;
3650 SSL3WaitState ws
= ss
->ssl3
.hs
.ws
;
3651 SSL3ChangeCipherSpecChoice change
;
3653 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
3654 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
3656 SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
3657 SSL_GETPID(), ss
->fd
));
3659 if (ws
!= wait_change_cipher
) {
3661 /* Ignore this because it's out of order. */
3662 SSL_TRC(3, ("%d: SSL3[%d]: discard out of order "
3663 "DTLS change_cipher_spec",
3664 SSL_GETPID(), ss
->fd
));
3668 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
3669 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER
);
3674 (void)ssl3_DecodeError(ss
);
3675 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER
);
3678 change
= (SSL3ChangeCipherSpecChoice
)buf
->buf
[0];
3679 if (change
!= change_cipher_spec_choice
) {
3680 /* illegal_parameter is correct here for both SSL3 and TLS. */
3681 (void)ssl3_IllegalParameter(ss
);
3682 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER
);
3687 /* Swap the pending and current read specs. */
3688 ssl_GetSpecWriteLock(ss
); /*************************************/
3689 prSpec
= ss
->ssl3
.prSpec
;
3691 ss
->ssl3
.prSpec
= ss
->ssl3
.crSpec
;
3692 ss
->ssl3
.crSpec
= prSpec
;
3693 ss
->ssl3
.hs
.ws
= wait_finished
;
3695 SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
3696 SSL_GETPID(), ss
->fd
));
3698 /* If we are really through with the old cipher prSpec
3699 * (Both the read and write sides have changed) destroy it.
3701 if (ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
) {
3702 ssl3_DestroyCipherSpec(ss
->ssl3
.prSpec
, PR_FALSE
/*freeSrvName*/);
3704 ssl_ReleaseSpecWriteLock(ss
); /*************************************/
3708 /* This method uses PKCS11 to derive the MS from the PMS, where PMS
3709 ** is a PKCS11 symkey. This is used in all cases except the
3710 ** "triple bypass" with RSA key exchange.
3711 ** Called from ssl3_InitPendingCipherSpec. prSpec is pwSpec.
3714 ssl3_DeriveMasterSecret(sslSocket
*ss
, PK11SymKey
*pms
)
3716 ssl3CipherSpec
* pwSpec
= ss
->ssl3
.pwSpec
;
3717 const ssl3KEADef
*kea_def
= ss
->ssl3
.hs
.kea_def
;
3718 unsigned char * cr
= (unsigned char *)&ss
->ssl3
.hs
.client_random
;
3719 unsigned char * sr
= (unsigned char *)&ss
->ssl3
.hs
.server_random
;
3720 PRBool isTLS
= (PRBool
)(kea_def
->tls_keygen
||
3721 (pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
));
3723 (PRBool
)(isTLS
&& pwSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_2
);
3725 * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
3726 * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
3727 * data into a 48-byte value.
3729 PRBool isDH
= (PRBool
) ((ss
->ssl3
.hs
.kea_def
->exchKeyType
== kt_dh
) ||
3730 (ss
->ssl3
.hs
.kea_def
->exchKeyType
== kt_ecdh
));
3731 SECStatus rv
= SECFailure
;
3732 CK_MECHANISM_TYPE master_derive
;
3733 CK_MECHANISM_TYPE key_derive
;
3736 CK_VERSION pms_version
;
3737 CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params
;
3739 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
3740 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSpecWriteLock(ss
));
3741 PORT_Assert(ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
);
3743 if(isDH
) master_derive
= CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256
;
3744 else master_derive
= CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256
;
3745 key_derive
= CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256
;
3746 keyFlags
= CKF_SIGN
| CKF_VERIFY
;
3748 if(isDH
) master_derive
= CKM_TLS_MASTER_KEY_DERIVE_DH
;
3749 else master_derive
= CKM_TLS_MASTER_KEY_DERIVE
;
3750 key_derive
= CKM_TLS_KEY_AND_MAC_DERIVE
;
3751 keyFlags
= CKF_SIGN
| CKF_VERIFY
;
3753 if (isDH
) master_derive
= CKM_SSL3_MASTER_KEY_DERIVE_DH
;
3754 else master_derive
= CKM_SSL3_MASTER_KEY_DERIVE
;
3755 key_derive
= CKM_SSL3_KEY_AND_MAC_DERIVE
;
3759 if (pms
|| !pwSpec
->master_secret
) {
3761 master_params
.pVersion
= NULL
;
3763 master_params
.pVersion
= &pms_version
;
3765 master_params
.RandomInfo
.pClientRandom
= cr
;
3766 master_params
.RandomInfo
.ulClientRandomLen
= SSL3_RANDOM_LENGTH
;
3767 master_params
.RandomInfo
.pServerRandom
= sr
;
3768 master_params
.RandomInfo
.ulServerRandomLen
= SSL3_RANDOM_LENGTH
;
3770 params
.data
= (unsigned char *) &master_params
;
3771 params
.len
= sizeof master_params
;
3776 if (ssl_trace
>= 100) {
3777 SECStatus extractRV
= PK11_ExtractKeyValue(pms
);
3778 if (extractRV
== SECSuccess
) {
3779 SECItem
* keyData
= PK11_GetKeyData(pms
);
3780 if (keyData
&& keyData
->data
&& keyData
->len
) {
3781 ssl_PrintBuf(ss
, "Pre-Master Secret",
3782 keyData
->data
, keyData
->len
);
3787 pwSpec
->master_secret
= PK11_DeriveWithFlags(pms
, master_derive
,
3788 ¶ms
, key_derive
, CKA_DERIVE
, 0, keyFlags
);
3789 if (!isDH
&& pwSpec
->master_secret
&& ss
->opt
.detectRollBack
) {
3790 SSL3ProtocolVersion client_version
;
3791 client_version
= pms_version
.major
<< 8 | pms_version
.minor
;
3794 client_version
= dtls_DTLSVersionToTLSVersion(client_version
);
3797 if (client_version
!= ss
->clientHelloVersion
) {
3798 /* Destroy it. Version roll-back detected. */
3799 PK11_FreeSymKey(pwSpec
->master_secret
);
3800 pwSpec
->master_secret
= NULL
;
3803 if (pwSpec
->master_secret
== NULL
) {
3804 /* Generate a faux master secret in the same slot as the old one. */
3805 PK11SlotInfo
* slot
= PK11_GetSlotFromKey((PK11SymKey
*)pms
);
3806 PK11SymKey
* fpms
= ssl3_GenerateRSAPMS(ss
, pwSpec
, slot
);
3808 PK11_FreeSlot(slot
);
3810 pwSpec
->master_secret
= PK11_DeriveWithFlags(fpms
,
3811 master_derive
, ¶ms
, key_derive
,
3812 CKA_DERIVE
, 0, keyFlags
);
3813 PK11_FreeSymKey(fpms
);
3817 if (pwSpec
->master_secret
== NULL
) {
3818 /* Generate a faux master secret from the internal slot. */
3819 PK11SlotInfo
* slot
= PK11_GetInternalSlot();
3820 PK11SymKey
* fpms
= ssl3_GenerateRSAPMS(ss
, pwSpec
, slot
);
3822 PK11_FreeSlot(slot
);
3824 pwSpec
->master_secret
= PK11_DeriveWithFlags(fpms
,
3825 master_derive
, ¶ms
, key_derive
,
3826 CKA_DERIVE
, 0, keyFlags
);
3827 if (pwSpec
->master_secret
== NULL
) {
3828 pwSpec
->master_secret
= fpms
; /* use the fpms as the master. */
3833 PK11_FreeSymKey(fpms
);
3836 if (pwSpec
->master_secret
== NULL
) {
3837 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE
);
3840 #ifndef NO_PKCS11_BYPASS
3841 if (ss
->opt
.bypassPKCS11
) {
3843 /* In hope of doing a "double bypass",
3844 * need to extract the master secret's value from the key object
3845 * and store it raw in the sslSocket struct.
3847 rv
= PK11_ExtractKeyValue(pwSpec
->master_secret
);
3848 if (rv
!= SECSuccess
) {
3851 /* This returns the address of the secItem inside the key struct,
3852 * not a copy or a reference. So, there's no need to free it.
3854 keydata
= PK11_GetKeyData(pwSpec
->master_secret
);
3855 if (keydata
&& keydata
->len
<= sizeof pwSpec
->raw_master_secret
) {
3856 memcpy(pwSpec
->raw_master_secret
, keydata
->data
, keydata
->len
);
3857 pwSpec
->msItem
.data
= pwSpec
->raw_master_secret
;
3858 pwSpec
->msItem
.len
= keydata
->len
;
3860 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
3870 * Derive encryption and MAC Keys (and IVs) from master secret
3871 * Sets a useful error code when returning SECFailure.
3873 * Called only from ssl3_InitPendingCipherSpec(),
3874 * which in turn is called from
3875 * sendRSAClientKeyExchange (for Full handshake)
3876 * sendDHClientKeyExchange (for Full handshake)
3877 * ssl3_HandleClientKeyExchange (for Full handshake)
3878 * ssl3_HandleServerHello (for session restart)
3879 * ssl3_HandleClientHello (for session restart)
3880 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
3881 * ssl3_InitPendingCipherSpec does that.
3885 ssl3_DeriveConnectionKeysPKCS11(sslSocket
*ss
)
3887 ssl3CipherSpec
* pwSpec
= ss
->ssl3
.pwSpec
;
3888 const ssl3KEADef
* kea_def
= ss
->ssl3
.hs
.kea_def
;
3889 unsigned char * cr
= (unsigned char *)&ss
->ssl3
.hs
.client_random
;
3890 unsigned char * sr
= (unsigned char *)&ss
->ssl3
.hs
.server_random
;
3891 PRBool isTLS
= (PRBool
)(kea_def
->tls_keygen
||
3892 (pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
));
3894 (PRBool
)(isTLS
&& pwSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_2
);
3895 /* following variables used in PKCS11 path */
3896 const ssl3BulkCipherDef
*cipher_def
= pwSpec
->cipher_def
;
3897 PK11SlotInfo
* slot
= NULL
;
3898 PK11SymKey
* symKey
= NULL
;
3899 void * pwArg
= ss
->pkcs11PinArg
;
3901 CK_SSL3_KEY_MAT_PARAMS key_material_params
;
3902 CK_SSL3_KEY_MAT_OUT returnedKeys
;
3903 CK_MECHANISM_TYPE key_derive
;
3904 CK_MECHANISM_TYPE bulk_mechanism
;
3905 SSLCipherAlgorithm calg
;
3907 PRBool skipKeysAndIVs
= (PRBool
)(cipher_def
->calg
== calg_null
);
3909 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
3910 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSpecWriteLock(ss
));
3911 PORT_Assert(ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
);
3913 if (!pwSpec
->master_secret
) {
3914 PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE
);
3918 * generate the key material
3920 key_material_params
.ulMacSizeInBits
= pwSpec
->mac_size
* BPB
;
3921 key_material_params
.ulKeySizeInBits
= cipher_def
->secret_key_size
* BPB
;
3922 key_material_params
.ulIVSizeInBits
= cipher_def
->iv_size
* BPB
;
3923 if (cipher_def
->type
== type_block
&&
3924 pwSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_1
) {
3925 /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
3926 key_material_params
.ulIVSizeInBits
= 0;
3927 memset(pwSpec
->client
.write_iv
, 0, cipher_def
->iv_size
);
3928 memset(pwSpec
->server
.write_iv
, 0, cipher_def
->iv_size
);
3931 key_material_params
.bIsExport
= (CK_BBOOL
)(kea_def
->is_limited
);
3933 key_material_params
.RandomInfo
.pClientRandom
= cr
;
3934 key_material_params
.RandomInfo
.ulClientRandomLen
= SSL3_RANDOM_LENGTH
;
3935 key_material_params
.RandomInfo
.pServerRandom
= sr
;
3936 key_material_params
.RandomInfo
.ulServerRandomLen
= SSL3_RANDOM_LENGTH
;
3937 key_material_params
.pReturnedKeyMaterial
= &returnedKeys
;
3939 returnedKeys
.pIVClient
= pwSpec
->client
.write_iv
;
3940 returnedKeys
.pIVServer
= pwSpec
->server
.write_iv
;
3941 keySize
= cipher_def
->key_size
;
3943 if (skipKeysAndIVs
) {
3945 key_material_params
.ulKeySizeInBits
= 0;
3946 key_material_params
.ulIVSizeInBits
= 0;
3947 returnedKeys
.pIVClient
= NULL
;
3948 returnedKeys
.pIVServer
= NULL
;
3951 calg
= cipher_def
->calg
;
3952 PORT_Assert( alg2Mech
[calg
].calg
== calg
);
3953 bulk_mechanism
= alg2Mech
[calg
].cmech
;
3955 params
.data
= (unsigned char *)&key_material_params
;
3956 params
.len
= sizeof(key_material_params
);
3959 key_derive
= CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256
;
3961 key_derive
= CKM_TLS_KEY_AND_MAC_DERIVE
;
3963 key_derive
= CKM_SSL3_KEY_AND_MAC_DERIVE
;
3966 /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
3967 * DERIVE by DEFAULT */
3968 symKey
= PK11_Derive(pwSpec
->master_secret
, key_derive
, ¶ms
,
3969 bulk_mechanism
, CKA_ENCRYPT
, keySize
);
3971 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE
);
3974 /* we really should use the actual mac'ing mechanism here, but we
3975 * don't because these types are used to map keytype anyway and both
3976 * mac's map to the same keytype.
3978 slot
= PK11_GetSlotFromKey(symKey
);
3980 PK11_FreeSlot(slot
); /* slot is held until the key is freed */
3981 pwSpec
->client
.write_mac_key
=
3982 PK11_SymKeyFromHandle(slot
, symKey
, PK11_OriginDerive
,
3983 CKM_SSL3_SHA1_MAC
, returnedKeys
.hClientMacSecret
, PR_TRUE
, pwArg
);
3984 if (pwSpec
->client
.write_mac_key
== NULL
) {
3985 goto loser
; /* loser sets err */
3987 pwSpec
->server
.write_mac_key
=
3988 PK11_SymKeyFromHandle(slot
, symKey
, PK11_OriginDerive
,
3989 CKM_SSL3_SHA1_MAC
, returnedKeys
.hServerMacSecret
, PR_TRUE
, pwArg
);
3990 if (pwSpec
->server
.write_mac_key
== NULL
) {
3991 goto loser
; /* loser sets err */
3993 if (!skipKeysAndIVs
) {
3994 pwSpec
->client
.write_key
=
3995 PK11_SymKeyFromHandle(slot
, symKey
, PK11_OriginDerive
,
3996 bulk_mechanism
, returnedKeys
.hClientKey
, PR_TRUE
, pwArg
);
3997 if (pwSpec
->client
.write_key
== NULL
) {
3998 goto loser
; /* loser sets err */
4000 pwSpec
->server
.write_key
=
4001 PK11_SymKeyFromHandle(slot
, symKey
, PK11_OriginDerive
,
4002 bulk_mechanism
, returnedKeys
.hServerKey
, PR_TRUE
, pwArg
);
4003 if (pwSpec
->server
.write_key
== NULL
) {
4004 goto loser
; /* loser sets err */
4007 PK11_FreeSymKey(symKey
);
4012 if (symKey
) PK11_FreeSymKey(symKey
);
4013 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE
);
4017 /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
4018 * buffered messages in ss->ssl3.hs.messages. */
4020 ssl3_InitHandshakeHashes(sslSocket
*ss
)
4022 SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss
->fd
));
4024 PORT_Assert(ss
->ssl3
.hs
.hashType
== handshake_hash_unknown
);
4025 #ifndef NO_PKCS11_BYPASS
4026 if (ss
->opt
.bypassPKCS11
) {
4027 PORT_Assert(!ss
->ssl3
.hs
.sha_obj
&& !ss
->ssl3
.hs
.sha_clone
);
4028 if (ss
->version
>= SSL_LIBRARY_VERSION_TLS_1_2
) {
4029 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4030 * then this will need to be updated. */
4031 ss
->ssl3
.hs
.sha_obj
= HASH_GetRawHashObject(HASH_AlgSHA256
);
4032 if (!ss
->ssl3
.hs
.sha_obj
) {
4033 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE
);
4036 ss
->ssl3
.hs
.sha_clone
= (void (*)(void *, void *))SHA256_Clone
;
4037 ss
->ssl3
.hs
.hashType
= handshake_hash_single
;
4038 ss
->ssl3
.hs
.sha_obj
->begin(ss
->ssl3
.hs
.sha_cx
);
4040 ss
->ssl3
.hs
.hashType
= handshake_hash_combo
;
4041 MD5_Begin((MD5Context
*)ss
->ssl3
.hs
.md5_cx
);
4042 SHA1_Begin((SHA1Context
*)ss
->ssl3
.hs
.sha_cx
);
4047 PORT_Assert(!ss
->ssl3
.hs
.md5
&& !ss
->ssl3
.hs
.sha
);
4049 * note: We should probably lookup an SSL3 slot for these
4050 * handshake hashes in hopes that we wind up with the same slots
4051 * that the master secret will wind up in ...
4053 if (ss
->version
>= SSL_LIBRARY_VERSION_TLS_1_2
) {
4054 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4055 * then this will need to be updated. */
4056 ss
->ssl3
.hs
.sha
= PK11_CreateDigestContext(SEC_OID_SHA256
);
4057 if (ss
->ssl3
.hs
.sha
== NULL
) {
4058 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
4061 ss
->ssl3
.hs
.hashType
= handshake_hash_single
;
4063 if (PK11_DigestBegin(ss
->ssl3
.hs
.sha
) != SECSuccess
) {
4064 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE
);
4068 /* Create a backup SHA-1 hash for a potential client auth
4071 * In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the
4072 * handshake hash function (SHA-256). If the server or the client
4073 * does not support SHA-256 as a signature hash, we can either
4074 * maintain a backup SHA-1 handshake hash or buffer all handshake
4077 if (!ss
->sec
.isServer
) {
4078 ss
->ssl3
.hs
.backupHash
= PK11_CreateDigestContext(SEC_OID_SHA1
);
4079 if (ss
->ssl3
.hs
.backupHash
== NULL
) {
4080 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
4084 if (PK11_DigestBegin(ss
->ssl3
.hs
.backupHash
) != SECSuccess
) {
4085 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
4090 /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
4091 * created successfully. */
4092 ss
->ssl3
.hs
.md5
= PK11_CreateDigestContext(SEC_OID_MD5
);
4093 if (ss
->ssl3
.hs
.md5
== NULL
) {
4094 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
4097 ss
->ssl3
.hs
.sha
= PK11_CreateDigestContext(SEC_OID_SHA1
);
4098 if (ss
->ssl3
.hs
.sha
== NULL
) {
4099 PK11_DestroyContext(ss
->ssl3
.hs
.md5
, PR_TRUE
);
4100 ss
->ssl3
.hs
.md5
= NULL
;
4101 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
4104 ss
->ssl3
.hs
.hashType
= handshake_hash_combo
;
4106 if (PK11_DigestBegin(ss
->ssl3
.hs
.md5
) != SECSuccess
) {
4107 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
4110 if (PK11_DigestBegin(ss
->ssl3
.hs
.sha
) != SECSuccess
) {
4111 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
4117 if (ss
->ssl3
.hs
.messages
.len
> 0) {
4118 if (ssl3_UpdateHandshakeHashes(ss
, ss
->ssl3
.hs
.messages
.buf
,
4119 ss
->ssl3
.hs
.messages
.len
) !=
4123 PORT_Free(ss
->ssl3
.hs
.messages
.buf
);
4124 ss
->ssl3
.hs
.messages
.buf
= NULL
;
4125 ss
->ssl3
.hs
.messages
.len
= 0;
4126 ss
->ssl3
.hs
.messages
.space
= 0;
4133 ssl3_RestartHandshakeHashes(sslSocket
*ss
)
4135 SECStatus rv
= SECSuccess
;
4137 SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
4138 SSL_GETPID(), ss
->fd
));
4139 ss
->ssl3
.hs
.hashType
= handshake_hash_unknown
;
4140 ss
->ssl3
.hs
.messages
.len
= 0;
4141 #ifndef NO_PKCS11_BYPASS
4142 ss
->ssl3
.hs
.sha_obj
= NULL
;
4143 ss
->ssl3
.hs
.sha_clone
= NULL
;
4145 if (ss
->ssl3
.hs
.md5
) {
4146 PK11_DestroyContext(ss
->ssl3
.hs
.md5
,PR_TRUE
);
4147 ss
->ssl3
.hs
.md5
= NULL
;
4149 if (ss
->ssl3
.hs
.sha
) {
4150 PK11_DestroyContext(ss
->ssl3
.hs
.sha
,PR_TRUE
);
4151 ss
->ssl3
.hs
.sha
= NULL
;
4157 * Handshake messages
4159 /* Called from ssl3_InitHandshakeHashes()
4160 ** ssl3_AppendHandshake()
4161 ** ssl3_StartHandshakeHash()
4162 ** ssl3_HandleV2ClientHello()
4163 ** ssl3_HandleHandshakeMessage()
4164 ** Caller must hold the ssl3Handshake lock.
4167 ssl3_UpdateHandshakeHashes(sslSocket
*ss
, const unsigned char *b
,
4170 SECStatus rv
= SECSuccess
;
4172 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
4174 /* We need to buffer the handshake messages until we have established
4175 * which handshake hash function to use. */
4176 if (ss
->ssl3
.hs
.hashType
== handshake_hash_unknown
) {
4177 return sslBuffer_Append(&ss
->ssl3
.hs
.messages
, b
, l
);
4180 PRINT_BUF(90, (NULL
, "handshake hash input:", b
, l
));
4182 #ifndef NO_PKCS11_BYPASS
4183 if (ss
->opt
.bypassPKCS11
) {
4184 if (ss
->ssl3
.hs
.hashType
== handshake_hash_single
) {
4185 ss
->ssl3
.hs
.sha_obj
->update(ss
->ssl3
.hs
.sha_cx
, b
, l
);
4187 MD5_Update((MD5Context
*)ss
->ssl3
.hs
.md5_cx
, b
, l
);
4188 SHA1_Update((SHA1Context
*)ss
->ssl3
.hs
.sha_cx
, b
, l
);
4193 if (ss
->ssl3
.hs
.hashType
== handshake_hash_single
) {
4194 rv
= PK11_DigestOp(ss
->ssl3
.hs
.sha
, b
, l
);
4195 if (rv
!= SECSuccess
) {
4196 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE
);
4199 if (ss
->ssl3
.hs
.backupHash
) {
4200 rv
= PK11_DigestOp(ss
->ssl3
.hs
.backupHash
, b
, l
);
4201 if (rv
!= SECSuccess
) {
4202 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
4207 rv
= PK11_DigestOp(ss
->ssl3
.hs
.md5
, b
, l
);
4208 if (rv
!= SECSuccess
) {
4209 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
4212 rv
= PK11_DigestOp(ss
->ssl3
.hs
.sha
, b
, l
);
4213 if (rv
!= SECSuccess
) {
4214 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
4221 /**************************************************************************
4222 * Append Handshake functions.
4223 * All these functions set appropriate error codes.
4224 * Most rely on ssl3_AppendHandshake to set the error code.
4225 **************************************************************************/
4227 ssl3_AppendHandshake(sslSocket
*ss
, const void *void_src
, PRInt32 bytes
)
4229 unsigned char * src
= (unsigned char *)void_src
;
4230 int room
= ss
->sec
.ci
.sendBuf
.space
- ss
->sec
.ci
.sendBuf
.len
;
4233 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) ); /* protects sendBuf. */
4237 if (ss
->sec
.ci
.sendBuf
.space
< MAX_SEND_BUF_LENGTH
&& room
< bytes
) {
4238 rv
= sslBuffer_Grow(&ss
->sec
.ci
.sendBuf
, PR_MAX(MIN_SEND_BUF_LENGTH
,
4239 PR_MIN(MAX_SEND_BUF_LENGTH
, ss
->sec
.ci
.sendBuf
.len
+ bytes
)));
4240 if (rv
!= SECSuccess
)
4241 return rv
; /* sslBuffer_Grow has set a memory error code. */
4242 room
= ss
->sec
.ci
.sendBuf
.space
- ss
->sec
.ci
.sendBuf
.len
;
4245 PRINT_BUF(60, (ss
, "Append to Handshake", (unsigned char*)void_src
, bytes
));
4246 rv
= ssl3_UpdateHandshakeHashes(ss
, src
, bytes
);
4247 if (rv
!= SECSuccess
)
4248 return rv
; /* error code set by ssl3_UpdateHandshakeHashes */
4250 while (bytes
> room
) {
4252 PORT_Memcpy(ss
->sec
.ci
.sendBuf
.buf
+ ss
->sec
.ci
.sendBuf
.len
, src
,
4254 ss
->sec
.ci
.sendBuf
.len
+= room
;
4255 rv
= ssl3_FlushHandshake(ss
, ssl_SEND_FLAG_FORCE_INTO_BUFFER
);
4256 if (rv
!= SECSuccess
) {
4257 return rv
; /* error code set by ssl3_FlushHandshake */
4261 room
= ss
->sec
.ci
.sendBuf
.space
;
4262 PORT_Assert(ss
->sec
.ci
.sendBuf
.len
== 0);
4264 PORT_Memcpy(ss
->sec
.ci
.sendBuf
.buf
+ ss
->sec
.ci
.sendBuf
.len
, src
, bytes
);
4265 ss
->sec
.ci
.sendBuf
.len
+= bytes
;
4270 ssl3_AppendHandshakeNumber(sslSocket
*ss
, PRInt32 num
, PRInt32 lenSize
)
4278 *p
++ = (num
>> 24) & 0xff;
4280 *p
++ = (num
>> 16) & 0xff;
4282 *p
++ = (num
>> 8) & 0xff;
4286 SSL_TRC(60, ("%d: number:", SSL_GETPID()));
4287 rv
= ssl3_AppendHandshake(ss
, &b
[0], lenSize
);
4288 return rv
; /* error code set by AppendHandshake, if applicable. */
4292 ssl3_AppendHandshakeVariable(
4293 sslSocket
*ss
, const SSL3Opaque
*src
, PRInt32 bytes
, PRInt32 lenSize
)
4297 PORT_Assert((bytes
< (1<<8) && lenSize
== 1) ||
4298 (bytes
< (1L<<16) && lenSize
== 2) ||
4299 (bytes
< (1L<<24) && lenSize
== 3));
4301 SSL_TRC(60,("%d: append variable:", SSL_GETPID()));
4302 rv
= ssl3_AppendHandshakeNumber(ss
, bytes
, lenSize
);
4303 if (rv
!= SECSuccess
) {
4304 return rv
; /* error code set by AppendHandshake, if applicable. */
4306 SSL_TRC(60, ("data:"));
4307 rv
= ssl3_AppendHandshake(ss
, src
, bytes
);
4308 return rv
; /* error code set by AppendHandshake, if applicable. */
4312 ssl3_AppendHandshakeHeader(sslSocket
*ss
, SSL3HandshakeType t
, PRUint32 length
)
4316 /* If we already have a message in place, we need to enqueue it.
4317 * This empties the buffer. This is a convenient place to call
4318 * dtls_StageHandshakeMessage to mark the message boundary.
4321 rv
= dtls_StageHandshakeMessage(ss
);
4322 if (rv
!= SECSuccess
) {
4327 SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s",
4328 SSL_GETPID(), ss
->fd
, ssl3_DecodeHandshakeType(t
)));
4330 rv
= ssl3_AppendHandshakeNumber(ss
, t
, 1);
4331 if (rv
!= SECSuccess
) {
4332 return rv
; /* error code set by AppendHandshake, if applicable. */
4334 rv
= ssl3_AppendHandshakeNumber(ss
, length
, 3);
4335 if (rv
!= SECSuccess
) {
4336 return rv
; /* error code set by AppendHandshake, if applicable. */
4340 /* Note that we make an unfragmented message here. We fragment in the
4341 * transmission code, if necessary */
4342 rv
= ssl3_AppendHandshakeNumber(ss
, ss
->ssl3
.hs
.sendMessageSeq
, 2);
4343 if (rv
!= SECSuccess
) {
4344 return rv
; /* error code set by AppendHandshake, if applicable. */
4346 ss
->ssl3
.hs
.sendMessageSeq
++;
4348 /* 0 is the fragment offset, because it's not fragmented yet */
4349 rv
= ssl3_AppendHandshakeNumber(ss
, 0, 3);
4350 if (rv
!= SECSuccess
) {
4351 return rv
; /* error code set by AppendHandshake, if applicable. */
4354 /* Fragment length -- set to the packet length because not fragmented */
4355 rv
= ssl3_AppendHandshakeNumber(ss
, length
, 3);
4356 if (rv
!= SECSuccess
) {
4357 return rv
; /* error code set by AppendHandshake, if applicable. */
4361 return rv
; /* error code set by AppendHandshake, if applicable. */
4364 /* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of
4365 * |sigAndHash| to the current handshake message. */
4367 ssl3_AppendSignatureAndHashAlgorithm(
4368 sslSocket
*ss
, const SSL3SignatureAndHashAlgorithm
* sigAndHash
)
4370 unsigned char serialized
[2];
4372 serialized
[0] = ssl3_OIDToTLSHashAlgorithm(sigAndHash
->hashAlg
);
4373 if (serialized
[0] == 0) {
4374 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM
);
4378 serialized
[1] = sigAndHash
->sigAlg
;
4380 return ssl3_AppendHandshake(ss
, serialized
, sizeof(serialized
));
4383 /**************************************************************************
4384 * Consume Handshake functions.
4386 * All data used in these functions is protected by two locks,
4387 * the RecvBufLock and the SSL3HandshakeLock
4388 **************************************************************************/
4390 /* Read up the next "bytes" number of bytes from the (decrypted) input
4391 * stream "b" (which is *length bytes long). Copy them into buffer "v".
4392 * Reduces *length by bytes. Advances *b by bytes.
4394 * If this function returns SECFailure, it has already sent an alert,
4395 * and has set a generic error code. The caller should probably
4396 * override the generic error code by setting another.
4399 ssl3_ConsumeHandshake(sslSocket
*ss
, void *v
, PRInt32 bytes
, SSL3Opaque
**b
,
4402 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
4403 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
4405 if ((PRUint32
)bytes
> *length
) {
4406 return ssl3_DecodeError(ss
);
4408 PORT_Memcpy(v
, *b
, bytes
);
4409 PRINT_BUF(60, (ss
, "consume bytes:", *b
, bytes
));
4415 /* Read up the next "bytes" number of bytes from the (decrypted) input
4416 * stream "b" (which is *length bytes long), and interpret them as an
4417 * integer in network byte order. Returns the received value.
4418 * Reduces *length by bytes. Advances *b by bytes.
4420 * Returns SECFailure (-1) on failure.
4421 * This value is indistinguishable from the equivalent received value.
4422 * Only positive numbers are to be received this way.
4423 * Thus, the largest value that may be sent this way is 0x7fffffff.
4424 * On error, an alert has been sent, and a generic error code has been set.
4427 ssl3_ConsumeHandshakeNumber(sslSocket
*ss
, PRInt32 bytes
, SSL3Opaque
**b
,
4434 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
4435 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
4436 PORT_Assert( bytes
<= sizeof num
);
4438 if ((PRUint32
)bytes
> *length
) {
4439 return ssl3_DecodeError(ss
);
4441 PRINT_BUF(60, (ss
, "consume bytes:", *b
, bytes
));
4443 for (i
= 0; i
< bytes
; i
++)
4444 num
= (num
<< 8) + buf
[i
];
4450 /* Read in two values from the incoming decrypted byte stream "b", which is
4451 * *length bytes long. The first value is a number whose size is "bytes"
4452 * bytes long. The second value is a byte-string whose size is the value
4453 * of the first number received. The latter byte-string, and its length,
4454 * is returned in the SECItem i.
4456 * Returns SECFailure (-1) on failure.
4457 * On error, an alert has been sent, and a generic error code has been set.
4459 * RADICAL CHANGE for NSS 3.11. All callers of this function make copies
4460 * of the data returned in the SECItem *i, so making a copy of it here
4461 * is simply wasteful. So, This function now just sets SECItem *i to
4462 * point to the values in the buffer **b.
4465 ssl3_ConsumeHandshakeVariable(sslSocket
*ss
, SECItem
*i
, PRInt32 bytes
,
4466 SSL3Opaque
**b
, PRUint32
*length
)
4470 PORT_Assert(bytes
<= 3);
4473 count
= ssl3_ConsumeHandshakeNumber(ss
, bytes
, b
, length
);
4474 if (count
< 0) { /* Can't test for SECSuccess here. */
4478 if ((PRUint32
)count
> *length
) {
4479 return ssl3_DecodeError(ss
);
4489 /* tlsHashOIDMap contains the mapping between TLS hash identifiers and the
4490 * SECOidTag used internally by NSS. */
4491 static const struct {
4494 } tlsHashOIDMap
[] = {
4495 { tls_hash_md5
, SEC_OID_MD5
},
4496 { tls_hash_sha1
, SEC_OID_SHA1
},
4497 { tls_hash_sha224
, SEC_OID_SHA224
},
4498 { tls_hash_sha256
, SEC_OID_SHA256
},
4499 { tls_hash_sha384
, SEC_OID_SHA384
},
4500 { tls_hash_sha512
, SEC_OID_SHA512
}
4503 /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
4504 * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
4506 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4508 ssl3_TLSHashAlgorithmToOID(int hashFunc
)
4512 for (i
= 0; i
< PR_ARRAY_SIZE(tlsHashOIDMap
); i
++) {
4513 if (hashFunc
== tlsHashOIDMap
[i
].tlsHash
) {
4514 return tlsHashOIDMap
[i
].oid
;
4517 return SEC_OID_UNKNOWN
;
4520 /* ssl3_OIDToTLSHashAlgorithm converts an OID to a TLS hash algorithm
4521 * identifier. If the hash is not recognised, zero is returned.
4523 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4525 ssl3_OIDToTLSHashAlgorithm(SECOidTag oid
)
4529 for (i
= 0; i
< PR_ARRAY_SIZE(tlsHashOIDMap
); i
++) {
4530 if (oid
== tlsHashOIDMap
[i
].oid
) {
4531 return tlsHashOIDMap
[i
].tlsHash
;
4537 /* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm
4538 * identifier for a given KeyType. */
4540 ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType
,
4541 TLSSignatureAlgorithm
*out
)
4551 *out
= tls_sig_ecdsa
;
4554 PORT_SetError(SEC_ERROR_INVALID_KEY
);
4559 /* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature
4560 * algorithm identifier for the given certificate. */
4562 ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate
*cert
,
4563 TLSSignatureAlgorithm
*out
)
4565 SECKEYPublicKey
*key
;
4568 key
= CERT_ExtractPublicKey(cert
);
4570 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE
);
4574 keyType
= key
->keyType
;
4575 SECKEY_DestroyPublicKey(key
);
4576 return ssl3_TLSSignatureAlgorithmForKeyType(keyType
, out
);
4579 /* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature
4580 * algorithm identifier in |sigAndHash| is consistent with the public key in
4581 * |cert|. If so, SECSuccess is returned. Otherwise, PORT_SetError is called
4582 * and SECFailure is returned. */
4584 ssl3_CheckSignatureAndHashAlgorithmConsistency(
4585 const SSL3SignatureAndHashAlgorithm
*sigAndHash
, CERTCertificate
* cert
)
4588 TLSSignatureAlgorithm sigAlg
;
4590 rv
= ssl3_TLSSignatureAlgorithmForCertificate(cert
, &sigAlg
);
4591 if (rv
!= SECSuccess
) {
4594 if (sigAlg
!= sigAndHash
->sigAlg
) {
4595 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM
);
4601 /* ssl3_ConsumeSignatureAndHashAlgorithm reads a SignatureAndHashAlgorithm
4602 * structure from |b| and puts the resulting value into |out|. |b| and |length|
4603 * are updated accordingly.
4605 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4607 ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket
*ss
,
4610 SSL3SignatureAndHashAlgorithm
*out
)
4612 unsigned char bytes
[2];
4615 rv
= ssl3_ConsumeHandshake(ss
, bytes
, sizeof(bytes
), b
, length
);
4616 if (rv
!= SECSuccess
) {
4620 out
->hashAlg
= ssl3_TLSHashAlgorithmToOID(bytes
[0]);
4621 if (out
->hashAlg
== SEC_OID_UNKNOWN
) {
4622 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM
);
4626 out
->sigAlg
= bytes
[1];
4630 /**************************************************************************
4631 * end of Consume Handshake functions.
4632 **************************************************************************/
4634 /* Extract the hashes of handshake messages to this point.
4635 * Called from ssl3_SendCertificateVerify
4637 * ssl3_HandleHandshakeMessage
4639 * Caller must hold the SSL3HandshakeLock.
4640 * Caller must hold a read or write lock on the Spec R/W lock.
4641 * (There is presently no way to assert on a Read lock.)
4644 ssl3_ComputeHandshakeHashes(sslSocket
* ss
,
4645 ssl3CipherSpec
*spec
, /* uses ->master_secret */
4646 SSL3Hashes
* hashes
, /* output goes here. */
4649 SECStatus rv
= SECSuccess
;
4650 PRBool isTLS
= (PRBool
)(spec
->version
> SSL_LIBRARY_VERSION_3_0
);
4651 unsigned int outLength
;
4652 SSL3Opaque md5_inner
[MAX_MAC_LENGTH
];
4653 SSL3Opaque sha_inner
[MAX_MAC_LENGTH
];
4655 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
4656 hashes
->hashAlg
= SEC_OID_UNKNOWN
;
4658 #ifndef NO_PKCS11_BYPASS
4659 if (ss
->opt
.bypassPKCS11
&&
4660 ss
->ssl3
.hs
.hashType
== handshake_hash_single
) {
4661 /* compute them without PKCS11 */
4662 PRUint64 sha_cx
[MAX_MAC_CONTEXT_LLONGS
];
4664 if (!spec
->msItem
.data
) {
4665 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE
);
4669 ss
->ssl3
.hs
.sha_clone(sha_cx
, ss
->ssl3
.hs
.sha_cx
);
4670 ss
->ssl3
.hs
.sha_obj
->end(sha_cx
, hashes
->u
.raw
, &hashes
->len
,
4671 sizeof(hashes
->u
.raw
));
4673 PRINT_BUF(60, (NULL
, "SHA-256: result", hashes
->u
.raw
, hashes
->len
));
4675 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4676 * then this will need to be updated. */
4677 hashes
->hashAlg
= SEC_OID_SHA256
;
4679 } else if (ss
->opt
.bypassPKCS11
) {
4680 /* compute them without PKCS11 */
4681 PRUint64 md5_cx
[MAX_MAC_CONTEXT_LLONGS
];
4682 PRUint64 sha_cx
[MAX_MAC_CONTEXT_LLONGS
];
4684 #define md5cx ((MD5Context *)md5_cx)
4685 #define shacx ((SHA1Context *)sha_cx)
4687 if (!spec
->msItem
.data
) {
4688 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE
);
4692 MD5_Clone (md5cx
, (MD5Context
*)ss
->ssl3
.hs
.md5_cx
);
4693 SHA1_Clone(shacx
, (SHA1Context
*)ss
->ssl3
.hs
.sha_cx
);
4696 /* compute hashes for SSL3. */
4699 s
[0] = (unsigned char)(sender
>> 24);
4700 s
[1] = (unsigned char)(sender
>> 16);
4701 s
[2] = (unsigned char)(sender
>> 8);
4702 s
[3] = (unsigned char)sender
;
4705 MD5_Update(md5cx
, s
, 4);
4706 PRINT_BUF(95, (NULL
, "MD5 inner: sender", s
, 4));
4709 PRINT_BUF(95, (NULL
, "MD5 inner: MAC Pad 1", mac_pad_1
,
4710 mac_defs
[mac_md5
].pad_size
));
4712 MD5_Update(md5cx
, spec
->msItem
.data
, spec
->msItem
.len
);
4713 MD5_Update(md5cx
, mac_pad_1
, mac_defs
[mac_md5
].pad_size
);
4714 MD5_End(md5cx
, md5_inner
, &outLength
, MD5_LENGTH
);
4716 PRINT_BUF(95, (NULL
, "MD5 inner: result", md5_inner
, outLength
));
4719 SHA1_Update(shacx
, s
, 4);
4720 PRINT_BUF(95, (NULL
, "SHA inner: sender", s
, 4));
4723 PRINT_BUF(95, (NULL
, "SHA inner: MAC Pad 1", mac_pad_1
,
4724 mac_defs
[mac_sha
].pad_size
));
4726 SHA1_Update(shacx
, spec
->msItem
.data
, spec
->msItem
.len
);
4727 SHA1_Update(shacx
, mac_pad_1
, mac_defs
[mac_sha
].pad_size
);
4728 SHA1_End(shacx
, sha_inner
, &outLength
, SHA1_LENGTH
);
4730 PRINT_BUF(95, (NULL
, "SHA inner: result", sha_inner
, outLength
));
4731 PRINT_BUF(95, (NULL
, "MD5 outer: MAC Pad 2", mac_pad_2
,
4732 mac_defs
[mac_md5
].pad_size
));
4733 PRINT_BUF(95, (NULL
, "MD5 outer: MD5 inner", md5_inner
, MD5_LENGTH
));
4736 MD5_Update(md5cx
, spec
->msItem
.data
, spec
->msItem
.len
);
4737 MD5_Update(md5cx
, mac_pad_2
, mac_defs
[mac_md5
].pad_size
);
4738 MD5_Update(md5cx
, md5_inner
, MD5_LENGTH
);
4740 MD5_End(md5cx
, hashes
->u
.s
.md5
, &outLength
, MD5_LENGTH
);
4742 PRINT_BUF(60, (NULL
, "MD5 outer: result", hashes
->u
.s
.md5
, MD5_LENGTH
));
4745 PRINT_BUF(95, (NULL
, "SHA outer: MAC Pad 2", mac_pad_2
,
4746 mac_defs
[mac_sha
].pad_size
));
4747 PRINT_BUF(95, (NULL
, "SHA outer: SHA inner", sha_inner
, SHA1_LENGTH
));
4750 SHA1_Update(shacx
, spec
->msItem
.data
, spec
->msItem
.len
);
4751 SHA1_Update(shacx
, mac_pad_2
, mac_defs
[mac_sha
].pad_size
);
4752 SHA1_Update(shacx
, sha_inner
, SHA1_LENGTH
);
4754 SHA1_End(shacx
, hashes
->u
.s
.sha
, &outLength
, SHA1_LENGTH
);
4756 PRINT_BUF(60, (NULL
, "SHA outer: result", hashes
->u
.s
.sha
, SHA1_LENGTH
));
4758 hashes
->len
= MD5_LENGTH
+ SHA1_LENGTH
;
4764 if (ss
->ssl3
.hs
.hashType
== handshake_hash_single
) {
4765 /* compute hashes with PKCS11 */
4767 unsigned int stateLen
;
4768 unsigned char stackBuf
[1024];
4769 unsigned char *stateBuf
= NULL
;
4771 if (!spec
->master_secret
) {
4772 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE
);
4776 h
= ss
->ssl3
.hs
.sha
;
4777 stateBuf
= PK11_SaveContextAlloc(h
, stackBuf
,
4778 sizeof(stackBuf
), &stateLen
);
4779 if (stateBuf
== NULL
) {
4780 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE
);
4783 rv
|= PK11_DigestFinal(h
, hashes
->u
.raw
, &hashes
->len
,
4784 sizeof(hashes
->u
.raw
));
4785 if (rv
!= SECSuccess
) {
4786 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE
);
4790 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4791 * then this will need to be updated. */
4792 hashes
->hashAlg
= SEC_OID_SHA256
;
4797 if (PK11_RestoreContext(h
, stateBuf
, stateLen
) != SECSuccess
) {
4798 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE
);
4801 if (stateBuf
!= stackBuf
) {
4802 PORT_ZFree(stateBuf
, stateLen
);
4806 /* compute hashes with PKCS11 */
4808 PK11Context
* sha
= NULL
;
4809 unsigned char *md5StateBuf
= NULL
;
4810 unsigned char *shaStateBuf
= NULL
;
4811 unsigned int md5StateLen
, shaStateLen
;
4812 unsigned char md5StackBuf
[256];
4813 unsigned char shaStackBuf
[512];
4815 if (!spec
->master_secret
) {
4816 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE
);
4820 md5StateBuf
= PK11_SaveContextAlloc(ss
->ssl3
.hs
.md5
, md5StackBuf
,
4821 sizeof md5StackBuf
, &md5StateLen
);
4822 if (md5StateBuf
== NULL
) {
4823 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
4826 md5
= ss
->ssl3
.hs
.md5
;
4828 shaStateBuf
= PK11_SaveContextAlloc(ss
->ssl3
.hs
.sha
, shaStackBuf
,
4829 sizeof shaStackBuf
, &shaStateLen
);
4830 if (shaStateBuf
== NULL
) {
4831 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
4834 sha
= ss
->ssl3
.hs
.sha
;
4837 /* compute hashes for SSL3. */
4840 s
[0] = (unsigned char)(sender
>> 24);
4841 s
[1] = (unsigned char)(sender
>> 16);
4842 s
[2] = (unsigned char)(sender
>> 8);
4843 s
[3] = (unsigned char)sender
;
4846 rv
|= PK11_DigestOp(md5
, s
, 4);
4847 PRINT_BUF(95, (NULL
, "MD5 inner: sender", s
, 4));
4850 PRINT_BUF(95, (NULL
, "MD5 inner: MAC Pad 1", mac_pad_1
,
4851 mac_defs
[mac_md5
].pad_size
));
4853 rv
|= PK11_DigestKey(md5
,spec
->master_secret
);
4854 rv
|= PK11_DigestOp(md5
, mac_pad_1
, mac_defs
[mac_md5
].pad_size
);
4855 rv
|= PK11_DigestFinal(md5
, md5_inner
, &outLength
, MD5_LENGTH
);
4856 PORT_Assert(rv
!= SECSuccess
|| outLength
== MD5_LENGTH
);
4857 if (rv
!= SECSuccess
) {
4858 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
4863 PRINT_BUF(95, (NULL
, "MD5 inner: result", md5_inner
, outLength
));
4866 rv
|= PK11_DigestOp(sha
, s
, 4);
4867 PRINT_BUF(95, (NULL
, "SHA inner: sender", s
, 4));
4870 PRINT_BUF(95, (NULL
, "SHA inner: MAC Pad 1", mac_pad_1
,
4871 mac_defs
[mac_sha
].pad_size
));
4873 rv
|= PK11_DigestKey(sha
, spec
->master_secret
);
4874 rv
|= PK11_DigestOp(sha
, mac_pad_1
, mac_defs
[mac_sha
].pad_size
);
4875 rv
|= PK11_DigestFinal(sha
, sha_inner
, &outLength
, SHA1_LENGTH
);
4876 PORT_Assert(rv
!= SECSuccess
|| outLength
== SHA1_LENGTH
);
4877 if (rv
!= SECSuccess
) {
4878 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
4883 PRINT_BUF(95, (NULL
, "SHA inner: result", sha_inner
, outLength
));
4885 PRINT_BUF(95, (NULL
, "MD5 outer: MAC Pad 2", mac_pad_2
,
4886 mac_defs
[mac_md5
].pad_size
));
4887 PRINT_BUF(95, (NULL
, "MD5 outer: MD5 inner", md5_inner
, MD5_LENGTH
));
4889 rv
|= PK11_DigestBegin(md5
);
4890 rv
|= PK11_DigestKey(md5
, spec
->master_secret
);
4891 rv
|= PK11_DigestOp(md5
, mac_pad_2
, mac_defs
[mac_md5
].pad_size
);
4892 rv
|= PK11_DigestOp(md5
, md5_inner
, MD5_LENGTH
);
4894 rv
|= PK11_DigestFinal(md5
, hashes
->u
.s
.md5
, &outLength
, MD5_LENGTH
);
4895 PORT_Assert(rv
!= SECSuccess
|| outLength
== MD5_LENGTH
);
4896 if (rv
!= SECSuccess
) {
4897 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
4902 PRINT_BUF(60, (NULL
, "MD5 outer: result", hashes
->u
.s
.md5
, MD5_LENGTH
));
4905 PRINT_BUF(95, (NULL
, "SHA outer: MAC Pad 2", mac_pad_2
,
4906 mac_defs
[mac_sha
].pad_size
));
4907 PRINT_BUF(95, (NULL
, "SHA outer: SHA inner", sha_inner
, SHA1_LENGTH
));
4909 rv
|= PK11_DigestBegin(sha
);
4910 rv
|= PK11_DigestKey(sha
,spec
->master_secret
);
4911 rv
|= PK11_DigestOp(sha
, mac_pad_2
, mac_defs
[mac_sha
].pad_size
);
4912 rv
|= PK11_DigestOp(sha
, sha_inner
, SHA1_LENGTH
);
4914 rv
|= PK11_DigestFinal(sha
, hashes
->u
.s
.sha
, &outLength
, SHA1_LENGTH
);
4915 PORT_Assert(rv
!= SECSuccess
|| outLength
== SHA1_LENGTH
);
4916 if (rv
!= SECSuccess
) {
4917 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
4922 PRINT_BUF(60, (NULL
, "SHA outer: result", hashes
->u
.s
.sha
, SHA1_LENGTH
));
4924 hashes
->len
= MD5_LENGTH
+ SHA1_LENGTH
;
4929 if (PK11_RestoreContext(ss
->ssl3
.hs
.md5
, md5StateBuf
, md5StateLen
)
4932 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
4935 if (md5StateBuf
!= md5StackBuf
) {
4936 PORT_ZFree(md5StateBuf
, md5StateLen
);
4940 if (PK11_RestoreContext(ss
->ssl3
.hs
.sha
, shaStateBuf
, shaStateLen
)
4943 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
4946 if (shaStateBuf
!= shaStackBuf
) {
4947 PORT_ZFree(shaStateBuf
, shaStateLen
);
4955 ssl3_ComputeBackupHandshakeHashes(sslSocket
* ss
,
4956 SSL3Hashes
* hashes
) /* output goes here. */
4958 SECStatus rv
= SECSuccess
;
4960 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
4961 PORT_Assert( !ss
->sec
.isServer
);
4962 PORT_Assert( ss
->ssl3
.hs
.hashType
== handshake_hash_single
);
4964 rv
= PK11_DigestFinal(ss
->ssl3
.hs
.backupHash
, hashes
->u
.raw
, &hashes
->len
,
4965 sizeof(hashes
->u
.raw
));
4966 if (rv
!= SECSuccess
) {
4967 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
4971 hashes
->hashAlg
= SEC_OID_SHA1
;
4974 PK11_DestroyContext(ss
->ssl3
.hs
.backupHash
, PR_TRUE
);
4975 ss
->ssl3
.hs
.backupHash
= NULL
;
4980 * SSL 2 based implementations pass in the initial outbound buffer
4981 * so that the handshake hash can contain the included information.
4983 * Called from ssl2_BeginClientHandshake() in sslcon.c
4986 ssl3_StartHandshakeHash(sslSocket
*ss
, unsigned char * buf
, int length
)
4990 ssl_GetSSL3HandshakeLock(ss
); /**************************************/
4992 rv
= ssl3_InitState(ss
);
4993 if (rv
!= SECSuccess
) {
4994 goto done
; /* ssl3_InitState has set the error code. */
4996 rv
= ssl3_RestartHandshakeHashes(ss
);
4997 if (rv
!= SECSuccess
) {
5001 PORT_Memset(&ss
->ssl3
.hs
.client_random
, 0, SSL3_RANDOM_LENGTH
);
5003 &ss
->ssl3
.hs
.client_random
.rand
[SSL3_RANDOM_LENGTH
- SSL_CHALLENGE_BYTES
],
5004 &ss
->sec
.ci
.clientChallenge
,
5005 SSL_CHALLENGE_BYTES
);
5007 rv
= ssl3_UpdateHandshakeHashes(ss
, buf
, length
);
5008 /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */
5011 ssl_ReleaseSSL3HandshakeLock(ss
); /**************************************/
5015 /**************************************************************************
5016 * end of Handshake Hash functions.
5017 * Begin Send and Handle functions for handshakes.
5018 **************************************************************************/
5020 /* Called from ssl3_HandleHelloRequest(),
5021 * ssl3_RedoHandshake()
5022 * ssl2_BeginClientHandshake (when resuming ssl3 session)
5023 * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
5026 ssl3_SendClientHello(sslSocket
*ss
, PRBool resending
)
5029 ssl3CipherSpec
* cwSpec
;
5034 int actual_count
= 0;
5035 PRBool isTLS
= PR_FALSE
;
5036 PRBool requestingResume
= PR_FALSE
, fallbackSCSV
= PR_FALSE
;
5037 PRInt32 total_exten_len
= 0;
5038 unsigned paddingExtensionLen
;
5039 unsigned numCompressionMethods
;
5042 SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(),
5045 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
5046 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
5048 rv
= ssl3_InitState(ss
);
5049 if (rv
!= SECSuccess
) {
5050 return rv
; /* ssl3_InitState has set the error code. */
5052 ss
->ssl3
.hs
.sendingSCSV
= PR_FALSE
; /* Must be reset every handshake */
5053 PORT_Assert(IS_DTLS(ss
) || !resending
);
5055 SECITEM_FreeItem(&ss
->ssl3
.hs
.newSessionTicket
.ticket
, PR_FALSE
);
5056 ss
->ssl3
.hs
.receivedNewSessionTicket
= PR_FALSE
;
5058 /* We might be starting a session renegotiation in which case we should
5059 * clear previous state.
5061 PORT_Memset(&ss
->xtnData
, 0, sizeof(TLSExtensionData
));
5063 rv
= ssl3_RestartHandshakeHashes(ss
);
5064 if (rv
!= SECSuccess
) {
5069 * During a renegotiation, ss->clientHelloVersion will be used again to
5070 * work around a Windows SChannel bug. Ensure that it is still enabled.
5072 if (ss
->firstHsDone
) {
5073 if (SSL3_ALL_VERSIONS_DISABLED(&ss
->vrange
)) {
5074 PORT_SetError(SSL_ERROR_SSL_DISABLED
);
5078 if (ss
->clientHelloVersion
< ss
->vrange
.min
||
5079 ss
->clientHelloVersion
> ss
->vrange
.max
) {
5080 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP
);
5085 /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
5086 * handles expired entries and other details.
5087 * XXX If we've been called from ssl2_BeginClientHandshake, then
5088 * this lookup is duplicative and wasteful.
5090 sid
= (ss
->opt
.noCache
) ? NULL
5091 : ssl_LookupSID(&ss
->sec
.ci
.peer
, ss
->sec
.ci
.port
, ss
->peerID
, ss
->url
);
5093 /* We can't resume based on a different token. If the sid exists,
5094 * make sure the token that holds the master secret still exists ...
5095 * If we previously did client-auth, make sure that the token that holds
5096 * the private key still exists, is logged in, hasn't been removed, etc.
5099 PRBool sidOK
= PR_TRUE
;
5100 if (sid
->u
.ssl3
.keys
.msIsWrapped
) {
5101 /* Session key was wrapped, which means it was using PKCS11, */
5102 PK11SlotInfo
*slot
= NULL
;
5103 if (sid
->u
.ssl3
.masterValid
&& !ss
->opt
.bypassPKCS11
) {
5104 slot
= SECMOD_LookupSlot(sid
->u
.ssl3
.masterModuleID
,
5105 sid
->u
.ssl3
.masterSlotID
);
5110 PK11SymKey
*wrapKey
= NULL
;
5111 if (!PK11_IsPresent(slot
) ||
5112 ((wrapKey
= PK11_GetWrapKey(slot
,
5113 sid
->u
.ssl3
.masterWrapIndex
,
5114 sid
->u
.ssl3
.masterWrapMech
,
5115 sid
->u
.ssl3
.masterWrapSeries
,
5116 ss
->pkcs11PinArg
)) == NULL
) ) {
5119 if (wrapKey
) PK11_FreeSymKey(wrapKey
);
5120 PK11_FreeSlot(slot
);
5124 /* If we previously did client-auth, make sure that the token that
5125 ** holds the private key still exists, is logged in, hasn't been
5128 if (sidOK
&& !ssl3_ClientAuthTokenPresent(sid
)) {
5133 /* Set ss->version based on the session cache */
5134 if (ss
->firstHsDone
) {
5136 * Windows SChannel compares the client_version inside the RSA
5137 * EncryptedPreMasterSecret of a renegotiation with the
5138 * client_version of the initial ClientHello rather than the
5139 * ClientHello in the renegotiation. To work around this bug, we
5140 * continue to use the client_version used in the initial
5141 * ClientHello when renegotiating.
5143 * The client_version of the initial ClientHello is still
5144 * available in ss->clientHelloVersion. Ensure that
5145 * sid->version is bounded within
5146 * [ss->vrange.min, ss->clientHelloVersion], otherwise we
5149 if (sid
->version
>= ss
->vrange
.min
&&
5150 sid
->version
<= ss
->clientHelloVersion
) {
5151 ss
->version
= ss
->clientHelloVersion
;
5157 * Check sid->version is OK first.
5158 * Previously, we would cap the version based on sid->version,
5159 * but that prevents negotiation of a higher version if the
5160 * previous session was reduced (e.g., with version fallback)
5162 if (sid
->version
< ss
->vrange
.min
||
5163 sid
->version
> ss
->vrange
.max
) {
5166 rv
= ssl3_NegotiateVersion(ss
, SSL_LIBRARY_VERSION_MAX_SUPPORTED
,
5168 if (rv
!= SECSuccess
) {
5169 return rv
; /* error code was set */
5176 SSL_AtomicIncrementLong(& ssl3stats
.sch_sid_cache_not_ok
);
5177 if (ss
->sec
.uncache
)
5178 (*ss
->sec
.uncache
)(sid
);
5185 requestingResume
= PR_TRUE
;
5186 SSL_AtomicIncrementLong(& ssl3stats
.sch_sid_cache_hits
);
5188 PRINT_BUF(4, (ss
, "client, found session-id:", sid
->u
.ssl3
.sessionID
,
5189 sid
->u
.ssl3
.sessionIDLength
));
5191 ss
->ssl3
.policy
= sid
->u
.ssl3
.policy
;
5193 SSL_AtomicIncrementLong(& ssl3stats
.sch_sid_cache_misses
);
5196 * Windows SChannel compares the client_version inside the RSA
5197 * EncryptedPreMasterSecret of a renegotiation with the
5198 * client_version of the initial ClientHello rather than the
5199 * ClientHello in the renegotiation. To work around this bug, we
5200 * continue to use the client_version used in the initial
5201 * ClientHello when renegotiating.
5203 if (ss
->firstHsDone
) {
5204 ss
->version
= ss
->clientHelloVersion
;
5206 rv
= ssl3_NegotiateVersion(ss
, SSL_LIBRARY_VERSION_MAX_SUPPORTED
,
5208 if (rv
!= SECSuccess
)
5209 return rv
; /* error code was set */
5212 sid
= ssl3_NewSessionID(ss
, PR_FALSE
);
5214 return SECFailure
; /* memory error is set */
5218 isTLS
= (ss
->version
> SSL_LIBRARY_VERSION_3_0
);
5219 ssl_GetSpecWriteLock(ss
);
5220 cwSpec
= ss
->ssl3
.cwSpec
;
5221 if (cwSpec
->mac_def
->mac
== mac_null
) {
5222 /* SSL records are not being MACed. */
5223 cwSpec
->version
= ss
->version
;
5225 ssl_ReleaseSpecWriteLock(ss
);
5227 if (ss
->sec
.ci
.sid
!= NULL
) {
5228 ssl_FreeSID(ss
->sec
.ci
.sid
); /* decrement ref count, free if zero */
5230 ss
->sec
.ci
.sid
= sid
;
5232 ss
->sec
.send
= ssl3_SendApplicationData
;
5234 /* shouldn't get here if SSL3 is disabled, but ... */
5235 if (SSL3_ALL_VERSIONS_DISABLED(&ss
->vrange
)) {
5236 PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
5237 PORT_SetError(SSL_ERROR_SSL_DISABLED
);
5241 /* how many suites does our PKCS11 support (regardless of policy)? */
5242 num_suites
= ssl3_config_match_init(ss
);
5244 return SECFailure
; /* ssl3_config_match_init has set error code. */
5246 /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV,
5247 * only if TLS is disabled.
5249 if (!ss
->firstHsDone
&& !isTLS
) {
5250 /* Must set this before calling Hello Extension Senders,
5251 * to suppress sending of empty RI extension.
5253 ss
->ssl3
.hs
.sendingSCSV
= PR_TRUE
;
5256 /* When we attempt session resumption (only), we must lock the sid to
5257 * prevent races with other resumption connections that receive a
5258 * NewSessionTicket that will cause the ticket in the sid to be replaced.
5259 * Once we've copied the session ticket into our ClientHello message, it
5260 * is OK for the ticket to change, so we just need to make sure we hold
5261 * the lock across the calls to ssl3_CallHelloExtensionSenders.
5263 if (sid
->u
.ssl3
.lock
) {
5264 NSSRWLock_LockRead(sid
->u
.ssl3
.lock
);
5267 if (isTLS
|| (ss
->firstHsDone
&& ss
->peerRequestedProtection
)) {
5268 PRUint32 maxBytes
= 65535; /* 2^16 - 1 */
5271 extLen
= ssl3_CallHelloExtensionSenders(ss
, PR_FALSE
, maxBytes
, NULL
);
5273 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5276 total_exten_len
+= extLen
;
5278 if (total_exten_len
> 0)
5279 total_exten_len
+= 2;
5282 #ifndef NSS_DISABLE_ECC
5283 if (!total_exten_len
|| !isTLS
) {
5284 /* not sending the elliptic_curves and ec_point_formats extensions */
5285 ssl3_DisableECCSuites(ss
, NULL
); /* disable all ECC suites */
5287 #endif /* NSS_DISABLE_ECC */
5290 ssl3_DisableNonDTLSSuites(ss
);
5293 if (!ssl3_HasGCMSupport()) {
5294 ssl3_DisableGCMSuites(ss
);
5297 /* how many suites are permitted by policy and user preference? */
5298 num_suites
= count_cipher_suites(ss
, ss
->ssl3
.policy
, PR_TRUE
);
5300 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5301 return SECFailure
; /* count_cipher_suites has set error code. */
5304 fallbackSCSV
= ss
->opt
.enableFallbackSCSV
&& (!requestingResume
||
5305 ss
->version
< sid
->version
);
5306 /* make room for SCSV */
5307 if (ss
->ssl3
.hs
.sendingSCSV
) {
5314 /* count compression methods */
5315 numCompressionMethods
= 0;
5316 for (i
= 0; i
< compressionMethodsCount
; i
++) {
5317 if (compressionEnabled(ss
, compressions
[i
]))
5318 numCompressionMethods
++;
5321 length
= sizeof(SSL3ProtocolVersion
) + SSL3_RANDOM_LENGTH
+
5322 1 + ((sid
== NULL
) ? 0 : sid
->u
.ssl3
.sessionIDLength
) +
5323 2 + num_suites
*sizeof(ssl3CipherSuite
) +
5324 1 + numCompressionMethods
+ total_exten_len
;
5326 length
+= 1 + ss
->ssl3
.hs
.cookieLen
;
5329 /* A padding extension may be included to ensure that the record containing
5330 * the ClientHello doesn't have a length between 256 and 511 bytes
5331 * (inclusive). Initial, ClientHello records with such lengths trigger bugs
5334 * This is not done for DTLS nor for renegotiation. */
5335 if (!IS_DTLS(ss
) && isTLS
&& !ss
->firstHsDone
) {
5336 paddingExtensionLen
= ssl3_CalculatePaddingExtensionLength(length
);
5337 total_exten_len
+= paddingExtensionLen
;
5338 length
+= paddingExtensionLen
;
5340 paddingExtensionLen
= 0;
5343 rv
= ssl3_AppendHandshakeHeader(ss
, client_hello
, length
);
5344 if (rv
!= SECSuccess
) {
5345 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5346 return rv
; /* err set by ssl3_AppendHandshake* */
5349 if (ss
->firstHsDone
) {
5350 /* The client hello version must stay unchanged to work around
5351 * the Windows SChannel bug described above. */
5352 PORT_Assert(ss
->version
== ss
->clientHelloVersion
);
5354 ss
->clientHelloVersion
= ss
->version
;
5358 version
= dtls_TLSVersionToDTLSVersion(ss
->clientHelloVersion
);
5359 rv
= ssl3_AppendHandshakeNumber(ss
, version
, 2);
5361 rv
= ssl3_AppendHandshakeNumber(ss
, ss
->clientHelloVersion
, 2);
5363 if (rv
!= SECSuccess
) {
5364 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5365 return rv
; /* err set by ssl3_AppendHandshake* */
5368 if (!resending
) { /* Don't re-generate if we are in DTLS re-sending mode */
5369 rv
= ssl3_GetNewRandom(&ss
->ssl3
.hs
.client_random
);
5370 if (rv
!= SECSuccess
) {
5371 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5372 return rv
; /* err set by GetNewRandom. */
5375 rv
= ssl3_AppendHandshake(ss
, &ss
->ssl3
.hs
.client_random
,
5376 SSL3_RANDOM_LENGTH
);
5377 if (rv
!= SECSuccess
) {
5378 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5379 return rv
; /* err set by ssl3_AppendHandshake* */
5383 rv
= ssl3_AppendHandshakeVariable(
5384 ss
, sid
->u
.ssl3
.sessionID
, sid
->u
.ssl3
.sessionIDLength
, 1);
5386 rv
= ssl3_AppendHandshakeNumber(ss
, 0, 1);
5387 if (rv
!= SECSuccess
) {
5388 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5389 return rv
; /* err set by ssl3_AppendHandshake* */
5393 rv
= ssl3_AppendHandshakeVariable(
5394 ss
, ss
->ssl3
.hs
.cookie
, ss
->ssl3
.hs
.cookieLen
, 1);
5395 if (rv
!= SECSuccess
) {
5396 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5397 return rv
; /* err set by ssl3_AppendHandshake* */
5401 rv
= ssl3_AppendHandshakeNumber(ss
, num_suites
*sizeof(ssl3CipherSuite
), 2);
5402 if (rv
!= SECSuccess
) {
5403 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5404 return rv
; /* err set by ssl3_AppendHandshake* */
5407 if (ss
->ssl3
.hs
.sendingSCSV
) {
5408 /* Add the actual SCSV */
5409 rv
= ssl3_AppendHandshakeNumber(ss
, TLS_EMPTY_RENEGOTIATION_INFO_SCSV
,
5410 sizeof(ssl3CipherSuite
));
5411 if (rv
!= SECSuccess
) {
5412 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5413 return rv
; /* err set by ssl3_AppendHandshake* */
5418 rv
= ssl3_AppendHandshakeNumber(ss
, TLS_FALLBACK_SCSV
,
5419 sizeof(ssl3CipherSuite
));
5420 if (rv
!= SECSuccess
) {
5421 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5422 return rv
; /* err set by ssl3_AppendHandshake* */
5426 for (i
= 0; i
< ssl_V3_SUITES_IMPLEMENTED
; i
++) {
5427 ssl3CipherSuiteCfg
*suite
= &ss
->cipherSuites
[i
];
5428 if (config_match(suite
, ss
->ssl3
.policy
, PR_TRUE
, &ss
->vrange
)) {
5430 if (actual_count
> num_suites
) {
5431 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5432 /* set error card removal/insertion error */
5433 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL
);
5436 rv
= ssl3_AppendHandshakeNumber(ss
, suite
->cipher_suite
,
5437 sizeof(ssl3CipherSuite
));
5438 if (rv
!= SECSuccess
) {
5439 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5440 return rv
; /* err set by ssl3_AppendHandshake* */
5445 /* if cards were removed or inserted between count_cipher_suites and
5446 * generating our list, detect the error here rather than send it off to
5448 if (actual_count
!= num_suites
) {
5449 /* Card removal/insertion error */
5450 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5451 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL
);
5455 rv
= ssl3_AppendHandshakeNumber(ss
, numCompressionMethods
, 1);
5456 if (rv
!= SECSuccess
) {
5457 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5458 return rv
; /* err set by ssl3_AppendHandshake* */
5460 for (i
= 0; i
< compressionMethodsCount
; i
++) {
5461 if (!compressionEnabled(ss
, compressions
[i
]))
5463 rv
= ssl3_AppendHandshakeNumber(ss
, compressions
[i
], 1);
5464 if (rv
!= SECSuccess
) {
5465 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5466 return rv
; /* err set by ssl3_AppendHandshake* */
5470 if (total_exten_len
) {
5471 PRUint32 maxBytes
= total_exten_len
- 2;
5474 rv
= ssl3_AppendHandshakeNumber(ss
, maxBytes
, 2);
5475 if (rv
!= SECSuccess
) {
5476 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5477 return rv
; /* err set by AppendHandshake. */
5480 extLen
= ssl3_CallHelloExtensionSenders(ss
, PR_TRUE
, maxBytes
, NULL
);
5482 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5487 extLen
= ssl3_AppendPaddingExtension(ss
, paddingExtensionLen
, maxBytes
);
5489 if (sid
->u
.ssl3
.lock
) { NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
); }
5494 PORT_Assert(!maxBytes
);
5497 if (sid
->u
.ssl3
.lock
) {
5498 NSSRWLock_UnlockRead(sid
->u
.ssl3
.lock
);
5501 if (ss
->xtnData
.sentSessionTicketInClientHello
) {
5502 SSL_AtomicIncrementLong(&ssl3stats
.sch_sid_stateless_resumes
);
5505 if (ss
->ssl3
.hs
.sendingSCSV
) {
5506 /* Since we sent the SCSV, pretend we sent empty RI extension. */
5507 TLSExtensionData
*xtnData
= &ss
->xtnData
;
5508 xtnData
->advertised
[xtnData
->numAdvertised
++] =
5509 ssl_renegotiation_info_xtn
;
5513 if (!ss
->firstHsDone
&& !IS_DTLS(ss
)) {
5514 flags
|= ssl_SEND_FLAG_CAP_RECORD_VERSION
;
5516 rv
= ssl3_FlushHandshake(ss
, flags
);
5517 if (rv
!= SECSuccess
) {
5518 return rv
; /* error code set by ssl3_FlushHandshake */
5521 ss
->ssl3
.hs
.ws
= wait_server_hello
;
5526 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5527 * ssl3 Hello Request.
5528 * Caller must hold Handshake and RecvBuf locks.
5531 ssl3_HandleHelloRequest(sslSocket
*ss
)
5533 sslSessionID
*sid
= ss
->sec
.ci
.sid
;
5536 SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
5537 SSL_GETPID(), ss
->fd
));
5539 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
5540 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
5542 if (ss
->ssl3
.hs
.ws
== wait_server_hello
)
5544 if (ss
->ssl3
.hs
.ws
!= idle_handshake
|| ss
->sec
.isServer
) {
5545 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
5546 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST
);
5549 if (ss
->opt
.enableRenegotiation
== SSL_RENEGOTIATE_NEVER
) {
5550 (void)SSL3_SendAlert(ss
, alert_warning
, no_renegotiation
);
5551 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
);
5556 if (ss
->sec
.uncache
)
5557 ss
->sec
.uncache(sid
);
5559 ss
->sec
.ci
.sid
= NULL
;
5563 dtls_RehandshakeCleanup(ss
);
5566 ssl_GetXmitBufLock(ss
);
5567 rv
= ssl3_SendClientHello(ss
, PR_FALSE
);
5568 ssl_ReleaseXmitBufLock(ss
);
5573 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff
5575 static const CK_MECHANISM_TYPE wrapMechanismList
[SSL_NUM_WRAP_MECHS
] = {
5591 UNKNOWN_WRAP_MECHANISM
5595 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech
)
5597 const CK_MECHANISM_TYPE
*pMech
= wrapMechanismList
;
5599 while (mech
!= *pMech
&& *pMech
!= UNKNOWN_WRAP_MECHANISM
) {
5602 return (*pMech
== UNKNOWN_WRAP_MECHANISM
) ? -1
5603 : (pMech
- wrapMechanismList
);
5607 ssl_UnwrapSymWrappingKey(
5608 SSLWrappedSymWrappingKey
*pWswk
,
5609 SECKEYPrivateKey
* svrPrivKey
,
5610 SSL3KEAType exchKeyType
,
5611 CK_MECHANISM_TYPE masterWrapMech
,
5614 PK11SymKey
* unwrappedWrappingKey
= NULL
;
5616 #ifndef NSS_DISABLE_ECC
5618 SECKEYPublicKey pubWrapKey
;
5619 ECCWrappedKeyInfo
*ecWrapped
;
5620 #endif /* NSS_DISABLE_ECC */
5622 /* found the wrapping key on disk. */
5623 PORT_Assert(pWswk
->symWrapMechanism
== masterWrapMech
);
5624 PORT_Assert(pWswk
->exchKeyType
== exchKeyType
);
5625 if (pWswk
->symWrapMechanism
!= masterWrapMech
||
5626 pWswk
->exchKeyType
!= exchKeyType
) {
5629 wrappedKey
.type
= siBuffer
;
5630 wrappedKey
.data
= pWswk
->wrappedSymmetricWrappingkey
;
5631 wrappedKey
.len
= pWswk
->wrappedSymKeyLen
;
5632 PORT_Assert(wrappedKey
.len
<= sizeof pWswk
->wrappedSymmetricWrappingkey
);
5634 switch (exchKeyType
) {
5637 unwrappedWrappingKey
=
5638 PK11_PubUnwrapSymKey(svrPrivKey
, &wrappedKey
,
5639 masterWrapMech
, CKA_UNWRAP
, 0);
5642 #ifndef NSS_DISABLE_ECC
5645 * For kt_ecdh, we first create an EC public key based on
5646 * data stored with the wrappedSymmetricWrappingkey. Next,
5647 * we do an ECDH computation involving this public key and
5648 * the SSL server's (long-term) EC private key. The resulting
5649 * shared secret is treated the same way as Fortezza's Ks, i.e.,
5650 * it is used to recover the symmetric wrapping key.
5652 * The data in wrappedSymmetricWrappingkey is laid out as defined
5653 * in the ECCWrappedKeyInfo structure.
5655 ecWrapped
= (ECCWrappedKeyInfo
*) pWswk
->wrappedSymmetricWrappingkey
;
5657 PORT_Assert(ecWrapped
->encodedParamLen
+ ecWrapped
->pubValueLen
+
5658 ecWrapped
->wrappedKeyLen
<= MAX_EC_WRAPPED_KEY_BUFLEN
);
5660 if (ecWrapped
->encodedParamLen
+ ecWrapped
->pubValueLen
+
5661 ecWrapped
->wrappedKeyLen
> MAX_EC_WRAPPED_KEY_BUFLEN
) {
5662 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
5666 pubWrapKey
.keyType
= ecKey
;
5667 pubWrapKey
.u
.ec
.size
= ecWrapped
->size
;
5668 pubWrapKey
.u
.ec
.DEREncodedParams
.len
= ecWrapped
->encodedParamLen
;
5669 pubWrapKey
.u
.ec
.DEREncodedParams
.data
= ecWrapped
->var
;
5670 pubWrapKey
.u
.ec
.publicValue
.len
= ecWrapped
->pubValueLen
;
5671 pubWrapKey
.u
.ec
.publicValue
.data
= ecWrapped
->var
+
5672 ecWrapped
->encodedParamLen
;
5674 wrappedKey
.len
= ecWrapped
->wrappedKeyLen
;
5675 wrappedKey
.data
= ecWrapped
->var
+ ecWrapped
->encodedParamLen
+
5676 ecWrapped
->pubValueLen
;
5678 /* Derive Ks using ECDH */
5679 Ks
= PK11_PubDeriveWithKDF(svrPrivKey
, &pubWrapKey
, PR_FALSE
, NULL
,
5680 NULL
, CKM_ECDH1_DERIVE
, masterWrapMech
,
5681 CKA_DERIVE
, 0, CKD_NULL
, NULL
, NULL
);
5686 /* Use Ks to unwrap the wrapping key */
5687 unwrappedWrappingKey
= PK11_UnwrapSymKey(Ks
, masterWrapMech
, NULL
,
5688 &wrappedKey
, masterWrapMech
,
5690 PK11_FreeSymKey(Ks
);
5701 return unwrappedWrappingKey
;
5704 /* Each process sharing the server session ID cache has its own array of
5705 * SymKey pointers for the symmetric wrapping keys that are used to wrap
5706 * the master secrets. There is one key for each KEA type. These Symkeys
5707 * correspond to the wrapped SymKeys kept in the server session cache.
5711 PK11SymKey
* symWrapKey
[kt_kea_size
];
5714 static PZLock
* symWrapKeysLock
= NULL
;
5715 static ssl3SymWrapKey symWrapKeys
[SSL_NUM_WRAP_MECHS
];
5717 SECStatus
ssl_FreeSymWrapKeysLock(void)
5719 if (symWrapKeysLock
) {
5720 PZ_DestroyLock(symWrapKeysLock
);
5721 symWrapKeysLock
= NULL
;
5724 PORT_SetError(SEC_ERROR_NOT_INITIALIZED
);
5729 SSL3_ShutdownServerCache(void)
5733 if (!symWrapKeysLock
)
5734 return SECSuccess
; /* lock was never initialized */
5735 PZ_Lock(symWrapKeysLock
);
5736 /* get rid of all symWrapKeys */
5737 for (i
= 0; i
< SSL_NUM_WRAP_MECHS
; ++i
) {
5738 for (j
= 0; j
< kt_kea_size
; ++j
) {
5739 PK11SymKey
** pSymWrapKey
;
5740 pSymWrapKey
= &symWrapKeys
[i
].symWrapKey
[j
];
5742 PK11_FreeSymKey(*pSymWrapKey
);
5743 *pSymWrapKey
= NULL
;
5748 PZ_Unlock(symWrapKeysLock
);
5752 SECStatus
ssl_InitSymWrapKeysLock(void)
5754 symWrapKeysLock
= PZ_NewLock(nssILockOther
);
5755 return symWrapKeysLock
? SECSuccess
: SECFailure
;
5758 /* Try to get wrapping key for mechanism from in-memory array.
5759 * If that fails, look for one on disk.
5760 * If that fails, generate a new one, put the new one on disk,
5761 * Put the new key in the in-memory array.
5764 getWrappingKey( sslSocket
* ss
,
5765 PK11SlotInfo
* masterSecretSlot
,
5766 SSL3KEAType exchKeyType
,
5767 CK_MECHANISM_TYPE masterWrapMech
,
5770 SECKEYPrivateKey
* svrPrivKey
;
5771 SECKEYPublicKey
* svrPubKey
= NULL
;
5772 PK11SymKey
* unwrappedWrappingKey
= NULL
;
5773 PK11SymKey
** pSymWrapKey
;
5774 CK_MECHANISM_TYPE asymWrapMechanism
= CKM_INVALID_MECHANISM
;
5776 int symWrapMechIndex
;
5779 SSLWrappedSymWrappingKey wswk
;
5780 #ifndef NSS_DISABLE_ECC
5781 PK11SymKey
* Ks
= NULL
;
5782 SECKEYPublicKey
*pubWrapKey
= NULL
;
5783 SECKEYPrivateKey
*privWrapKey
= NULL
;
5784 ECCWrappedKeyInfo
*ecWrapped
;
5785 #endif /* NSS_DISABLE_ECC */
5787 svrPrivKey
= ss
->serverCerts
[exchKeyType
].SERVERKEY
;
5788 PORT_Assert(svrPrivKey
!= NULL
);
5790 return NULL
; /* why are we here?!? */
5793 symWrapMechIndex
= ssl_FindIndexByWrapMechanism(masterWrapMech
);
5794 PORT_Assert(symWrapMechIndex
>= 0);
5795 if (symWrapMechIndex
< 0)
5796 return NULL
; /* invalid masterWrapMech. */
5798 pSymWrapKey
= &symWrapKeys
[symWrapMechIndex
].symWrapKey
[exchKeyType
];
5800 ssl_InitSessionCacheLocks();
5802 PZ_Lock(symWrapKeysLock
);
5804 unwrappedWrappingKey
= *pSymWrapKey
;
5805 if (unwrappedWrappingKey
!= NULL
) {
5806 if (PK11_VerifyKeyOK(unwrappedWrappingKey
)) {
5807 unwrappedWrappingKey
= PK11_ReferenceSymKey(unwrappedWrappingKey
);
5810 /* slot series has changed, so this key is no good any more. */
5811 PK11_FreeSymKey(unwrappedWrappingKey
);
5812 *pSymWrapKey
= unwrappedWrappingKey
= NULL
;
5815 /* Try to get wrapped SymWrapping key out of the (disk) cache. */
5816 /* Following call fills in wswk on success. */
5817 if (ssl_GetWrappingKey(symWrapMechIndex
, exchKeyType
, &wswk
)) {
5818 /* found the wrapped sym wrapping key on disk. */
5819 unwrappedWrappingKey
=
5820 ssl_UnwrapSymWrappingKey(&wswk
, svrPrivKey
, exchKeyType
,
5821 masterWrapMech
, pwArg
);
5822 if (unwrappedWrappingKey
) {
5827 if (!masterSecretSlot
) /* caller doesn't want to create a new one. */
5830 length
= PK11_GetBestKeyLength(masterSecretSlot
, masterWrapMech
);
5831 /* Zero length means fixed key length algorithm, or error.
5834 unwrappedWrappingKey
= PK11_KeyGen(masterSecretSlot
, masterWrapMech
, NULL
,
5836 if (!unwrappedWrappingKey
) {
5840 /* Prepare the buffer to receive the wrappedWrappingKey,
5841 * the symmetric wrapping key wrapped using the server's pub key.
5843 PORT_Memset(&wswk
, 0, sizeof wswk
); /* eliminate UMRs. */
5845 if (ss
->serverCerts
[exchKeyType
].serverKeyPair
) {
5846 svrPubKey
= ss
->serverCerts
[exchKeyType
].serverKeyPair
->pubKey
;
5848 if (svrPubKey
== NULL
) {
5849 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
5852 wrappedKey
.type
= siBuffer
;
5853 wrappedKey
.len
= SECKEY_PublicKeyStrength(svrPubKey
);
5854 wrappedKey
.data
= wswk
.wrappedSymmetricWrappingkey
;
5856 PORT_Assert(wrappedKey
.len
<= sizeof wswk
.wrappedSymmetricWrappingkey
);
5857 if (wrappedKey
.len
> sizeof wswk
.wrappedSymmetricWrappingkey
)
5860 /* wrap symmetric wrapping key in server's public key. */
5861 switch (exchKeyType
) {
5863 asymWrapMechanism
= CKM_RSA_PKCS
;
5864 rv
= PK11_PubWrapSymKey(asymWrapMechanism
, svrPubKey
,
5865 unwrappedWrappingKey
, &wrappedKey
);
5868 #ifndef NSS_DISABLE_ECC
5871 * We generate an ephemeral EC key pair. Perform an ECDH
5872 * computation involving this ephemeral EC public key and
5873 * the SSL server's (long-term) EC private key. The resulting
5874 * shared secret is treated in the same way as Fortezza's Ks,
5875 * i.e., it is used to wrap the wrapping key. To facilitate
5876 * unwrapping in ssl_UnwrapWrappingKey, we also store all
5877 * relevant info about the ephemeral EC public key in
5878 * wswk.wrappedSymmetricWrappingkey and lay it out as
5879 * described in the ECCWrappedKeyInfo structure.
5881 PORT_Assert(svrPubKey
->keyType
== ecKey
);
5882 if (svrPubKey
->keyType
!= ecKey
) {
5883 /* something is wrong in sslsecur.c if this isn't an ecKey */
5884 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
5889 privWrapKey
= SECKEY_CreateECPrivateKey(
5890 &svrPubKey
->u
.ec
.DEREncodedParams
, &pubWrapKey
, NULL
);
5891 if ((privWrapKey
== NULL
) || (pubWrapKey
== NULL
)) {
5896 /* Set the key size in bits */
5897 if (pubWrapKey
->u
.ec
.size
== 0) {
5898 pubWrapKey
->u
.ec
.size
= SECKEY_PublicKeyStrengthInBits(svrPubKey
);
5901 PORT_Assert(pubWrapKey
->u
.ec
.DEREncodedParams
.len
+
5902 pubWrapKey
->u
.ec
.publicValue
.len
< MAX_EC_WRAPPED_KEY_BUFLEN
);
5903 if (pubWrapKey
->u
.ec
.DEREncodedParams
.len
+
5904 pubWrapKey
->u
.ec
.publicValue
.len
>= MAX_EC_WRAPPED_KEY_BUFLEN
) {
5905 PORT_SetError(SEC_ERROR_INVALID_KEY
);
5910 /* Derive Ks using ECDH */
5911 Ks
= PK11_PubDeriveWithKDF(svrPrivKey
, pubWrapKey
, PR_FALSE
, NULL
,
5912 NULL
, CKM_ECDH1_DERIVE
, masterWrapMech
,
5913 CKA_DERIVE
, 0, CKD_NULL
, NULL
, NULL
);
5919 ecWrapped
= (ECCWrappedKeyInfo
*) (wswk
.wrappedSymmetricWrappingkey
);
5920 ecWrapped
->size
= pubWrapKey
->u
.ec
.size
;
5921 ecWrapped
->encodedParamLen
= pubWrapKey
->u
.ec
.DEREncodedParams
.len
;
5922 PORT_Memcpy(ecWrapped
->var
, pubWrapKey
->u
.ec
.DEREncodedParams
.data
,
5923 pubWrapKey
->u
.ec
.DEREncodedParams
.len
);
5925 ecWrapped
->pubValueLen
= pubWrapKey
->u
.ec
.publicValue
.len
;
5926 PORT_Memcpy(ecWrapped
->var
+ ecWrapped
->encodedParamLen
,
5927 pubWrapKey
->u
.ec
.publicValue
.data
,
5928 pubWrapKey
->u
.ec
.publicValue
.len
);
5930 wrappedKey
.len
= MAX_EC_WRAPPED_KEY_BUFLEN
-
5931 (ecWrapped
->encodedParamLen
+ ecWrapped
->pubValueLen
);
5932 wrappedKey
.data
= ecWrapped
->var
+ ecWrapped
->encodedParamLen
+
5933 ecWrapped
->pubValueLen
;
5935 /* wrap symmetricWrapping key with the local Ks */
5936 rv
= PK11_WrapSymKey(masterWrapMech
, NULL
, Ks
,
5937 unwrappedWrappingKey
, &wrappedKey
);
5939 if (rv
!= SECSuccess
) {
5943 /* Write down the length of wrapped key in the buffer
5944 * wswk.wrappedSymmetricWrappingkey at the appropriate offset
5946 ecWrapped
->wrappedKeyLen
= wrappedKey
.len
;
5949 if (privWrapKey
) SECKEY_DestroyPrivateKey(privWrapKey
);
5950 if (pubWrapKey
) SECKEY_DestroyPublicKey(pubWrapKey
);
5951 if (Ks
) PK11_FreeSymKey(Ks
);
5952 asymWrapMechanism
= masterWrapMech
;
5954 #endif /* NSS_DISABLE_ECC */
5961 if (rv
!= SECSuccess
) {
5962 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
5966 PORT_Assert(asymWrapMechanism
!= CKM_INVALID_MECHANISM
);
5968 wswk
.symWrapMechanism
= masterWrapMech
;
5969 wswk
.symWrapMechIndex
= symWrapMechIndex
;
5970 wswk
.asymWrapMechanism
= asymWrapMechanism
;
5971 wswk
.exchKeyType
= exchKeyType
;
5972 wswk
.wrappedSymKeyLen
= wrappedKey
.len
;
5974 /* put it on disk. */
5975 /* If the wrapping key for this KEA type has already been set,
5976 * then abandon the value we just computed and
5977 * use the one we got from the disk.
5979 if (ssl_SetWrappingKey(&wswk
)) {
5980 /* somebody beat us to it. The original contents of our wswk
5981 * has been replaced with the content on disk. Now, discard
5982 * the key we just created and unwrap this new one.
5984 PK11_FreeSymKey(unwrappedWrappingKey
);
5986 unwrappedWrappingKey
=
5987 ssl_UnwrapSymWrappingKey(&wswk
, svrPrivKey
, exchKeyType
,
5988 masterWrapMech
, pwArg
);
5992 if (unwrappedWrappingKey
) {
5993 *pSymWrapKey
= PK11_ReferenceSymKey(unwrappedWrappingKey
);
5998 PZ_Unlock(symWrapKeysLock
);
5999 return unwrappedWrappingKey
;
6002 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
6003 * bytes to |out|. */
6005 hexEncode(char *out
, const unsigned char *in
, unsigned int length
)
6007 static const char hextable
[] = "0123456789abcdef";
6010 for (i
= 0; i
< length
; i
++) {
6011 *(out
++) = hextable
[in
[i
] >> 4];
6012 *(out
++) = hextable
[in
[i
] & 15];
6016 /* Called from ssl3_SendClientKeyExchange(). */
6017 /* Presently, this always uses PKCS11. There is no bypass for this. */
6019 sendRSAClientKeyExchange(sslSocket
* ss
, SECKEYPublicKey
* svrPubKey
)
6021 PK11SymKey
* pms
= NULL
;
6022 SECStatus rv
= SECFailure
;
6023 SECItem enc_pms
= {siBuffer
, NULL
, 0};
6026 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
6027 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
6029 /* Generate the pre-master secret ... */
6030 ssl_GetSpecWriteLock(ss
);
6031 isTLS
= (PRBool
)(ss
->ssl3
.pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
6033 pms
= ssl3_GenerateRSAPMS(ss
, ss
->ssl3
.pwSpec
, NULL
);
6034 ssl_ReleaseSpecWriteLock(ss
);
6036 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
6040 /* Get the wrapped (encrypted) pre-master secret, enc_pms */
6041 enc_pms
.len
= SECKEY_PublicKeyStrength(svrPubKey
);
6042 enc_pms
.data
= (unsigned char*)PORT_Alloc(enc_pms
.len
);
6043 if (enc_pms
.data
== NULL
) {
6044 goto loser
; /* err set by PORT_Alloc */
6047 /* wrap pre-master secret in server's public key. */
6048 rv
= PK11_PubWrapSymKey(CKM_RSA_PKCS
, svrPubKey
, pms
, &enc_pms
);
6049 if (rv
!= SECSuccess
) {
6050 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
6054 if (ssl_keylog_iob
) {
6055 SECStatus extractRV
= PK11_ExtractKeyValue(pms
);
6056 if (extractRV
== SECSuccess
) {
6057 SECItem
* keyData
= PK11_GetKeyData(pms
);
6058 if (keyData
&& keyData
->data
&& keyData
->len
) {
6060 if (ssl_trace
>= 100) {
6061 ssl_PrintBuf(ss
, "Pre-Master Secret",
6062 keyData
->data
, keyData
->len
);
6065 if (ssl_keylog_iob
&& enc_pms
.len
>= 8 && keyData
->len
== 48) {
6066 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
6068 /* There could be multiple, concurrent writers to the
6069 * keylog, so we have to do everything in a single call to
6071 char buf
[4 + 8*2 + 1 + 48*2 + 1];
6073 strcpy(buf
, "RSA ");
6074 hexEncode(buf
+ 4, enc_pms
.data
, 8);
6076 hexEncode(buf
+ 21, keyData
->data
, 48);
6077 buf
[sizeof(buf
) - 1] = '\n';
6079 fwrite(buf
, sizeof(buf
), 1, ssl_keylog_iob
);
6080 fflush(ssl_keylog_iob
);
6086 rv
= ssl3_InitPendingCipherSpec(ss
, pms
);
6087 PK11_FreeSymKey(pms
); pms
= NULL
;
6089 if (rv
!= SECSuccess
) {
6090 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
6094 rv
= ssl3_AppendHandshakeHeader(ss
, client_key_exchange
,
6095 isTLS
? enc_pms
.len
+ 2 : enc_pms
.len
);
6096 if (rv
!= SECSuccess
) {
6097 goto loser
; /* err set by ssl3_AppendHandshake* */
6100 rv
= ssl3_AppendHandshakeVariable(ss
, enc_pms
.data
, enc_pms
.len
, 2);
6102 rv
= ssl3_AppendHandshake(ss
, enc_pms
.data
, enc_pms
.len
);
6104 if (rv
!= SECSuccess
) {
6105 goto loser
; /* err set by ssl3_AppendHandshake* */
6111 if (enc_pms
.data
!= NULL
) {
6112 PORT_Free(enc_pms
.data
);
6115 PK11_FreeSymKey(pms
);
6120 /* Called from ssl3_SendClientKeyExchange(). */
6121 /* Presently, this always uses PKCS11. There is no bypass for this. */
6123 sendDHClientKeyExchange(sslSocket
* ss
, SECKEYPublicKey
* svrPubKey
)
6125 PK11SymKey
* pms
= NULL
;
6126 SECStatus rv
= SECFailure
;
6128 CK_MECHANISM_TYPE target
;
6130 SECKEYDHParams dhParam
; /* DH parameters */
6131 SECKEYPublicKey
*pubKey
= NULL
; /* Ephemeral DH key */
6132 SECKEYPrivateKey
*privKey
= NULL
; /* Ephemeral DH key */
6134 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
6135 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
6137 isTLS
= (PRBool
)(ss
->ssl3
.pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
6139 /* Copy DH parameters from server key */
6141 if (svrPubKey
->keyType
!= dhKey
) {
6142 PORT_SetError(SEC_ERROR_BAD_KEY
);
6145 dhParam
.prime
.data
= svrPubKey
->u
.dh
.prime
.data
;
6146 dhParam
.prime
.len
= svrPubKey
->u
.dh
.prime
.len
;
6147 dhParam
.base
.data
= svrPubKey
->u
.dh
.base
.data
;
6148 dhParam
.base
.len
= svrPubKey
->u
.dh
.base
.len
;
6150 /* Generate ephemeral DH keypair */
6151 privKey
= SECKEY_CreateDHPrivateKey(&dhParam
, &pubKey
, NULL
);
6152 if (!privKey
|| !pubKey
) {
6153 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL
);
6157 PRINT_BUF(50, (ss
, "DH public value:",
6158 pubKey
->u
.dh
.publicValue
.data
,
6159 pubKey
->u
.dh
.publicValue
.len
));
6161 if (isTLS
) target
= CKM_TLS_MASTER_KEY_DERIVE_DH
;
6162 else target
= CKM_SSL3_MASTER_KEY_DERIVE_DH
;
6164 /* Determine the PMS */
6166 pms
= PK11_PubDerive(privKey
, svrPubKey
, PR_FALSE
, NULL
, NULL
,
6167 CKM_DH_PKCS_DERIVE
, target
, CKA_DERIVE
, 0, NULL
);
6170 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
6174 SECKEY_DestroyPrivateKey(privKey
);
6177 rv
= ssl3_InitPendingCipherSpec(ss
, pms
);
6178 PK11_FreeSymKey(pms
); pms
= NULL
;
6180 if (rv
!= SECSuccess
) {
6181 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
6185 rv
= ssl3_AppendHandshakeHeader(ss
, client_key_exchange
,
6186 pubKey
->u
.dh
.publicValue
.len
+ 2);
6187 if (rv
!= SECSuccess
) {
6188 goto loser
; /* err set by ssl3_AppendHandshake* */
6190 rv
= ssl3_AppendHandshakeVariable(ss
,
6191 pubKey
->u
.dh
.publicValue
.data
,
6192 pubKey
->u
.dh
.publicValue
.len
, 2);
6193 SECKEY_DestroyPublicKey(pubKey
);
6196 if (rv
!= SECSuccess
) {
6197 goto loser
; /* err set by ssl3_AppendHandshake* */
6205 if(pms
) PK11_FreeSymKey(pms
);
6206 if(privKey
) SECKEY_DestroyPrivateKey(privKey
);
6207 if(pubKey
) SECKEY_DestroyPublicKey(pubKey
);
6215 /* Called from ssl3_HandleServerHelloDone(). */
6217 ssl3_SendClientKeyExchange(sslSocket
*ss
)
6219 SECKEYPublicKey
* serverKey
= NULL
;
6220 SECStatus rv
= SECFailure
;
6223 SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
6224 SSL_GETPID(), ss
->fd
));
6226 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
6227 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
6229 if (ss
->sec
.peerKey
== NULL
) {
6230 serverKey
= CERT_ExtractPublicKey(ss
->sec
.peerCert
);
6231 if (serverKey
== NULL
) {
6232 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE
);
6236 serverKey
= ss
->sec
.peerKey
;
6237 ss
->sec
.peerKey
= NULL
; /* we're done with it now */
6240 isTLS
= (PRBool
)(ss
->ssl3
.pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
6241 /* enforce limits on kea key sizes. */
6242 if (ss
->ssl3
.hs
.kea_def
->is_limited
) {
6243 int keyLen
= SECKEY_PublicKeyStrength(serverKey
); /* bytes */
6245 if (keyLen
* BPB
> ss
->ssl3
.hs
.kea_def
->key_size_limit
) {
6247 (void)SSL3_SendAlert(ss
, alert_fatal
, export_restriction
);
6249 (void)ssl3_HandshakeFailure(ss
);
6250 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED
);
6255 ss
->sec
.keaType
= ss
->ssl3
.hs
.kea_def
->exchKeyType
;
6256 ss
->sec
.keaKeyBits
= SECKEY_PublicKeyStrengthInBits(serverKey
);
6258 switch (ss
->ssl3
.hs
.kea_def
->exchKeyType
) {
6260 rv
= sendRSAClientKeyExchange(ss
, serverKey
);
6264 rv
= sendDHClientKeyExchange(ss
, serverKey
);
6267 #ifndef NSS_DISABLE_ECC
6269 rv
= ssl3_SendECDHClientKeyExchange(ss
, serverKey
);
6271 #endif /* NSS_DISABLE_ECC */
6274 /* got an unknown or unsupported Key Exchange Algorithm. */
6276 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG
);
6280 SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
6281 SSL_GETPID(), ss
->fd
));
6285 SECKEY_DestroyPublicKey(serverKey
);
6286 return rv
; /* err code already set. */
6289 /* Called from ssl3_HandleServerHelloDone(). */
6291 ssl3_SendCertificateVerify(sslSocket
*ss
)
6293 SECStatus rv
= SECFailure
;
6296 SECItem buf
= {siBuffer
, NULL
, 0};
6300 SSL3SignatureAndHashAlgorithm sigAndHash
;
6302 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
6303 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
6305 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
6306 SSL_GETPID(), ss
->fd
));
6308 ssl_GetSpecReadLock(ss
);
6309 if (ss
->ssl3
.hs
.hashType
== handshake_hash_single
&&
6310 ss
->ssl3
.hs
.backupHash
) {
6311 rv
= ssl3_ComputeBackupHandshakeHashes(ss
, &hashes
);
6312 PORT_Assert(!ss
->ssl3
.hs
.backupHash
);
6314 rv
= ssl3_ComputeHandshakeHashes(ss
, ss
->ssl3
.pwSpec
, &hashes
, 0);
6316 ssl_ReleaseSpecReadLock(ss
);
6317 if (rv
!= SECSuccess
) {
6318 goto done
; /* err code was set by ssl3_ComputeHandshakeHashes */
6321 isTLS
= (PRBool
)(ss
->ssl3
.pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
6322 isTLS12
= (PRBool
)(ss
->ssl3
.pwSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_2
);
6323 if (ss
->ssl3
.platformClientKey
) {
6324 #ifdef NSS_PLATFORM_CLIENT_AUTH
6325 keyType
= CERT_GetCertKeyType(
6326 &ss
->ssl3
.clientCertificate
->subjectPublicKeyInfo
);
6327 rv
= ssl3_PlatformSignHashes(
6328 &hashes
, ss
->ssl3
.platformClientKey
, &buf
, isTLS
, keyType
);
6329 ssl_FreePlatformKey(ss
->ssl3
.platformClientKey
);
6330 ss
->ssl3
.platformClientKey
= (PlatformKey
)NULL
;
6331 #endif /* NSS_PLATFORM_CLIENT_AUTH */
6333 keyType
= ss
->ssl3
.clientPrivateKey
->keyType
;
6334 rv
= ssl3_SignHashes(&hashes
, ss
->ssl3
.clientPrivateKey
, &buf
, isTLS
);
6335 if (rv
== SECSuccess
) {
6336 PK11SlotInfo
* slot
;
6337 sslSessionID
* sid
= ss
->sec
.ci
.sid
;
6339 /* Remember the info about the slot that did the signing.
6340 ** Later, when doing an SSL restart handshake, verify this.
6341 ** These calls are mere accessors, and can't fail.
6343 slot
= PK11_GetSlotFromPrivateKey(ss
->ssl3
.clientPrivateKey
);
6344 sid
->u
.ssl3
.clAuthSeries
= PK11_GetSlotSeries(slot
);
6345 sid
->u
.ssl3
.clAuthSlotID
= PK11_GetSlotID(slot
);
6346 sid
->u
.ssl3
.clAuthModuleID
= PK11_GetModuleID(slot
);
6347 sid
->u
.ssl3
.clAuthValid
= PR_TRUE
;
6348 PK11_FreeSlot(slot
);
6350 SECKEY_DestroyPrivateKey(ss
->ssl3
.clientPrivateKey
);
6351 ss
->ssl3
.clientPrivateKey
= NULL
;
6353 if (rv
!= SECSuccess
) {
6354 goto done
; /* err code was set by ssl3_SignHashes */
6357 len
= buf
.len
+ 2 + (isTLS12
? 2 : 0);
6359 rv
= ssl3_AppendHandshakeHeader(ss
, certificate_verify
, len
);
6360 if (rv
!= SECSuccess
) {
6361 goto done
; /* error code set by AppendHandshake */
6364 rv
= ssl3_TLSSignatureAlgorithmForKeyType(keyType
,
6365 &sigAndHash
.sigAlg
);
6366 if (rv
!= SECSuccess
) {
6369 sigAndHash
.hashAlg
= hashes
.hashAlg
;
6371 rv
= ssl3_AppendSignatureAndHashAlgorithm(ss
, &sigAndHash
);
6372 if (rv
!= SECSuccess
) {
6373 goto done
; /* err set by AppendHandshake. */
6376 rv
= ssl3_AppendHandshakeVariable(ss
, buf
.data
, buf
.len
, 2);
6377 if (rv
!= SECSuccess
) {
6378 goto done
; /* error code set by AppendHandshake */
6383 PORT_Free(buf
.data
);
6387 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6388 * ssl3 ServerHello message.
6389 * Caller must hold Handshake and RecvBuf locks.
6392 ssl3_HandleServerHello(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
6394 sslSessionID
*sid
= ss
->sec
.ci
.sid
;
6395 PRInt32 temp
; /* allow for consume number failure */
6396 PRBool suite_found
= PR_FALSE
;
6398 int errCode
= SSL_ERROR_RX_MALFORMED_SERVER_HELLO
;
6400 SECItem sidBytes
= {siBuffer
, NULL
, 0};
6402 PRBool isTLS
= PR_FALSE
;
6403 SSL3AlertDescription desc
= illegal_parameter
;
6404 SSL3ProtocolVersion version
;
6406 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
6407 SSL_GETPID(), ss
->fd
));
6408 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
6409 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
6410 PORT_Assert( ss
->ssl3
.initialized
);
6412 if (ss
->ssl3
.hs
.ws
!= wait_server_hello
) {
6413 errCode
= SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO
;
6414 desc
= unexpected_message
;
6418 /* clean up anything left from previous handshake. */
6419 if (ss
->ssl3
.clientCertChain
!= NULL
) {
6420 CERT_DestroyCertificateList(ss
->ssl3
.clientCertChain
);
6421 ss
->ssl3
.clientCertChain
= NULL
;
6423 if (ss
->ssl3
.clientCertificate
!= NULL
) {
6424 CERT_DestroyCertificate(ss
->ssl3
.clientCertificate
);
6425 ss
->ssl3
.clientCertificate
= NULL
;
6427 if (ss
->ssl3
.clientPrivateKey
!= NULL
) {
6428 SECKEY_DestroyPrivateKey(ss
->ssl3
.clientPrivateKey
);
6429 ss
->ssl3
.clientPrivateKey
= NULL
;
6431 #ifdef NSS_PLATFORM_CLIENT_AUTH
6432 if (ss
->ssl3
.platformClientKey
) {
6433 ssl_FreePlatformKey(ss
->ssl3
.platformClientKey
);
6434 ss
->ssl3
.platformClientKey
= (PlatformKey
)NULL
;
6436 #endif /* NSS_PLATFORM_CLIENT_AUTH */
6438 if (ss
->ssl3
.channelID
!= NULL
) {
6439 SECKEY_DestroyPrivateKey(ss
->ssl3
.channelID
);
6440 ss
->ssl3
.channelID
= NULL
;
6442 if (ss
->ssl3
.channelIDPub
!= NULL
) {
6443 SECKEY_DestroyPublicKey(ss
->ssl3
.channelIDPub
);
6444 ss
->ssl3
.channelIDPub
= NULL
;
6447 temp
= ssl3_ConsumeHandshakeNumber(ss
, 2, &b
, &length
);
6449 goto loser
; /* alert has been sent */
6451 version
= (SSL3ProtocolVersion
)temp
;
6454 /* RFC 4347 required that you verify that the server versions
6455 * match (Section 4.2.1) in the HelloVerifyRequest and the
6458 * RFC 6347 suggests (SHOULD) that servers always use 1.0
6459 * in HelloVerifyRequest and allows the versions not to match,
6460 * especially when 1.2 is being negotiated.
6462 * Therefore we do not check for matching here.
6464 version
= dtls_DTLSVersionToTLSVersion(version
);
6465 if (version
== 0) { /* Insane version number */
6470 rv
= ssl3_NegotiateVersion(ss
, version
, PR_FALSE
);
6471 if (rv
!= SECSuccess
) {
6472 desc
= (version
> SSL_LIBRARY_VERSION_3_0
) ? protocol_version
6473 : handshake_failure
;
6474 errCode
= SSL_ERROR_UNSUPPORTED_VERSION
;
6477 isTLS
= (ss
->version
> SSL_LIBRARY_VERSION_3_0
);
6479 rv
= ssl3_InitHandshakeHashes(ss
);
6480 if (rv
!= SECSuccess
) {
6481 desc
= internal_error
;
6482 errCode
= PORT_GetError();
6486 rv
= ssl3_ConsumeHandshake(
6487 ss
, &ss
->ssl3
.hs
.server_random
, SSL3_RANDOM_LENGTH
, &b
, &length
);
6488 if (rv
!= SECSuccess
) {
6489 goto loser
; /* alert has been sent */
6492 rv
= ssl3_ConsumeHandshakeVariable(ss
, &sidBytes
, 1, &b
, &length
);
6493 if (rv
!= SECSuccess
) {
6494 goto loser
; /* alert has been sent */
6496 if (sidBytes
.len
> SSL3_SESSIONID_BYTES
) {
6498 desc
= decode_error
;
6499 goto alert_loser
; /* malformed. */
6502 /* find selected cipher suite in our list. */
6503 temp
= ssl3_ConsumeHandshakeNumber(ss
, 2, &b
, &length
);
6505 goto loser
; /* alert has been sent */
6507 ssl3_config_match_init(ss
);
6508 for (i
= 0; i
< ssl_V3_SUITES_IMPLEMENTED
; i
++) {
6509 ssl3CipherSuiteCfg
*suite
= &ss
->cipherSuites
[i
];
6510 if (temp
== suite
->cipher_suite
) {
6511 SSLVersionRange vrange
= {ss
->version
, ss
->version
};
6512 if (!config_match(suite
, ss
->ssl3
.policy
, PR_TRUE
, &vrange
)) {
6513 /* config_match already checks whether the cipher suite is
6514 * acceptable for the version, but the check is repeated here
6515 * in order to give a more precise error code. */
6516 if (!ssl3_CipherSuiteAllowedForVersionRange(temp
, &vrange
)) {
6517 desc
= handshake_failure
;
6518 errCode
= SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION
;
6522 break; /* failure */
6525 suite_found
= PR_TRUE
;
6526 break; /* success */
6530 desc
= handshake_failure
;
6531 errCode
= SSL_ERROR_NO_CYPHER_OVERLAP
;
6534 ss
->ssl3
.hs
.cipher_suite
= (ssl3CipherSuite
)temp
;
6535 ss
->ssl3
.hs
.suite_def
= ssl_LookupCipherSuiteDef((ssl3CipherSuite
)temp
);
6536 PORT_Assert(ss
->ssl3
.hs
.suite_def
);
6537 if (!ss
->ssl3
.hs
.suite_def
) {
6538 PORT_SetError(errCode
= SEC_ERROR_LIBRARY_FAILURE
);
6539 goto loser
; /* we don't send alerts for our screw-ups. */
6542 /* find selected compression method in our list. */
6543 temp
= ssl3_ConsumeHandshakeNumber(ss
, 1, &b
, &length
);
6545 goto loser
; /* alert has been sent */
6547 suite_found
= PR_FALSE
;
6548 for (i
= 0; i
< compressionMethodsCount
; i
++) {
6549 if (temp
== compressions
[i
]) {
6550 if (!compressionEnabled(ss
, compressions
[i
])) {
6551 break; /* failure */
6553 suite_found
= PR_TRUE
;
6554 break; /* success */
6558 desc
= handshake_failure
;
6559 errCode
= SSL_ERROR_NO_COMPRESSION_OVERLAP
;
6562 ss
->ssl3
.hs
.compression
= (SSLCompressionMethod
)temp
;
6564 /* Note that if !isTLS and the extra stuff is not extensions, we
6565 * do NOT goto alert_loser.
6566 * There are some old SSL 3.0 implementations that do send stuff
6567 * after the end of the server hello, and we deliberately ignore
6568 * such stuff in the interest of maximal interoperability (being
6569 * "generous in what you accept").
6570 * Update: Starting in NSS 3.12.6, we handle the renegotiation_info
6571 * extension in SSL 3.0.
6575 rv
= ssl3_ConsumeHandshakeVariable(ss
, &extensions
, 2, &b
, &length
);
6576 if (rv
!= SECSuccess
|| length
!= 0) {
6580 rv
= ssl3_HandleHelloExtensions(ss
, &extensions
.data
,
6582 if (rv
!= SECSuccess
)
6586 if ((ss
->opt
.requireSafeNegotiation
||
6587 (ss
->firstHsDone
&& (ss
->peerRequestedProtection
||
6588 ss
->opt
.enableRenegotiation
== SSL_RENEGOTIATE_REQUIRES_XTN
))) &&
6589 !ssl3_ExtensionNegotiated(ss
, ssl_renegotiation_info_xtn
)) {
6590 desc
= handshake_failure
;
6591 errCode
= ss
->firstHsDone
? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
6592 : SSL_ERROR_UNSAFE_NEGOTIATION
;
6596 /* Any errors after this point are not "malformed" errors. */
6597 desc
= handshake_failure
;
6599 /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
6600 * key exchange algorithm. */
6601 rv
= ssl3_SetupPendingCipherSpec(ss
);
6602 if (rv
!= SECSuccess
) {
6603 goto alert_loser
; /* error code is set. */
6606 /* We may or may not have sent a session id, we may get one back or
6607 * not and if so it may match the one we sent.
6608 * Attempt to restore the master secret to see if this is so...
6609 * Don't consider failure to find a matching SID an error.
6611 sid_match
= (PRBool
)(sidBytes
.len
> 0 &&
6612 sidBytes
.len
== sid
->u
.ssl3
.sessionIDLength
&&
6613 !PORT_Memcmp(sid
->u
.ssl3
.sessionID
, sidBytes
.data
, sidBytes
.len
));
6616 sid
->version
== ss
->version
&&
6617 sid
->u
.ssl3
.cipherSuite
== ss
->ssl3
.hs
.cipher_suite
) do {
6618 ssl3CipherSpec
*pwSpec
= ss
->ssl3
.pwSpec
;
6620 SECItem wrappedMS
; /* wrapped master secret. */
6622 ss
->sec
.authAlgorithm
= sid
->authAlgorithm
;
6623 ss
->sec
.authKeyBits
= sid
->authKeyBits
;
6624 ss
->sec
.keaType
= sid
->keaType
;
6625 ss
->sec
.keaKeyBits
= sid
->keaKeyBits
;
6628 * a) key is wrapped (implies using PKCS11)
6629 * b) key is unwrapped, but we're still using PKCS11
6630 * c) key is unwrapped, and we're bypassing PKCS11.
6632 if (sid
->u
.ssl3
.keys
.msIsWrapped
) {
6634 PK11SymKey
* wrapKey
; /* wrapping key */
6635 CK_FLAGS keyFlags
= 0;
6637 #ifndef NO_PKCS11_BYPASS
6638 if (ss
->opt
.bypassPKCS11
) {
6639 /* we cannot restart a non-bypass session in a
6645 /* unwrap master secret with PKCS11 */
6646 slot
= SECMOD_LookupSlot(sid
->u
.ssl3
.masterModuleID
,
6647 sid
->u
.ssl3
.masterSlotID
);
6649 break; /* not considered an error. */
6651 if (!PK11_IsPresent(slot
)) {
6652 PK11_FreeSlot(slot
);
6653 break; /* not considered an error. */
6655 wrapKey
= PK11_GetWrapKey(slot
, sid
->u
.ssl3
.masterWrapIndex
,
6656 sid
->u
.ssl3
.masterWrapMech
,
6657 sid
->u
.ssl3
.masterWrapSeries
,
6659 PK11_FreeSlot(slot
);
6660 if (wrapKey
== NULL
) {
6661 break; /* not considered an error. */
6664 if (ss
->version
> SSL_LIBRARY_VERSION_3_0
) { /* isTLS */
6665 keyFlags
= CKF_SIGN
| CKF_VERIFY
;
6668 wrappedMS
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
6669 wrappedMS
.len
= sid
->u
.ssl3
.keys
.wrapped_master_secret_len
;
6670 pwSpec
->master_secret
=
6671 PK11_UnwrapSymKeyWithFlags(wrapKey
, sid
->u
.ssl3
.masterWrapMech
,
6672 NULL
, &wrappedMS
, CKM_SSL3_MASTER_KEY_DERIVE
,
6673 CKA_DERIVE
, sizeof(SSL3MasterSecret
), keyFlags
);
6674 errCode
= PORT_GetError();
6675 PK11_FreeSymKey(wrapKey
);
6676 if (pwSpec
->master_secret
== NULL
) {
6677 break; /* errorCode set just after call to UnwrapSymKey. */
6679 #ifndef NO_PKCS11_BYPASS
6680 } else if (ss
->opt
.bypassPKCS11
) {
6681 /* MS is not wrapped */
6682 wrappedMS
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
6683 wrappedMS
.len
= sid
->u
.ssl3
.keys
.wrapped_master_secret_len
;
6684 memcpy(pwSpec
->raw_master_secret
, wrappedMS
.data
, wrappedMS
.len
);
6685 pwSpec
->msItem
.data
= pwSpec
->raw_master_secret
;
6686 pwSpec
->msItem
.len
= wrappedMS
.len
;
6689 /* We CAN restart a bypass session in a non-bypass socket. */
6690 /* need to import the raw master secret to session object */
6691 PK11SlotInfo
*slot
= PK11_GetInternalSlot();
6692 wrappedMS
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
6693 wrappedMS
.len
= sid
->u
.ssl3
.keys
.wrapped_master_secret_len
;
6694 pwSpec
->master_secret
=
6695 PK11_ImportSymKey(slot
, CKM_SSL3_MASTER_KEY_DERIVE
,
6696 PK11_OriginUnwrap
, CKA_ENCRYPT
,
6698 PK11_FreeSlot(slot
);
6699 if (pwSpec
->master_secret
== NULL
) {
6705 SSL_AtomicIncrementLong(& ssl3stats
.hsh_sid_cache_hits
);
6707 /* If we sent a session ticket, then this is a stateless resume. */
6708 if (ss
->xtnData
.sentSessionTicketInClientHello
)
6709 SSL_AtomicIncrementLong(& ssl3stats
.hsh_sid_stateless_resumes
);
6711 if (ssl3_ExtensionNegotiated(ss
, ssl_session_ticket_xtn
))
6712 ss
->ssl3
.hs
.ws
= wait_new_session_ticket
;
6714 ss
->ssl3
.hs
.ws
= wait_change_cipher
;
6716 ss
->ssl3
.hs
.isResuming
= PR_TRUE
;
6718 /* copy the peer cert from the SID */
6719 if (sid
->peerCert
!= NULL
) {
6720 ss
->sec
.peerCert
= CERT_DupCertificate(sid
->peerCert
);
6721 ssl3_CopyPeerCertsFromSID(ss
, sid
);
6724 /* NULL value for PMS signifies re-use of the old MS */
6725 rv
= ssl3_InitPendingCipherSpec(ss
, NULL
);
6726 if (rv
!= SECSuccess
) {
6727 goto alert_loser
; /* err code was set */
6733 SSL_AtomicIncrementLong(& ssl3stats
.hsh_sid_cache_not_ok
);
6735 SSL_AtomicIncrementLong(& ssl3stats
.hsh_sid_cache_misses
);
6737 /* throw the old one away */
6738 sid
->u
.ssl3
.keys
.resumable
= PR_FALSE
;
6739 if (ss
->sec
.uncache
)
6740 (*ss
->sec
.uncache
)(sid
);
6744 ss
->sec
.ci
.sid
= sid
= ssl3_NewSessionID(ss
, PR_FALSE
);
6746 goto alert_loser
; /* memory error is set. */
6749 sid
->version
= ss
->version
;
6750 sid
->u
.ssl3
.sessionIDLength
= sidBytes
.len
;
6751 PORT_Memcpy(sid
->u
.ssl3
.sessionID
, sidBytes
.data
, sidBytes
.len
);
6753 /* Copy Signed Certificate Timestamps, if any. */
6754 if (ss
->xtnData
.signedCertTimestamps
.data
) {
6755 rv
= SECITEM_CopyItem(NULL
, &sid
->u
.ssl3
.signedCertTimestamps
,
6756 &ss
->xtnData
.signedCertTimestamps
);
6757 if (rv
!= SECSuccess
)
6761 ss
->ssl3
.hs
.isResuming
= PR_FALSE
;
6762 if (ss
->ssl3
.hs
.kea_def
->signKeyType
!= sign_null
) {
6763 /* All current cipher suites other than those with sign_null (i.e.,
6764 * DH_anon_* suites) require a certificate, so use that signal. */
6765 ss
->ssl3
.hs
.ws
= wait_server_cert
;
6766 } else if (ss
->ssl3
.hs
.kea_def
->ephemeral
) {
6767 /* Only ephemeral cipher suites use ServerKeyExchange. */
6768 ss
->ssl3
.hs
.ws
= wait_server_key
;
6770 ss
->ssl3
.hs
.ws
= wait_cert_request
;
6774 /* Clean up the temporary pointer to the handshake buffer. */
6775 ss
->xtnData
.signedCertTimestamps
.data
= NULL
;
6776 ss
->xtnData
.signedCertTimestamps
.len
= 0;
6778 /* If we will need a ChannelID key then we make the callback now. This
6779 * allows the handshake to be restarted cleanly if the callback returns
6781 if (ssl3_ExtensionNegotiated(ss
, ssl_channel_id_xtn
)) {
6782 rv
= ss
->getChannelID(ss
->getChannelIDArg
, ss
->fd
,
6783 &ss
->ssl3
.channelIDPub
, &ss
->ssl3
.channelID
);
6784 if (rv
== SECWouldBlock
) {
6785 ssl3_SetAlwaysBlock(ss
);
6788 if (rv
!= SECSuccess
||
6789 ss
->ssl3
.channelIDPub
== NULL
||
6790 ss
->ssl3
.channelID
== NULL
) {
6791 PORT_SetError(SSL_ERROR_GET_CHANNEL_ID_FAILED
);
6792 desc
= internal_error
;
6800 (void)SSL3_SendAlert(ss
, alert_fatal
, desc
);
6803 /* Clean up the temporary pointer to the handshake buffer. */
6804 ss
->xtnData
.signedCertTimestamps
.data
= NULL
;
6805 ss
->xtnData
.signedCertTimestamps
.len
= 0;
6806 errCode
= ssl_MapLowLevelError(errCode
);
6810 /* ssl3_BigIntGreaterThanOne returns true iff |mpint|, taken as an unsigned,
6811 * big-endian integer is > 1 */
6813 ssl3_BigIntGreaterThanOne(const SECItem
* mpint
) {
6814 unsigned char firstNonZeroByte
= 0;
6817 for (i
= 0; i
< mpint
->len
; i
++) {
6818 if (mpint
->data
[i
]) {
6819 firstNonZeroByte
= mpint
->data
[i
];
6824 if (firstNonZeroByte
== 0)
6826 if (firstNonZeroByte
> 1)
6829 /* firstNonZeroByte == 1, therefore mpint > 1 iff the first non-zero byte
6830 * is followed by another byte. */
6831 return (i
< mpint
->len
- 1);
6834 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6835 * ssl3 ServerKeyExchange message.
6836 * Caller must hold Handshake and RecvBuf locks.
6839 ssl3_HandleServerKeyExchange(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
6841 PLArenaPool
* arena
= NULL
;
6842 SECKEYPublicKey
*peerKey
= NULL
;
6843 PRBool isTLS
, isTLS12
;
6845 int errCode
= SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH
;
6846 SSL3AlertDescription desc
= illegal_parameter
;
6848 SECItem signature
= {siBuffer
, NULL
, 0};
6849 SSL3SignatureAndHashAlgorithm sigAndHash
;
6851 sigAndHash
.hashAlg
= SEC_OID_UNKNOWN
;
6853 SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
6854 SSL_GETPID(), ss
->fd
));
6855 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
6856 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
6858 if (ss
->ssl3
.hs
.ws
!= wait_server_key
) {
6859 errCode
= SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH
;
6860 desc
= unexpected_message
;
6864 isTLS
= (PRBool
)(ss
->ssl3
.prSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
6865 isTLS12
= (PRBool
)(ss
->ssl3
.prSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_2
);
6867 switch (ss
->ssl3
.hs
.kea_def
->exchKeyType
) {
6870 SECItem modulus
= {siBuffer
, NULL
, 0};
6871 SECItem exponent
= {siBuffer
, NULL
, 0};
6873 rv
= ssl3_ConsumeHandshakeVariable(ss
, &modulus
, 2, &b
, &length
);
6874 if (rv
!= SECSuccess
) {
6875 goto loser
; /* malformed. */
6877 rv
= ssl3_ConsumeHandshakeVariable(ss
, &exponent
, 2, &b
, &length
);
6878 if (rv
!= SECSuccess
) {
6879 goto loser
; /* malformed. */
6882 rv
= ssl3_ConsumeSignatureAndHashAlgorithm(ss
, &b
, &length
,
6884 if (rv
!= SECSuccess
) {
6885 goto loser
; /* malformed or unsupported. */
6887 rv
= ssl3_CheckSignatureAndHashAlgorithmConsistency(
6888 &sigAndHash
, ss
->sec
.peerCert
);
6889 if (rv
!= SECSuccess
) {
6893 rv
= ssl3_ConsumeHandshakeVariable(ss
, &signature
, 2, &b
, &length
);
6894 if (rv
!= SECSuccess
) {
6895 goto loser
; /* malformed. */
6899 desc
= decode_error
;
6900 goto alert_loser
; /* malformed. */
6903 /* failures after this point are not malformed handshakes. */
6904 /* TLS: send decrypt_error if signature failed. */
6905 desc
= isTLS
? decrypt_error
: handshake_failure
;
6908 * check to make sure the hash is signed by right guy
6910 rv
= ssl3_ComputeExportRSAKeyHash(sigAndHash
.hashAlg
, modulus
, exponent
,
6911 &ss
->ssl3
.hs
.client_random
,
6912 &ss
->ssl3
.hs
.server_random
,
6913 &hashes
, ss
->opt
.bypassPKCS11
);
6914 if (rv
!= SECSuccess
) {
6916 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
6919 rv
= ssl3_VerifySignedHashes(&hashes
, ss
->sec
.peerCert
, &signature
,
6920 isTLS
, ss
->pkcs11PinArg
);
6921 if (rv
!= SECSuccess
) {
6923 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
6928 * we really need to build a new key here because we can no longer
6929 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
6930 * pkcs11 slots and ID's.
6932 arena
= PORT_NewArena(DER_DEFAULT_CHUNKSIZE
);
6933 if (arena
== NULL
) {
6937 peerKey
= PORT_ArenaZNew(arena
, SECKEYPublicKey
);
6938 if (peerKey
== NULL
) {
6939 PORT_FreeArena(arena
, PR_FALSE
);
6943 peerKey
->arena
= arena
;
6944 peerKey
->keyType
= rsaKey
;
6945 peerKey
->pkcs11Slot
= NULL
;
6946 peerKey
->pkcs11ID
= CK_INVALID_HANDLE
;
6947 if (SECITEM_CopyItem(arena
, &peerKey
->u
.rsa
.modulus
, &modulus
) ||
6948 SECITEM_CopyItem(arena
, &peerKey
->u
.rsa
.publicExponent
, &exponent
))
6950 PORT_FreeArena(arena
, PR_FALSE
);
6953 ss
->sec
.peerKey
= peerKey
;
6954 ss
->ssl3
.hs
.ws
= wait_cert_request
;
6959 SECItem dh_p
= {siBuffer
, NULL
, 0};
6960 SECItem dh_g
= {siBuffer
, NULL
, 0};
6961 SECItem dh_Ys
= {siBuffer
, NULL
, 0};
6963 rv
= ssl3_ConsumeHandshakeVariable(ss
, &dh_p
, 2, &b
, &length
);
6964 if (rv
!= SECSuccess
) {
6965 goto loser
; /* malformed. */
6967 if (dh_p
.len
< 1024/8 ||
6968 (dh_p
.len
== 1024/8 && (dh_p
.data
[0] & 0x80) == 0)) {
6969 errCode
= SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY
;
6972 rv
= ssl3_ConsumeHandshakeVariable(ss
, &dh_g
, 2, &b
, &length
);
6973 if (rv
!= SECSuccess
) {
6974 goto loser
; /* malformed. */
6976 if (dh_g
.len
> dh_p
.len
|| !ssl3_BigIntGreaterThanOne(&dh_g
))
6978 rv
= ssl3_ConsumeHandshakeVariable(ss
, &dh_Ys
, 2, &b
, &length
);
6979 if (rv
!= SECSuccess
) {
6980 goto loser
; /* malformed. */
6982 if (dh_Ys
.len
> dh_p
.len
|| !ssl3_BigIntGreaterThanOne(&dh_Ys
))
6985 rv
= ssl3_ConsumeSignatureAndHashAlgorithm(ss
, &b
, &length
,
6987 if (rv
!= SECSuccess
) {
6988 goto loser
; /* malformed or unsupported. */
6990 rv
= ssl3_CheckSignatureAndHashAlgorithmConsistency(
6991 &sigAndHash
, ss
->sec
.peerCert
);
6992 if (rv
!= SECSuccess
) {
6996 rv
= ssl3_ConsumeHandshakeVariable(ss
, &signature
, 2, &b
, &length
);
6997 if (rv
!= SECSuccess
) {
6998 goto loser
; /* malformed. */
7002 desc
= decode_error
;
7003 goto alert_loser
; /* malformed. */
7006 PRINT_BUF(60, (NULL
, "Server DH p", dh_p
.data
, dh_p
.len
));
7007 PRINT_BUF(60, (NULL
, "Server DH g", dh_g
.data
, dh_g
.len
));
7008 PRINT_BUF(60, (NULL
, "Server DH Ys", dh_Ys
.data
, dh_Ys
.len
));
7010 /* failures after this point are not malformed handshakes. */
7011 /* TLS: send decrypt_error if signature failed. */
7012 desc
= isTLS
? decrypt_error
: handshake_failure
;
7015 * check to make sure the hash is signed by right guy
7017 rv
= ssl3_ComputeDHKeyHash(sigAndHash
.hashAlg
, dh_p
, dh_g
, dh_Ys
,
7018 &ss
->ssl3
.hs
.client_random
,
7019 &ss
->ssl3
.hs
.server_random
,
7020 &hashes
, ss
->opt
.bypassPKCS11
);
7021 if (rv
!= SECSuccess
) {
7023 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
7026 rv
= ssl3_VerifySignedHashes(&hashes
, ss
->sec
.peerCert
, &signature
,
7027 isTLS
, ss
->pkcs11PinArg
);
7028 if (rv
!= SECSuccess
) {
7030 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
7035 * we really need to build a new key here because we can no longer
7036 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
7037 * pkcs11 slots and ID's.
7039 arena
= PORT_NewArena(DER_DEFAULT_CHUNKSIZE
);
7040 if (arena
== NULL
) {
7044 ss
->sec
.peerKey
= peerKey
= PORT_ArenaZNew(arena
, SECKEYPublicKey
);
7045 if (peerKey
== NULL
) {
7049 peerKey
->arena
= arena
;
7050 peerKey
->keyType
= dhKey
;
7051 peerKey
->pkcs11Slot
= NULL
;
7052 peerKey
->pkcs11ID
= CK_INVALID_HANDLE
;
7054 if (SECITEM_CopyItem(arena
, &peerKey
->u
.dh
.prime
, &dh_p
) ||
7055 SECITEM_CopyItem(arena
, &peerKey
->u
.dh
.base
, &dh_g
) ||
7056 SECITEM_CopyItem(arena
, &peerKey
->u
.dh
.publicValue
, &dh_Ys
))
7058 PORT_FreeArena(arena
, PR_FALSE
);
7061 ss
->sec
.peerKey
= peerKey
;
7062 ss
->ssl3
.hs
.ws
= wait_cert_request
;
7066 #ifndef NSS_DISABLE_ECC
7068 rv
= ssl3_HandleECDHServerKeyExchange(ss
, b
, length
);
7070 #endif /* NSS_DISABLE_ECC */
7073 desc
= handshake_failure
;
7074 errCode
= SEC_ERROR_UNSUPPORTED_KEYALG
;
7075 break; /* goto alert_loser; */
7079 (void)SSL3_SendAlert(ss
, alert_fatal
, desc
);
7081 PORT_SetError( errCode
);
7084 no_memory
: /* no-memory error has already been set. */
7085 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
7090 * Returns the TLS signature algorithm for the client authentication key and
7091 * whether it is an RSA or DSA key that may be able to sign only SHA-1 hashes.
7094 ssl3_ExtractClientKeyInfo(sslSocket
*ss
,
7095 TLSSignatureAlgorithm
*sigAlg
,
7098 SECStatus rv
= SECSuccess
;
7099 SECKEYPublicKey
*pubk
;
7101 pubk
= CERT_ExtractPublicKey(ss
->ssl3
.clientCertificate
);
7107 rv
= ssl3_TLSSignatureAlgorithmForKeyType(pubk
->keyType
, sigAlg
);
7108 if (rv
!= SECSuccess
) {
7112 #if defined(NSS_PLATFORM_CLIENT_AUTH) && defined(_WIN32)
7113 /* If the key is in CAPI, assume conservatively that the CAPI service
7114 * provider may be unable to sign SHA-256 hashes.
7116 if (ss
->ssl3
.platformClientKey
->dwKeySpec
!= CERT_NCRYPT_KEY_SPEC
) {
7117 /* CAPI only supports RSA and DSA signatures, so we don't need to
7118 * check the key type. */
7119 *preferSha1
= PR_TRUE
;
7122 #endif /* NSS_PLATFORM_CLIENT_AUTH && _WIN32 */
7124 /* If the key is a 1024-bit RSA or DSA key, assume conservatively that
7125 * it may be unable to sign SHA-256 hashes. This is the case for older
7126 * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and
7127 * older, DSA key size is at most 1024 bits and the hash function must
7130 if (pubk
->keyType
== rsaKey
|| pubk
->keyType
== dsaKey
) {
7131 *preferSha1
= SECKEY_PublicKeyStrength(pubk
) <= 128;
7133 *preferSha1
= PR_FALSE
;
7138 SECKEY_DestroyPublicKey(pubk
);
7142 /* Destroys the backup handshake hash context if we don't need it. Note that
7143 * this function selects the hash algorithm for client authentication
7144 * signatures; ssl3_SendCertificateVerify uses the presence of the backup hash
7145 * to determine whether to use SHA-1 or SHA-256. */
7147 ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket
*ss
,
7148 const SECItem
*algorithms
)
7151 TLSSignatureAlgorithm sigAlg
;
7153 PRBool supportsSha1
= PR_FALSE
;
7154 PRBool supportsSha256
= PR_FALSE
;
7155 PRBool needBackupHash
= PR_FALSE
;
7158 #ifndef NO_PKCS11_BYPASS
7159 /* Backup handshake hash is not supported in PKCS #11 bypass mode. */
7160 if (ss
->opt
.bypassPKCS11
) {
7161 PORT_Assert(!ss
->ssl3
.hs
.backupHash
);
7165 PORT_Assert(ss
->ssl3
.hs
.backupHash
);
7167 /* Determine the key's signature algorithm and whether it prefers SHA-1. */
7168 rv
= ssl3_ExtractClientKeyInfo(ss
, &sigAlg
, &preferSha1
);
7169 if (rv
!= SECSuccess
) {
7173 /* Determine the server's hash support for that signature algorithm. */
7174 for (i
= 0; i
< algorithms
->len
; i
+= 2) {
7175 if (algorithms
->data
[i
+1] == sigAlg
) {
7176 if (algorithms
->data
[i
] == tls_hash_sha1
) {
7177 supportsSha1
= PR_TRUE
;
7178 } else if (algorithms
->data
[i
] == tls_hash_sha256
) {
7179 supportsSha256
= PR_TRUE
;
7184 /* If either the server does not support SHA-256 or the client key prefers
7185 * SHA-1, leave the backup hash. */
7186 if (supportsSha1
&& (preferSha1
|| !supportsSha256
)) {
7187 needBackupHash
= PR_TRUE
;
7191 if (!needBackupHash
) {
7192 PK11_DestroyContext(ss
->ssl3
.hs
.backupHash
, PR_TRUE
);
7193 ss
->ssl3
.hs
.backupHash
= NULL
;
7197 typedef struct dnameNode
{
7198 struct dnameNode
*next
;
7202 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7203 * ssl3 Certificate Request message.
7204 * Caller must hold Handshake and RecvBuf locks.
7207 ssl3_HandleCertificateRequest(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
7209 PLArenaPool
* arena
= NULL
;
7212 PRBool isTLS
= PR_FALSE
;
7213 PRBool isTLS12
= PR_FALSE
;
7215 int errCode
= SSL_ERROR_RX_MALFORMED_CERT_REQUEST
;
7218 SSL3AlertDescription desc
= illegal_parameter
;
7219 SECItem cert_types
= {siBuffer
, NULL
, 0};
7220 SECItem algorithms
= {siBuffer
, NULL
, 0};
7221 CERTDistNames ca_list
;
7222 #ifdef NSS_PLATFORM_CLIENT_AUTH
7223 CERTCertList
* platform_cert_list
= NULL
;
7224 CERTCertListNode
* certNode
= NULL
;
7225 #endif /* NSS_PLATFORM_CLIENT_AUTH */
7227 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
7228 SSL_GETPID(), ss
->fd
));
7229 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
7230 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
7232 if (ss
->ssl3
.hs
.ws
!= wait_cert_request
) {
7233 desc
= unexpected_message
;
7234 errCode
= SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST
;
7238 PORT_Assert(ss
->ssl3
.clientCertChain
== NULL
);
7239 PORT_Assert(ss
->ssl3
.clientCertificate
== NULL
);
7240 PORT_Assert(ss
->ssl3
.clientPrivateKey
== NULL
);
7241 PORT_Assert(ss
->ssl3
.platformClientKey
== (PlatformKey
)NULL
);
7243 isTLS
= (PRBool
)(ss
->ssl3
.prSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
7244 isTLS12
= (PRBool
)(ss
->ssl3
.prSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_2
);
7245 rv
= ssl3_ConsumeHandshakeVariable(ss
, &cert_types
, 1, &b
, &length
);
7246 if (rv
!= SECSuccess
)
7247 goto loser
; /* malformed, alert has been sent */
7249 PORT_Assert(!ss
->requestedCertTypes
);
7250 ss
->requestedCertTypes
= &cert_types
;
7253 rv
= ssl3_ConsumeHandshakeVariable(ss
, &algorithms
, 2, &b
, &length
);
7254 if (rv
!= SECSuccess
)
7255 goto loser
; /* malformed, alert has been sent */
7256 /* An empty or odd-length value is invalid.
7257 * SignatureAndHashAlgorithm
7258 * supported_signature_algorithms<2..2^16-2>;
7260 if (algorithms
.len
== 0 || (algorithms
.len
& 1) != 0)
7264 arena
= ca_list
.arena
= PORT_NewArena(DER_DEFAULT_CHUNKSIZE
);
7268 remaining
= ssl3_ConsumeHandshakeNumber(ss
, 2, &b
, &length
);
7270 goto loser
; /* malformed, alert has been sent */
7272 if ((PRUint32
)remaining
> length
)
7275 ca_list
.head
= node
= PORT_ArenaZNew(arena
, dnameNode
);
7279 while (remaining
> 0) {
7283 goto alert_loser
; /* malformed */
7285 node
->name
.len
= len
= ssl3_ConsumeHandshakeNumber(ss
, 2, &b
, &length
);
7287 goto loser
; /* malformed, alert has been sent */
7290 if (remaining
< len
)
7291 goto alert_loser
; /* malformed */
7293 node
->name
.data
= b
;
7299 break; /* success */
7301 node
->next
= PORT_ArenaZNew(arena
, dnameNode
);
7307 ca_list
.nnames
= nnames
;
7308 ca_list
.names
= PORT_ArenaNewArray(arena
, SECItem
, nnames
);
7309 if (nnames
> 0 && ca_list
.names
== NULL
)
7312 for(i
= 0, node
= (dnameNode
*)ca_list
.head
;
7314 i
++, node
= node
->next
) {
7315 ca_list
.names
[i
] = node
->name
;
7319 goto alert_loser
; /* malformed */
7321 desc
= no_certificate
;
7322 ss
->ssl3
.hs
.ws
= wait_hello_done
;
7324 #ifdef NSS_PLATFORM_CLIENT_AUTH
7325 if (ss
->getPlatformClientAuthData
!= NULL
) {
7326 /* XXX Should pass cert_types and algorithms in this call!! */
7327 rv
= (SECStatus
)(*ss
->getPlatformClientAuthData
)(
7328 ss
->getPlatformClientAuthDataArg
,
7330 &platform_cert_list
,
7331 (void**)&ss
->ssl3
.platformClientKey
,
7332 &ss
->ssl3
.clientCertificate
,
7333 &ss
->ssl3
.clientPrivateKey
);
7336 if (ss
->getClientAuthData
!= NULL
) {
7337 /* XXX Should pass cert_types and algorithms in this call!! */
7338 rv
= (SECStatus
)(*ss
->getClientAuthData
)(ss
->getClientAuthDataArg
,
7340 &ss
->ssl3
.clientCertificate
,
7341 &ss
->ssl3
.clientPrivateKey
);
7343 rv
= SECFailure
; /* force it to send a no_certificate alert */
7347 case SECWouldBlock
: /* getClientAuthData has put up a dialog box. */
7348 ssl3_SetAlwaysBlock(ss
);
7349 break; /* not an error */
7352 #ifdef NSS_PLATFORM_CLIENT_AUTH
7353 if (!platform_cert_list
|| CERT_LIST_EMPTY(platform_cert_list
) ||
7354 !ss
->ssl3
.platformClientKey
) {
7355 if (platform_cert_list
) {
7356 CERT_DestroyCertList(platform_cert_list
);
7357 platform_cert_list
= NULL
;
7359 if (ss
->ssl3
.platformClientKey
) {
7360 ssl_FreePlatformKey(ss
->ssl3
.platformClientKey
);
7361 ss
->ssl3
.platformClientKey
= (PlatformKey
)NULL
;
7363 /* Fall through to NSS client auth check */
7365 certNode
= CERT_LIST_HEAD(platform_cert_list
);
7366 ss
->ssl3
.clientCertificate
= CERT_DupCertificate(certNode
->cert
);
7368 /* Setting ssl3.clientCertChain non-NULL will cause
7369 * ssl3_HandleServerHelloDone to call SendCertificate.
7370 * Note: clientCertChain should include the EE cert as
7371 * clientCertificate is ignored during the actual sending
7373 ss
->ssl3
.clientCertChain
=
7374 hack_NewCertificateListFromCertList(platform_cert_list
);
7375 CERT_DestroyCertList(platform_cert_list
);
7376 platform_cert_list
= NULL
;
7377 if (ss
->ssl3
.clientCertChain
== NULL
) {
7378 if (ss
->ssl3
.clientCertificate
!= NULL
) {
7379 CERT_DestroyCertificate(ss
->ssl3
.clientCertificate
);
7380 ss
->ssl3
.clientCertificate
= NULL
;
7382 if (ss
->ssl3
.platformClientKey
) {
7383 ssl_FreePlatformKey(ss
->ssl3
.platformClientKey
);
7384 ss
->ssl3
.platformClientKey
= (PlatformKey
)NULL
;
7386 goto send_no_certificate
;
7388 if (ss
->ssl3
.hs
.hashType
== handshake_hash_single
) {
7389 ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss
, &algorithms
);
7391 break; /* not an error */
7393 #endif /* NSS_PLATFORM_CLIENT_AUTH */
7394 /* check what the callback function returned */
7395 if ((!ss
->ssl3
.clientCertificate
) || (!ss
->ssl3
.clientPrivateKey
)) {
7396 /* we are missing either the key or cert */
7397 if (ss
->ssl3
.clientCertificate
) {
7398 /* got a cert, but no key - free it */
7399 CERT_DestroyCertificate(ss
->ssl3
.clientCertificate
);
7400 ss
->ssl3
.clientCertificate
= NULL
;
7402 if (ss
->ssl3
.clientPrivateKey
) {
7403 /* got a key, but no cert - free it */
7404 SECKEY_DestroyPrivateKey(ss
->ssl3
.clientPrivateKey
);
7405 ss
->ssl3
.clientPrivateKey
= NULL
;
7407 goto send_no_certificate
;
7409 /* Setting ssl3.clientCertChain non-NULL will cause
7410 * ssl3_HandleServerHelloDone to call SendCertificate.
7412 ss
->ssl3
.clientCertChain
= CERT_CertChainFromCert(
7413 ss
->ssl3
.clientCertificate
,
7414 certUsageSSLClient
, PR_FALSE
);
7415 if (ss
->ssl3
.clientCertChain
== NULL
) {
7416 CERT_DestroyCertificate(ss
->ssl3
.clientCertificate
);
7417 ss
->ssl3
.clientCertificate
= NULL
;
7418 SECKEY_DestroyPrivateKey(ss
->ssl3
.clientPrivateKey
);
7419 ss
->ssl3
.clientPrivateKey
= NULL
;
7420 goto send_no_certificate
;
7422 if (ss
->ssl3
.hs
.hashType
== handshake_hash_single
) {
7423 ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss
, &algorithms
);
7425 break; /* not an error */
7429 send_no_certificate
:
7431 ss
->ssl3
.sendEmptyCert
= PR_TRUE
;
7433 (void)SSL3_SendAlert(ss
, alert_warning
, no_certificate
);
7442 PORT_SetError(SEC_ERROR_NO_MEMORY
);
7446 if (isTLS
&& desc
== illegal_parameter
)
7447 desc
= decode_error
;
7448 (void)SSL3_SendAlert(ss
, alert_fatal
, desc
);
7450 PORT_SetError(errCode
);
7453 ss
->requestedCertTypes
= NULL
;
7455 PORT_FreeArena(arena
, PR_FALSE
);
7456 #ifdef NSS_PLATFORM_CLIENT_AUTH
7457 if (platform_cert_list
)
7458 CERT_DestroyCertList(platform_cert_list
);
7464 * attempt to restart the handshake after asynchronously handling
7465 * a request for the client's certificate.
7468 * cert Client cert chosen by application.
7469 * Note: ssl takes this reference, and does not bump the
7470 * reference count. The caller should drop its reference
7471 * without calling CERT_DestroyCert after calling this function.
7473 * key Private key associated with cert. This function takes
7474 * ownership of the private key, so the caller should drop its
7475 * reference without destroying the private key after this
7478 * certChain DER-encoded certs, client cert and its signers.
7479 * Note: ssl takes this reference, and does not copy the chain.
7480 * The caller should drop its reference without destroying the
7481 * chain. SSL will free the chain when it is done with it.
7485 * XXX This code only works on the initial handshake on a connection, XXX
7486 * It does not work on a subsequent handshake (redo).
7488 * Caller holds 1stHandshakeLock.
7491 ssl3_RestartHandshakeAfterCertReq(sslSocket
* ss
,
7492 CERTCertificate
* cert
,
7493 SECKEYPrivateKey
* key
,
7494 CERTCertificateList
*certChain
)
7496 SECStatus rv
= SECSuccess
;
7498 /* XXX This code only works on the initial handshake on a connection,
7499 ** XXX It does not work on a subsequent handshake (redo).
7501 if (ss
->handshake
!= 0) {
7502 ss
->handshake
= ssl_GatherRecord1stHandshake
;
7503 ss
->ssl3
.clientCertificate
= cert
;
7504 ss
->ssl3
.clientPrivateKey
= key
;
7505 ss
->ssl3
.clientCertChain
= certChain
;
7506 if (!cert
|| !key
|| !certChain
) {
7507 /* we are missing the key, cert, or cert chain */
7508 if (ss
->ssl3
.clientCertificate
) {
7509 CERT_DestroyCertificate(ss
->ssl3
.clientCertificate
);
7510 ss
->ssl3
.clientCertificate
= NULL
;
7512 if (ss
->ssl3
.clientPrivateKey
) {
7513 SECKEY_DestroyPrivateKey(ss
->ssl3
.clientPrivateKey
);
7514 ss
->ssl3
.clientPrivateKey
= NULL
;
7516 if (ss
->ssl3
.clientCertChain
!= NULL
) {
7517 CERT_DestroyCertificateList(ss
->ssl3
.clientCertChain
);
7518 ss
->ssl3
.clientCertChain
= NULL
;
7520 if (ss
->ssl3
.prSpec
->version
> SSL_LIBRARY_VERSION_3_0
) {
7521 ss
->ssl3
.sendEmptyCert
= PR_TRUE
;
7523 (void)SSL3_SendAlert(ss
, alert_warning
, no_certificate
);
7528 CERT_DestroyCertificate(cert
);
7531 SECKEY_DestroyPrivateKey(key
);
7534 CERT_DestroyCertificateList(certChain
);
7536 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
7543 ssl3_CheckFalseStart(sslSocket
*ss
)
7545 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
7546 PORT_Assert( !ss
->ssl3
.hs
.authCertificatePending
);
7547 PORT_Assert( !ss
->ssl3
.hs
.canFalseStart
);
7549 if (!ss
->canFalseStartCallback
) {
7550 SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start",
7551 SSL_GETPID(), ss
->fd
));
7553 PRBool maybeFalseStart
;
7556 /* An attacker can control the selected ciphersuite so we only wish to
7557 * do False Start in the case that the selected ciphersuite is
7558 * sufficiently strong that the attack can gain no advantage.
7559 * Therefore we always require an 80-bit cipher. */
7560 ssl_GetSpecReadLock(ss
);
7561 maybeFalseStart
= ss
->ssl3
.cwSpec
->cipher_def
->secret_key_size
>= 10;
7562 ssl_ReleaseSpecReadLock(ss
);
7564 if (!maybeFalseStart
) {
7565 SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher",
7566 SSL_GETPID(), ss
->fd
));
7568 rv
= (ss
->canFalseStartCallback
)(ss
->fd
,
7569 ss
->canFalseStartCallbackData
,
7570 &ss
->ssl3
.hs
.canFalseStart
);
7571 if (rv
== SECSuccess
) {
7572 SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s",
7573 SSL_GETPID(), ss
->fd
,
7574 ss
->ssl3
.hs
.canFalseStart
? "TRUE" : "FALSE"));
7576 SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)",
7577 SSL_GETPID(), ss
->fd
,
7578 PR_ErrorToName(PR_GetError())));
7584 ss
->ssl3
.hs
.canFalseStart
= PR_FALSE
;
7589 ssl3_WaitingForStartOfServerSecondRound(sslSocket
*ss
)
7593 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
7595 switch (ss
->ssl3
.hs
.ws
) {
7596 case wait_new_session_ticket
:
7599 case wait_change_cipher
:
7600 result
= !ssl3_ExtensionNegotiated(ss
, ssl_session_ticket_xtn
);
7610 static SECStatus
ssl3_SendClientSecondRound(sslSocket
*ss
);
7612 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7613 * ssl3 Server Hello Done message.
7614 * Caller must hold Handshake and RecvBuf locks.
7617 ssl3_HandleServerHelloDone(sslSocket
*ss
)
7620 SSL3WaitState ws
= ss
->ssl3
.hs
.ws
;
7622 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
7623 SSL_GETPID(), ss
->fd
));
7624 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
7625 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
7627 /* Skipping CertificateRequest is always permitted. */
7628 if (ws
!= wait_hello_done
&&
7629 ws
!= wait_cert_request
) {
7630 SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
7631 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE
);
7635 rv
= ssl3_SendClientSecondRound(ss
);
7640 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
7642 * Caller must hold Handshake and RecvBuf locks.
7645 ssl3_SendClientSecondRound(sslSocket
*ss
)
7648 PRBool sendClientCert
;
7650 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
7651 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
7653 sendClientCert
= !ss
->ssl3
.sendEmptyCert
&&
7654 ss
->ssl3
.clientCertChain
!= NULL
&&
7655 (ss
->ssl3
.platformClientKey
||
7656 ss
->ssl3
.clientPrivateKey
!= NULL
);
7658 if (!sendClientCert
&&
7659 ss
->ssl3
.hs
.hashType
== handshake_hash_single
&&
7660 ss
->ssl3
.hs
.backupHash
) {
7661 /* Don't need the backup handshake hash. */
7662 PK11_DestroyContext(ss
->ssl3
.hs
.backupHash
, PR_TRUE
);
7663 ss
->ssl3
.hs
.backupHash
= NULL
;
7666 /* We must wait for the server's certificate to be authenticated before
7667 * sending the client certificate in order to disclosing the client
7668 * certificate to an attacker that does not have a valid cert for the
7669 * domain we are connecting to.
7671 * XXX: We should do the same for the NPN extension, but for that we
7672 * need an option to give the application the ability to leak the NPN
7673 * information to get better performance.
7675 * During the initial handshake on a connection, we never send/receive
7676 * application data until we have authenticated the server's certificate;
7677 * i.e. we have fully authenticated the handshake before using the cipher
7678 * specs agreed upon for that handshake. During a renegotiation, we may
7679 * continue sending and receiving application data during the handshake
7680 * interleaved with the handshake records. If we were to send the client's
7681 * second round for a renegotiation before the server's certificate was
7682 * authenticated, then the application data sent/received after this point
7683 * would be using cipher spec that hadn't been authenticated. By waiting
7684 * until the server's certificate has been authenticated during
7685 * renegotiations, we ensure that renegotiations have the same property
7686 * as initial handshakes; i.e. we have fully authenticated the handshake
7687 * before using the cipher specs agreed upon for that handshake for
7690 if (ss
->ssl3
.hs
.restartTarget
) {
7691 PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
7692 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
7695 if (ss
->ssl3
.hs
.authCertificatePending
&&
7696 (sendClientCert
|| ss
->ssl3
.sendEmptyCert
|| ss
->firstHsDone
)) {
7697 SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"
7698 " certificate authentication is still pending.",
7699 SSL_GETPID(), ss
->fd
));
7700 ss
->ssl3
.hs
.restartTarget
= ssl3_SendClientSecondRound
;
7701 return SECWouldBlock
;
7704 ssl_GetXmitBufLock(ss
); /*******************************/
7706 if (ss
->ssl3
.sendEmptyCert
) {
7707 ss
->ssl3
.sendEmptyCert
= PR_FALSE
;
7708 rv
= ssl3_SendEmptyCertificate(ss
);
7709 /* Don't send verify */
7710 if (rv
!= SECSuccess
) {
7711 goto loser
; /* error code is set. */
7713 } else if (sendClientCert
) {
7714 rv
= ssl3_SendCertificate(ss
);
7715 if (rv
!= SECSuccess
) {
7716 goto loser
; /* error code is set. */
7720 rv
= ssl3_SendClientKeyExchange(ss
);
7721 if (rv
!= SECSuccess
) {
7722 goto loser
; /* err is set. */
7725 if (sendClientCert
) {
7726 rv
= ssl3_SendCertificateVerify(ss
);
7727 if (rv
!= SECSuccess
) {
7728 goto loser
; /* err is set. */
7732 rv
= ssl3_SendChangeCipherSpecs(ss
);
7733 if (rv
!= SECSuccess
) {
7734 goto loser
; /* err code was set. */
7737 /* This must be done after we've set ss->ssl3.cwSpec in
7738 * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information
7739 * from cwSpec. This must be done before we call ssl3_CheckFalseStart
7740 * because the false start callback (if any) may need the information from
7741 * the functions that depend on this being set.
7743 ss
->enoughFirstHsDone
= PR_TRUE
;
7745 if (!ss
->firstHsDone
) {
7746 /* XXX: If the server's certificate hasn't been authenticated by this
7747 * point, then we may be leaking this NPN message to an attacker.
7749 rv
= ssl3_SendNextProto(ss
);
7750 if (rv
!= SECSuccess
) {
7751 goto loser
; /* err code was set. */
7755 rv
= ssl3_SendEncryptedExtensions(ss
);
7756 if (rv
!= SECSuccess
) {
7757 goto loser
; /* err code was set. */
7760 if (!ss
->firstHsDone
) {
7761 if (ss
->opt
.enableFalseStart
) {
7762 if (!ss
->ssl3
.hs
.authCertificatePending
) {
7763 /* When we fix bug 589047, we will need to know whether we are
7764 * false starting before we try to flush the client second
7765 * round to the network. With that in mind, we purposefully
7766 * call ssl3_CheckFalseStart before calling ssl3_SendFinished,
7767 * which includes a call to ssl3_FlushHandshake, so that
7768 * no application develops a reliance on such flushing being
7769 * done before its false start callback is called.
7771 ssl_ReleaseXmitBufLock(ss
);
7772 rv
= ssl3_CheckFalseStart(ss
);
7773 ssl_GetXmitBufLock(ss
);
7774 if (rv
!= SECSuccess
) {
7778 /* The certificate authentication and the server's Finished
7779 * message are racing each other. If the certificate
7780 * authentication wins, then we will try to false start in
7781 * ssl3_AuthCertificateComplete.
7783 SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because"
7784 " certificate authentication is still pending.",
7785 SSL_GETPID(), ss
->fd
));
7790 rv
= ssl3_SendFinished(ss
, 0);
7791 if (rv
!= SECSuccess
) {
7792 goto loser
; /* err code was set. */
7795 ssl_ReleaseXmitBufLock(ss
); /*******************************/
7797 if (!ss
->ssl3
.hs
.isResuming
&&
7798 ssl3_ExtensionNegotiated(ss
, ssl_channel_id_xtn
)) {
7799 /* If we are negotiating ChannelID on a full handshake then we record
7800 * the handshake hashes in |sid| at this point. They will be needed in
7801 * the event that we resume this session and use ChannelID on the
7802 * resumption handshake. */
7804 SECItem
*originalHandshakeHash
=
7805 &ss
->sec
.ci
.sid
->u
.ssl3
.originalHandshakeHash
;
7806 PORT_Assert(ss
->sec
.ci
.sid
->cached
== never_cached
);
7808 ssl_GetSpecReadLock(ss
);
7809 PORT_Assert(ss
->version
> SSL_LIBRARY_VERSION_3_0
);
7810 rv
= ssl3_ComputeHandshakeHashes(ss
, ss
->ssl3
.cwSpec
, &hashes
, 0);
7811 ssl_ReleaseSpecReadLock(ss
);
7812 if (rv
!= SECSuccess
) {
7816 PORT_Assert(originalHandshakeHash
->len
== 0);
7817 originalHandshakeHash
->data
= PORT_Alloc(hashes
.len
);
7818 if (!originalHandshakeHash
->data
)
7820 originalHandshakeHash
->len
= hashes
.len
;
7821 memcpy(originalHandshakeHash
->data
, hashes
.u
.raw
, hashes
.len
);
7824 if (ssl3_ExtensionNegotiated(ss
, ssl_session_ticket_xtn
))
7825 ss
->ssl3
.hs
.ws
= wait_new_session_ticket
;
7827 ss
->ssl3
.hs
.ws
= wait_change_cipher
;
7829 PORT_Assert(ssl3_WaitingForStartOfServerSecondRound(ss
));
7834 ssl_ReleaseXmitBufLock(ss
);
7839 * Routines used by servers
7842 ssl3_SendHelloRequest(sslSocket
*ss
)
7846 SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
7849 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
7850 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
7852 rv
= ssl3_AppendHandshakeHeader(ss
, hello_request
, 0);
7853 if (rv
!= SECSuccess
) {
7854 return rv
; /* err set by AppendHandshake */
7856 rv
= ssl3_FlushHandshake(ss
, 0);
7857 if (rv
!= SECSuccess
) {
7858 return rv
; /* error code set by ssl3_FlushHandshake */
7860 ss
->ssl3
.hs
.ws
= wait_client_hello
;
7866 * ssl3_HandleClientHello()
7868 static SECComparison
7869 ssl3_ServerNameCompare(const SECItem
*name1
, const SECItem
*name2
)
7871 if (!name1
!= !name2
) {
7877 if (name1
->type
!= name2
->type
) {
7880 return SECITEM_CompareItem(name1
, name2
);
7883 /* Sets memory error when returning NULL.
7885 * ssl3_SendClientHello()
7886 * ssl3_HandleServerHello()
7887 * ssl3_HandleClientHello()
7888 * ssl3_HandleV2ClientHello()
7891 ssl3_NewSessionID(sslSocket
*ss
, PRBool is_server
)
7895 sid
= PORT_ZNew(sslSessionID
);
7900 const SECItem
* srvName
;
7901 SECStatus rv
= SECSuccess
;
7903 ssl_GetSpecReadLock(ss
); /********************************/
7904 srvName
= &ss
->ssl3
.prSpec
->srvVirtName
;
7905 if (srvName
->len
&& srvName
->data
) {
7906 rv
= SECITEM_CopyItem(NULL
, &sid
->u
.ssl3
.srvName
, srvName
);
7908 ssl_ReleaseSpecReadLock(ss
); /************************************/
7909 if (rv
!= SECSuccess
) {
7914 sid
->peerID
= (ss
->peerID
== NULL
) ? NULL
: PORT_Strdup(ss
->peerID
);
7915 sid
->urlSvrName
= (ss
->url
== NULL
) ? NULL
: PORT_Strdup(ss
->url
);
7916 sid
->addr
= ss
->sec
.ci
.peer
;
7917 sid
->port
= ss
->sec
.ci
.port
;
7918 sid
->references
= 1;
7919 sid
->cached
= never_cached
;
7920 sid
->version
= ss
->version
;
7922 sid
->u
.ssl3
.keys
.resumable
= PR_TRUE
;
7923 sid
->u
.ssl3
.policy
= SSL_ALLOWED
;
7924 sid
->u
.ssl3
.clientWriteKey
= NULL
;
7925 sid
->u
.ssl3
.serverWriteKey
= NULL
;
7929 int pid
= SSL_GETPID();
7931 sid
->u
.ssl3
.sessionIDLength
= SSL3_SESSIONID_BYTES
;
7932 sid
->u
.ssl3
.sessionID
[0] = (pid
>> 8) & 0xff;
7933 sid
->u
.ssl3
.sessionID
[1] = pid
& 0xff;
7934 rv
= PK11_GenerateRandom(sid
->u
.ssl3
.sessionID
+ 2,
7935 SSL3_SESSIONID_BYTES
-2);
7936 if (rv
!= SECSuccess
) {
7938 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE
);
7945 /* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
7947 ssl3_SendServerHelloSequence(sslSocket
*ss
)
7949 const ssl3KEADef
*kea_def
;
7952 SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
7953 SSL_GETPID(), ss
->fd
));
7955 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
7956 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
7958 rv
= ssl3_SendServerHello(ss
);
7959 if (rv
!= SECSuccess
) {
7960 return rv
; /* err code is set. */
7962 rv
= ssl3_SendCertificate(ss
);
7963 if (rv
!= SECSuccess
) {
7964 return rv
; /* error code is set. */
7966 rv
= ssl3_SendCertificateStatus(ss
);
7967 if (rv
!= SECSuccess
) {
7968 return rv
; /* error code is set. */
7970 /* We have to do this after the call to ssl3_SendServerHello,
7971 * because kea_def is set up by ssl3_SendServerHello().
7973 kea_def
= ss
->ssl3
.hs
.kea_def
;
7974 ss
->ssl3
.hs
.usedStepDownKey
= PR_FALSE
;
7976 if (kea_def
->is_limited
&& kea_def
->exchKeyType
== kt_rsa
) {
7977 /* see if we can legally use the key in the cert. */
7978 int keyLen
; /* bytes */
7980 keyLen
= PK11_GetPrivateModulusLen(
7981 ss
->serverCerts
[kea_def
->exchKeyType
].SERVERKEY
);
7984 keyLen
* BPB
<= kea_def
->key_size_limit
) {
7985 /* XXX AND cert is not signing only!! */
7986 /* just fall through and use it. */
7987 } else if (ss
->stepDownKeyPair
!= NULL
) {
7988 ss
->ssl3
.hs
.usedStepDownKey
= PR_TRUE
;
7989 rv
= ssl3_SendServerKeyExchange(ss
);
7990 if (rv
!= SECSuccess
) {
7991 return rv
; /* err code was set. */
7994 #ifndef HACKED_EXPORT_SERVER
7995 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED
);
7999 } else if (kea_def
->ephemeral
) {
8000 rv
= ssl3_SendServerKeyExchange(ss
);
8001 if (rv
!= SECSuccess
) {
8002 return rv
; /* err code was set. */
8006 if (ss
->opt
.requestCertificate
) {
8007 rv
= ssl3_SendCertificateRequest(ss
);
8008 if (rv
!= SECSuccess
) {
8009 return rv
; /* err code is set. */
8012 rv
= ssl3_SendServerHelloDone(ss
);
8013 if (rv
!= SECSuccess
) {
8014 return rv
; /* err code is set. */
8017 ss
->ssl3
.hs
.ws
= (ss
->opt
.requestCertificate
) ? wait_client_cert
8022 /* An empty TLS Renegotiation Info (RI) extension */
8023 static const PRUint8 emptyRIext
[5] = {0xff, 0x01, 0x00, 0x01, 0x00};
8025 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
8026 * ssl3 Client Hello message.
8027 * Caller must hold Handshake and RecvBuf locks.
8030 ssl3_HandleClientHello(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
8032 sslSessionID
* sid
= NULL
;
8037 int errCode
= SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
;
8038 SSL3AlertDescription desc
= illegal_parameter
;
8039 SSL3AlertLevel level
= alert_fatal
;
8040 SSL3ProtocolVersion version
;
8041 SECItem sidBytes
= {siBuffer
, NULL
, 0};
8042 SECItem cookieBytes
= {siBuffer
, NULL
, 0};
8043 SECItem suites
= {siBuffer
, NULL
, 0};
8044 SECItem comps
= {siBuffer
, NULL
, 0};
8045 PRBool haveSpecWriteLock
= PR_FALSE
;
8046 PRBool haveXmitBufLock
= PR_FALSE
;
8048 SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
8049 SSL_GETPID(), ss
->fd
));
8051 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
8052 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
8053 PORT_Assert( ss
->ssl3
.initialized
);
8055 if (!ss
->sec
.isServer
||
8056 (ss
->ssl3
.hs
.ws
!= wait_client_hello
&&
8057 ss
->ssl3
.hs
.ws
!= idle_handshake
)) {
8058 desc
= unexpected_message
;
8059 errCode
= SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO
;
8062 if (ss
->ssl3
.hs
.ws
== idle_handshake
&&
8063 ss
->opt
.enableRenegotiation
== SSL_RENEGOTIATE_NEVER
) {
8064 desc
= no_renegotiation
;
8065 level
= alert_warning
;
8066 errCode
= SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
;
8070 /* Get peer name of client */
8071 rv
= ssl_GetPeerInfo(ss
);
8072 if (rv
!= SECSuccess
) {
8073 return rv
; /* error code is set. */
8076 /* Clearing the handshake pointers so that ssl_Do1stHandshake won't
8077 * call ssl2_HandleMessage.
8079 * The issue here is that TLS ordinarily starts out in
8080 * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility
8081 * code paths. That function zeroes these next pointers. But with DTLS,
8082 * we don't even try to do the v2 ClientHello so we skip that function
8083 * and need to reset these values here.
8086 ss
->nextHandshake
= 0;
8087 ss
->securityHandshake
= 0;
8090 /* We might be starting session renegotiation in which case we should
8091 * clear previous state.
8093 PORT_Memset(&ss
->xtnData
, 0, sizeof(TLSExtensionData
));
8094 ss
->statelessResume
= PR_FALSE
;
8097 dtls_RehandshakeCleanup(ss
);
8100 tmp
= ssl3_ConsumeHandshakeNumber(ss
, 2, &b
, &length
);
8102 goto loser
; /* malformed, alert already sent */
8104 /* Translate the version */
8106 ss
->clientHelloVersion
= version
=
8107 dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion
)tmp
);
8109 ss
->clientHelloVersion
= version
= (SSL3ProtocolVersion
)tmp
;
8112 rv
= ssl3_NegotiateVersion(ss
, version
, PR_TRUE
);
8113 if (rv
!= SECSuccess
) {
8114 desc
= (version
> SSL_LIBRARY_VERSION_3_0
) ? protocol_version
8115 : handshake_failure
;
8116 errCode
= SSL_ERROR_UNSUPPORTED_VERSION
;
8120 rv
= ssl3_InitHandshakeHashes(ss
);
8121 if (rv
!= SECSuccess
) {
8122 desc
= internal_error
;
8123 errCode
= PORT_GetError();
8127 /* grab the client random data. */
8128 rv
= ssl3_ConsumeHandshake(
8129 ss
, &ss
->ssl3
.hs
.client_random
, SSL3_RANDOM_LENGTH
, &b
, &length
);
8130 if (rv
!= SECSuccess
) {
8131 goto loser
; /* malformed */
8134 /* grab the client's SID, if present. */
8135 rv
= ssl3_ConsumeHandshakeVariable(ss
, &sidBytes
, 1, &b
, &length
);
8136 if (rv
!= SECSuccess
) {
8137 goto loser
; /* malformed */
8140 /* grab the client's cookie, if present. */
8142 rv
= ssl3_ConsumeHandshakeVariable(ss
, &cookieBytes
, 1, &b
, &length
);
8143 if (rv
!= SECSuccess
) {
8144 goto loser
; /* malformed */
8148 /* grab the list of cipher suites. */
8149 rv
= ssl3_ConsumeHandshakeVariable(ss
, &suites
, 2, &b
, &length
);
8150 if (rv
!= SECSuccess
) {
8151 goto loser
; /* malformed */
8154 /* If the ClientHello version is less than our maximum version, check for a
8155 * TLS_FALLBACK_SCSV and reject the connection if found. */
8156 if (ss
->vrange
.max
> ss
->clientHelloVersion
) {
8157 for (i
= 0; i
+ 1 < suites
.len
; i
+= 2) {
8158 PRUint16 suite_i
= (suites
.data
[i
] << 8) | suites
.data
[i
+ 1];
8159 if (suite_i
!= TLS_FALLBACK_SCSV
)
8161 desc
= inappropriate_fallback
;
8162 errCode
= SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT
;
8167 /* grab the list of compression methods. */
8168 rv
= ssl3_ConsumeHandshakeVariable(ss
, &comps
, 1, &b
, &length
);
8169 if (rv
!= SECSuccess
) {
8170 goto loser
; /* malformed */
8173 /* TLS 1.3 requires that compression be empty */
8174 if (ss
->version
>= SSL_LIBRARY_VERSION_TLS_1_3
) {
8175 if (comps
.len
!= 1 || comps
.data
[0] != ssl_compression_null
) {
8179 desc
= handshake_failure
;
8181 /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
8182 * we are restarting a previous session until extensions have been
8183 * parsed, since we might have received a SessionTicket extension.
8184 * Note: we allow extensions even when negotiating SSL3 for the sake
8185 * of interoperability (and backwards compatibility).
8189 /* Get length of hello extensions */
8190 PRInt32 extension_length
;
8191 extension_length
= ssl3_ConsumeHandshakeNumber(ss
, 2, &b
, &length
);
8192 if (extension_length
< 0) {
8193 goto loser
; /* alert already sent */
8195 if (extension_length
!= length
) {
8196 ssl3_DecodeError(ss
); /* send alert */
8199 rv
= ssl3_HandleHelloExtensions(ss
, &b
, &length
);
8200 if (rv
!= SECSuccess
) {
8201 goto loser
; /* malformed */
8204 if (!ssl3_ExtensionNegotiated(ss
, ssl_renegotiation_info_xtn
)) {
8205 /* If we didn't receive an RI extension, look for the SCSV,
8206 * and if found, treat it just like an empty RI extension
8207 * by processing a local copy of an empty RI extension.
8209 for (i
= 0; i
+ 1 < suites
.len
; i
+= 2) {
8210 PRUint16 suite_i
= (suites
.data
[i
] << 8) | suites
.data
[i
+ 1];
8211 if (suite_i
== TLS_EMPTY_RENEGOTIATION_INFO_SCSV
) {
8212 SSL3Opaque
* b2
= (SSL3Opaque
*)emptyRIext
;
8213 PRUint32 L2
= sizeof emptyRIext
;
8214 (void)ssl3_HandleHelloExtensions(ss
, &b2
, &L2
);
8219 if (ss
->firstHsDone
&&
8220 (ss
->opt
.enableRenegotiation
== SSL_RENEGOTIATE_REQUIRES_XTN
||
8221 ss
->opt
.enableRenegotiation
== SSL_RENEGOTIATE_TRANSITIONAL
) &&
8222 !ssl3_ExtensionNegotiated(ss
, ssl_renegotiation_info_xtn
)) {
8223 desc
= no_renegotiation
;
8224 level
= alert_warning
;
8225 errCode
= SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
;
8228 if ((ss
->opt
.requireSafeNegotiation
||
8229 (ss
->firstHsDone
&& ss
->peerRequestedProtection
)) &&
8230 !ssl3_ExtensionNegotiated(ss
, ssl_renegotiation_info_xtn
)) {
8231 desc
= handshake_failure
;
8232 errCode
= SSL_ERROR_UNSAFE_NEGOTIATION
;
8236 /* We do stateful resumes only if either of the following
8237 * conditions are satisfied: (1) the client does not support the
8238 * session ticket extension, or (2) the client support the session
8239 * ticket extension, but sent an empty ticket.
8241 if (!ssl3_ExtensionNegotiated(ss
, ssl_session_ticket_xtn
) ||
8242 ss
->xtnData
.emptySessionTicket
) {
8243 if (sidBytes
.len
> 0 && !ss
->opt
.noCache
) {
8244 SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
8245 SSL_GETPID(), ss
->fd
, ss
->sec
.ci
.peer
.pr_s6_addr32
[0],
8246 ss
->sec
.ci
.peer
.pr_s6_addr32
[1],
8247 ss
->sec
.ci
.peer
.pr_s6_addr32
[2],
8248 ss
->sec
.ci
.peer
.pr_s6_addr32
[3]));
8249 if (ssl_sid_lookup
) {
8250 sid
= (*ssl_sid_lookup
)(&ss
->sec
.ci
.peer
, sidBytes
.data
,
8251 sidBytes
.len
, ss
->dbHandle
);
8253 errCode
= SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED
;
8257 } else if (ss
->statelessResume
) {
8258 /* Fill in the client's session ID if doing a stateless resume.
8259 * (When doing stateless resumes, server echos client's SessionID.)
8261 sid
= ss
->sec
.ci
.sid
;
8262 PORT_Assert(sid
!= NULL
); /* Should have already been filled in.*/
8264 if (sidBytes
.len
> 0 && sidBytes
.len
<= SSL3_SESSIONID_BYTES
) {
8265 sid
->u
.ssl3
.sessionIDLength
= sidBytes
.len
;
8266 PORT_Memcpy(sid
->u
.ssl3
.sessionID
, sidBytes
.data
,
8268 sid
->u
.ssl3
.sessionIDLength
= sidBytes
.len
;
8270 sid
->u
.ssl3
.sessionIDLength
= 0;
8272 ss
->sec
.ci
.sid
= NULL
;
8275 /* We only send a session ticket extension if the client supports
8276 * the extension and we are unable to do either a stateful or
8279 * TODO: send a session ticket if performing a stateful
8280 * resumption. (As per RFC4507, a server may issue a session
8281 * ticket while doing a (stateless or stateful) session resume,
8282 * but OpenSSL-0.9.8g does not accept session tickets while
8285 if (ssl3_ExtensionNegotiated(ss
, ssl_session_ticket_xtn
) && sid
== NULL
) {
8286 ssl3_RegisterServerHelloExtensionSender(ss
,
8287 ssl_session_ticket_xtn
, ssl3_SendSessionTicketXtn
);
8291 /* We've found a session cache entry for this client.
8292 * Now, if we're going to require a client-auth cert,
8293 * and we don't already have this client's cert in the session cache,
8294 * and this is the first handshake on this connection (not a redo),
8295 * then drop this old cache entry and start a new session.
8297 if ((sid
->peerCert
== NULL
) && ss
->opt
.requestCertificate
&&
8298 ((ss
->opt
.requireCertificate
== SSL_REQUIRE_ALWAYS
) ||
8299 (ss
->opt
.requireCertificate
== SSL_REQUIRE_NO_ERROR
) ||
8300 ((ss
->opt
.requireCertificate
== SSL_REQUIRE_FIRST_HANDSHAKE
)
8301 && !ss
->firstHsDone
))) {
8303 SSL_AtomicIncrementLong(& ssl3stats
.hch_sid_cache_not_ok
);
8304 if (ss
->sec
.uncache
)
8305 ss
->sec
.uncache(sid
);
8311 #ifndef NSS_DISABLE_ECC
8312 /* Disable any ECC cipher suites for which we have no cert. */
8313 ssl3_FilterECCipherSuitesByServerCerts(ss
);
8317 ssl3_DisableNonDTLSSuites(ss
);
8320 if (!ssl3_HasGCMSupport()) {
8321 ssl3_DisableGCMSuites(ss
);
8325 /* Look for a matching cipher suite. */
8326 j
= ssl3_config_match_init(ss
);
8327 if (j
<= 0) { /* no ciphers are working/supported by PK11 */
8328 errCode
= PORT_GetError(); /* error code is already set. */
8333 /* If we already have a session for this client, be sure to pick the
8334 ** same cipher suite and compression method we picked before.
8335 ** This is not a loop, despite appearances.
8338 ssl3CipherSuiteCfg
*suite
;
8340 SSLVersionRange vrange
= {ss
->version
, ss
->version
};
8343 /* Check that the cached compression method is still enabled. */
8344 if (!compressionEnabled(ss
, sid
->u
.ssl3
.compression
))
8347 /* Check that the cached compression method is in the client's list */
8348 for (i
= 0; i
< comps
.len
; i
++) {
8349 if (comps
.data
[i
] == sid
->u
.ssl3
.compression
)
8355 suite
= ss
->cipherSuites
;
8356 /* Find the entry for the cipher suite used in the cached session. */
8357 for (j
= ssl_V3_SUITES_IMPLEMENTED
; j
> 0; --j
, ++suite
) {
8358 if (suite
->cipher_suite
== sid
->u
.ssl3
.cipherSuite
)
8365 /* Double check that the cached cipher suite is still enabled,
8366 * implemented, and allowed by policy. Might have been disabled.
8367 * The product policy won't change during the process lifetime.
8368 * Implemented ("isPresent") shouldn't change for servers.
8370 if (!config_match(suite
, ss
->ssl3
.policy
, PR_TRUE
, &vrange
))
8373 if (!suite
->enabled
)
8376 /* Double check that the cached cipher suite is in the client's list */
8377 for (i
= 0; i
+ 1 < suites
.len
; i
+= 2) {
8378 PRUint16 suite_i
= (suites
.data
[i
] << 8) | suites
.data
[i
+ 1];
8379 if (suite_i
== suite
->cipher_suite
) {
8380 ss
->ssl3
.hs
.cipher_suite
= suite
->cipher_suite
;
8381 ss
->ssl3
.hs
.suite_def
=
8382 ssl_LookupCipherSuiteDef(ss
->ssl3
.hs
.cipher_suite
);
8384 /* Use the cached compression method. */
8385 ss
->ssl3
.hs
.compression
= sid
->u
.ssl3
.compression
;
8386 goto compression_found
;
8391 /* START A NEW SESSION */
8394 /* Look for a matching cipher suite. */
8395 j
= ssl3_config_match_init(ss
);
8396 if (j
<= 0) { /* no ciphers are working/supported by PK11 */
8397 errCode
= PORT_GetError(); /* error code is already set. */
8402 /* Select a cipher suite.
8404 ** NOTE: This suite selection algorithm should be the same as the one in
8405 ** ssl3_HandleV2ClientHello().
8407 ** If TLS 1.0 is enabled, we could handle the case where the client
8408 ** offered TLS 1.1 but offered only export cipher suites by choosing TLS
8409 ** 1.0 and selecting one of those export cipher suites. However, a secure
8410 ** TLS 1.1 client should not have export cipher suites enabled at all,
8411 ** and a TLS 1.1 client should definitely not be offering *only* export
8412 ** cipher suites. Therefore, we refuse to negotiate export cipher suites
8413 ** with any client that indicates support for TLS 1.1 or higher when we
8414 ** (the server) have TLS 1.1 support enabled.
8416 for (j
= 0; j
< ssl_V3_SUITES_IMPLEMENTED
; j
++) {
8417 ssl3CipherSuiteCfg
*suite
= &ss
->cipherSuites
[j
];
8418 SSLVersionRange vrange
= {ss
->version
, ss
->version
};
8419 if (!config_match(suite
, ss
->ssl3
.policy
, PR_TRUE
, &vrange
)) {
8422 for (i
= 0; i
+ 1 < suites
.len
; i
+= 2) {
8423 PRUint16 suite_i
= (suites
.data
[i
] << 8) | suites
.data
[i
+ 1];
8424 if (suite_i
== suite
->cipher_suite
) {
8425 ss
->ssl3
.hs
.cipher_suite
= suite
->cipher_suite
;
8426 ss
->ssl3
.hs
.suite_def
=
8427 ssl_LookupCipherSuiteDef(ss
->ssl3
.hs
.cipher_suite
);
8432 errCode
= SSL_ERROR_NO_CYPHER_OVERLAP
;
8436 /* Select a compression algorithm. */
8437 for (i
= 0; i
< comps
.len
; i
++) {
8438 if (!compressionEnabled(ss
, comps
.data
[i
]))
8440 for (j
= 0; j
< compressionMethodsCount
; j
++) {
8441 if (comps
.data
[i
] == compressions
[j
]) {
8442 ss
->ssl3
.hs
.compression
=
8443 (SSLCompressionMethod
)compressions
[j
];
8444 goto compression_found
;
8448 errCode
= SSL_ERROR_NO_COMPRESSION_OVERLAP
;
8449 /* null compression must be supported */
8456 ss
->sec
.send
= ssl3_SendApplicationData
;
8458 /* If there are any failures while processing the old sid,
8459 * we don't consider them to be errors. Instead, We just behave
8460 * as if the client had sent us no sid to begin with, and make a new one.
8462 if (sid
!= NULL
) do {
8463 ssl3CipherSpec
*pwSpec
;
8464 SECItem wrappedMS
; /* wrapped key */
8466 if (sid
->version
!= ss
->version
||
8467 sid
->u
.ssl3
.cipherSuite
!= ss
->ssl3
.hs
.cipher_suite
||
8468 sid
->u
.ssl3
.compression
!= ss
->ssl3
.hs
.compression
) {
8469 break; /* not an error */
8472 if (ss
->sec
.ci
.sid
) {
8473 if (ss
->sec
.uncache
)
8474 ss
->sec
.uncache(ss
->sec
.ci
.sid
);
8475 PORT_Assert(ss
->sec
.ci
.sid
!= sid
); /* should be impossible, but ... */
8476 if (ss
->sec
.ci
.sid
!= sid
) {
8477 ssl_FreeSID(ss
->sec
.ci
.sid
);
8479 ss
->sec
.ci
.sid
= NULL
;
8481 /* we need to resurrect the master secret.... */
8483 ssl_GetSpecWriteLock(ss
); haveSpecWriteLock
= PR_TRUE
;
8484 pwSpec
= ss
->ssl3
.pwSpec
;
8485 if (sid
->u
.ssl3
.keys
.msIsWrapped
) {
8486 PK11SymKey
* wrapKey
; /* wrapping key */
8487 CK_FLAGS keyFlags
= 0;
8488 #ifndef NO_PKCS11_BYPASS
8489 if (ss
->opt
.bypassPKCS11
) {
8490 /* we cannot restart a non-bypass session in a
8497 wrapKey
= getWrappingKey(ss
, NULL
, sid
->u
.ssl3
.exchKeyType
,
8498 sid
->u
.ssl3
.masterWrapMech
,
8501 /* we have a SID cache entry, but no wrapping key for it??? */
8505 if (ss
->version
> SSL_LIBRARY_VERSION_3_0
) { /* isTLS */
8506 keyFlags
= CKF_SIGN
| CKF_VERIFY
;
8509 wrappedMS
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
8510 wrappedMS
.len
= sid
->u
.ssl3
.keys
.wrapped_master_secret_len
;
8512 /* unwrap the master secret. */
8513 pwSpec
->master_secret
=
8514 PK11_UnwrapSymKeyWithFlags(wrapKey
, sid
->u
.ssl3
.masterWrapMech
,
8515 NULL
, &wrappedMS
, CKM_SSL3_MASTER_KEY_DERIVE
,
8516 CKA_DERIVE
, sizeof(SSL3MasterSecret
), keyFlags
);
8517 PK11_FreeSymKey(wrapKey
);
8518 if (pwSpec
->master_secret
== NULL
) {
8519 break; /* not an error */
8521 #ifndef NO_PKCS11_BYPASS
8522 } else if (ss
->opt
.bypassPKCS11
) {
8523 wrappedMS
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
8524 wrappedMS
.len
= sid
->u
.ssl3
.keys
.wrapped_master_secret_len
;
8525 memcpy(pwSpec
->raw_master_secret
, wrappedMS
.data
, wrappedMS
.len
);
8526 pwSpec
->msItem
.data
= pwSpec
->raw_master_secret
;
8527 pwSpec
->msItem
.len
= wrappedMS
.len
;
8530 /* We CAN restart a bypass session in a non-bypass socket. */
8531 /* need to import the raw master secret to session object */
8532 PK11SlotInfo
* slot
;
8533 wrappedMS
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
8534 wrappedMS
.len
= sid
->u
.ssl3
.keys
.wrapped_master_secret_len
;
8535 slot
= PK11_GetInternalSlot();
8536 pwSpec
->master_secret
=
8537 PK11_ImportSymKey(slot
, CKM_SSL3_MASTER_KEY_DERIVE
,
8538 PK11_OriginUnwrap
, CKA_ENCRYPT
, &wrappedMS
,
8540 PK11_FreeSlot(slot
);
8541 if (pwSpec
->master_secret
== NULL
) {
8542 break; /* not an error */
8545 ss
->sec
.ci
.sid
= sid
;
8546 if (sid
->peerCert
!= NULL
) {
8547 ss
->sec
.peerCert
= CERT_DupCertificate(sid
->peerCert
);
8548 ssl3_CopyPeerCertsFromSID(ss
, sid
);
8552 * Old SID passed all tests, so resume this old session.
8554 * XXX make sure compression still matches
8556 SSL_AtomicIncrementLong(& ssl3stats
.hch_sid_cache_hits
);
8557 if (ss
->statelessResume
)
8558 SSL_AtomicIncrementLong(& ssl3stats
.hch_sid_stateless_resumes
);
8559 ss
->ssl3
.hs
.isResuming
= PR_TRUE
;
8561 ss
->sec
.authAlgorithm
= sid
->authAlgorithm
;
8562 ss
->sec
.authKeyBits
= sid
->authKeyBits
;
8563 ss
->sec
.keaType
= sid
->keaType
;
8564 ss
->sec
.keaKeyBits
= sid
->keaKeyBits
;
8566 /* server sids don't remember the server cert we previously sent,
8567 ** but they do remember the kea type we originally used, so we
8568 ** can locate it again, provided that the current ssl socket
8569 ** has had its server certs configured the same as the previous one.
8572 CERT_DupCertificate(ss
->serverCerts
[sid
->keaType
].serverCert
);
8574 /* Copy cached name in to pending spec */
8576 sid
->version
> SSL_LIBRARY_VERSION_3_0
&&
8577 sid
->u
.ssl3
.srvName
.len
&& sid
->u
.ssl3
.srvName
.data
) {
8578 /* Set server name from sid */
8579 SECItem
*sidName
= &sid
->u
.ssl3
.srvName
;
8580 SECItem
*pwsName
= &ss
->ssl3
.pwSpec
->srvVirtName
;
8581 if (pwsName
->data
) {
8582 SECITEM_FreeItem(pwsName
, PR_FALSE
);
8584 rv
= SECITEM_CopyItem(NULL
, pwsName
, sidName
);
8585 if (rv
!= SECSuccess
) {
8586 errCode
= PORT_GetError();
8587 desc
= internal_error
;
8592 /* Clean up sni name array */
8593 if (ssl3_ExtensionNegotiated(ss
, ssl_server_name_xtn
) &&
8594 ss
->xtnData
.sniNameArr
) {
8595 PORT_Free(ss
->xtnData
.sniNameArr
);
8596 ss
->xtnData
.sniNameArr
= NULL
;
8597 ss
->xtnData
.sniNameArrSize
= 0;
8600 ssl_GetXmitBufLock(ss
); haveXmitBufLock
= PR_TRUE
;
8602 rv
= ssl3_SendServerHello(ss
);
8603 if (rv
!= SECSuccess
) {
8604 errCode
= PORT_GetError();
8608 if (haveSpecWriteLock
) {
8609 ssl_ReleaseSpecWriteLock(ss
);
8610 haveSpecWriteLock
= PR_FALSE
;
8613 /* NULL value for PMS signifies re-use of the old MS */
8614 rv
= ssl3_InitPendingCipherSpec(ss
, NULL
);
8615 if (rv
!= SECSuccess
) {
8616 errCode
= PORT_GetError();
8620 rv
= ssl3_SendChangeCipherSpecs(ss
);
8621 if (rv
!= SECSuccess
) {
8622 errCode
= PORT_GetError();
8625 rv
= ssl3_SendFinished(ss
, 0);
8626 ss
->ssl3
.hs
.ws
= wait_change_cipher
;
8627 if (rv
!= SECSuccess
) {
8628 errCode
= PORT_GetError();
8632 if (haveXmitBufLock
) {
8633 ssl_ReleaseXmitBufLock(ss
);
8634 haveXmitBufLock
= PR_FALSE
;
8640 if (haveSpecWriteLock
) {
8641 ssl_ReleaseSpecWriteLock(ss
);
8642 haveSpecWriteLock
= PR_FALSE
;
8645 if (sid
) { /* we had a sid, but it's no longer valid, free it */
8646 SSL_AtomicIncrementLong(& ssl3stats
.hch_sid_cache_not_ok
);
8647 if (ss
->sec
.uncache
)
8648 ss
->sec
.uncache(sid
);
8652 SSL_AtomicIncrementLong(& ssl3stats
.hch_sid_cache_misses
);
8654 if (ssl3_ExtensionNegotiated(ss
, ssl_server_name_xtn
)) {
8656 if (ss
->sniSocketConfig
) do { /* not a loop */
8657 ret
= SSL_SNI_SEND_ALERT
;
8658 /* If extension is negotiated, the len of names should > 0. */
8659 if (ss
->xtnData
.sniNameArrSize
) {
8660 /* Calling client callback to reconfigure the socket. */
8661 ret
= (SECStatus
)(*ss
->sniSocketConfig
)(ss
->fd
,
8662 ss
->xtnData
.sniNameArr
,
8663 ss
->xtnData
.sniNameArrSize
,
8664 ss
->sniSocketConfigArg
);
8666 if (ret
<= SSL_SNI_SEND_ALERT
) {
8667 /* Application does not know the name or was not able to
8668 * properly reconfigure the socket. */
8669 errCode
= SSL_ERROR_UNRECOGNIZED_NAME_ALERT
;
8670 desc
= unrecognized_name
;
8672 } else if (ret
== SSL_SNI_CURRENT_CONFIG_IS_USED
) {
8673 SECStatus rv
= SECSuccess
;
8674 SECItem
* cwsName
, *pwsName
;
8676 ssl_GetSpecWriteLock(ss
); /*******************************/
8677 pwsName
= &ss
->ssl3
.pwSpec
->srvVirtName
;
8678 cwsName
= &ss
->ssl3
.cwSpec
->srvVirtName
;
8679 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
8680 /* not allow name change on the 2d HS */
8681 if (ss
->firstHsDone
) {
8682 if (ssl3_ServerNameCompare(pwsName
, cwsName
)) {
8683 ssl_ReleaseSpecWriteLock(ss
); /******************/
8684 errCode
= SSL_ERROR_UNRECOGNIZED_NAME_ALERT
;
8685 desc
= handshake_failure
;
8686 ret
= SSL_SNI_SEND_ALERT
;
8691 if (pwsName
->data
) {
8692 SECITEM_FreeItem(pwsName
, PR_FALSE
);
8694 if (cwsName
->data
) {
8695 rv
= SECITEM_CopyItem(NULL
, pwsName
, cwsName
);
8697 ssl_ReleaseSpecWriteLock(ss
); /**************************/
8698 if (rv
!= SECSuccess
) {
8699 errCode
= SSL_ERROR_INTERNAL_ERROR_ALERT
;
8700 desc
= internal_error
;
8701 ret
= SSL_SNI_SEND_ALERT
;
8704 } else if (ret
< ss
->xtnData
.sniNameArrSize
) {
8705 /* Application has configured new socket info. Lets check it
8706 * and save the name. */
8708 SECItem
* name
= &ss
->xtnData
.sniNameArr
[ret
];
8709 int configedCiphers
;
8712 /* get rid of the old name and save the newly picked. */
8713 /* This code is protected by ssl3HandshakeLock. */
8714 ssl_GetSpecWriteLock(ss
); /*******************************/
8715 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
8716 /* not allow name change on the 2d HS */
8717 if (ss
->firstHsDone
) {
8718 SECItem
*cwsName
= &ss
->ssl3
.cwSpec
->srvVirtName
;
8719 if (ssl3_ServerNameCompare(name
, cwsName
)) {
8720 ssl_ReleaseSpecWriteLock(ss
); /******************/
8721 errCode
= SSL_ERROR_UNRECOGNIZED_NAME_ALERT
;
8722 desc
= handshake_failure
;
8723 ret
= SSL_SNI_SEND_ALERT
;
8728 pwsName
= &ss
->ssl3
.pwSpec
->srvVirtName
;
8729 if (pwsName
->data
) {
8730 SECITEM_FreeItem(pwsName
, PR_FALSE
);
8732 rv
= SECITEM_CopyItem(NULL
, pwsName
, name
);
8733 ssl_ReleaseSpecWriteLock(ss
); /***************************/
8734 if (rv
!= SECSuccess
) {
8735 errCode
= SSL_ERROR_INTERNAL_ERROR_ALERT
;
8736 desc
= internal_error
;
8737 ret
= SSL_SNI_SEND_ALERT
;
8740 configedCiphers
= ssl3_config_match_init(ss
);
8741 if (configedCiphers
<= 0) {
8742 /* no ciphers are working/supported */
8743 errCode
= PORT_GetError();
8744 desc
= handshake_failure
;
8745 ret
= SSL_SNI_SEND_ALERT
;
8748 /* Need to tell the client that application has picked
8749 * the name from the offered list and reconfigured the socket.
8751 ssl3_RegisterServerHelloExtensionSender(ss
, ssl_server_name_xtn
,
8752 ssl3_SendServerNameXtn
);
8754 /* Callback returned index outside of the boundary. */
8755 PORT_Assert(ret
< ss
->xtnData
.sniNameArrSize
);
8756 errCode
= SSL_ERROR_INTERNAL_ERROR_ALERT
;
8757 desc
= internal_error
;
8758 ret
= SSL_SNI_SEND_ALERT
;
8762 /* Free sniNameArr. The data that each SECItem in the array
8763 * points into is the data from the input buffer "b". It will
8764 * not be available outside the scope of this or it's child
8766 if (ss
->xtnData
.sniNameArr
) {
8767 PORT_Free(ss
->xtnData
.sniNameArr
);
8768 ss
->xtnData
.sniNameArr
= NULL
;
8769 ss
->xtnData
.sniNameArrSize
= 0;
8771 if (ret
<= SSL_SNI_SEND_ALERT
) {
8772 /* desc and errCode should be set. */
8776 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
8777 else if (ss
->firstHsDone
) {
8778 /* Check that we don't have the name is current spec
8779 * if this extension was not negotiated on the 2d hs. */
8780 PRBool passed
= PR_TRUE
;
8781 ssl_GetSpecReadLock(ss
); /*******************************/
8782 if (ss
->ssl3
.cwSpec
->srvVirtName
.data
) {
8785 ssl_ReleaseSpecReadLock(ss
); /***************************/
8787 errCode
= SSL_ERROR_UNRECOGNIZED_NAME_ALERT
;
8788 desc
= handshake_failure
;
8794 sid
= ssl3_NewSessionID(ss
, PR_TRUE
);
8796 errCode
= PORT_GetError();
8797 goto loser
; /* memory error is set. */
8799 ss
->sec
.ci
.sid
= sid
;
8801 ss
->ssl3
.hs
.isResuming
= PR_FALSE
;
8802 ssl_GetXmitBufLock(ss
);
8803 rv
= ssl3_SendServerHelloSequence(ss
);
8804 ssl_ReleaseXmitBufLock(ss
);
8805 if (rv
!= SECSuccess
) {
8806 errCode
= PORT_GetError();
8810 if (haveXmitBufLock
) {
8811 ssl_ReleaseXmitBufLock(ss
);
8812 haveXmitBufLock
= PR_FALSE
;
8818 if (haveSpecWriteLock
) {
8819 ssl_ReleaseSpecWriteLock(ss
);
8820 haveSpecWriteLock
= PR_FALSE
;
8822 (void)SSL3_SendAlert(ss
, level
, desc
);
8825 if (haveSpecWriteLock
) {
8826 ssl_ReleaseSpecWriteLock(ss
);
8827 haveSpecWriteLock
= PR_FALSE
;
8830 if (haveXmitBufLock
) {
8831 ssl_ReleaseXmitBufLock(ss
);
8832 haveXmitBufLock
= PR_FALSE
;
8835 PORT_SetError(errCode
);
8840 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
8841 * in asking to use the V3 handshake.
8842 * Called from ssl2_HandleClientHelloMessage() in sslcon.c
8845 ssl3_HandleV2ClientHello(sslSocket
*ss
, unsigned char *buffer
, int length
)
8847 sslSessionID
* sid
= NULL
;
8848 unsigned char * suites
;
8849 unsigned char * random
;
8850 SSL3ProtocolVersion version
;
8857 int errCode
= SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
;
8858 SSL3AlertDescription desc
= handshake_failure
;
8860 SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss
->fd
));
8862 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
8864 ssl_GetSSL3HandshakeLock(ss
);
8866 PORT_Memset(&ss
->xtnData
, 0, sizeof(TLSExtensionData
));
8868 rv
= ssl3_InitState(ss
);
8869 if (rv
!= SECSuccess
) {
8870 ssl_ReleaseSSL3HandshakeLock(ss
);
8871 return rv
; /* ssl3_InitState has set the error code. */
8873 rv
= ssl3_RestartHandshakeHashes(ss
);
8874 if (rv
!= SECSuccess
) {
8875 ssl_ReleaseSSL3HandshakeLock(ss
);
8879 if (ss
->ssl3
.hs
.ws
!= wait_client_hello
) {
8880 desc
= unexpected_message
;
8881 errCode
= SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO
;
8882 goto loser
; /* alert_loser */
8885 version
= (buffer
[1] << 8) | buffer
[2];
8886 suite_length
= (buffer
[3] << 8) | buffer
[4];
8887 sid_length
= (buffer
[5] << 8) | buffer
[6];
8888 rand_length
= (buffer
[7] << 8) | buffer
[8];
8889 ss
->clientHelloVersion
= version
;
8891 rv
= ssl3_NegotiateVersion(ss
, version
, PR_TRUE
);
8892 if (rv
!= SECSuccess
) {
8893 /* send back which ever alert client will understand. */
8894 desc
= (version
> SSL_LIBRARY_VERSION_3_0
) ? protocol_version
8895 : handshake_failure
;
8896 errCode
= SSL_ERROR_UNSUPPORTED_VERSION
;
8900 rv
= ssl3_InitHandshakeHashes(ss
);
8901 if (rv
!= SECSuccess
) {
8902 desc
= internal_error
;
8903 errCode
= PORT_GetError();
8907 /* if we get a non-zero SID, just ignore it. */
8909 SSL_HL_CLIENT_HELLO_HBYTES
+ suite_length
+ sid_length
+ rand_length
) {
8910 SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
8911 SSL_GETPID(), ss
->fd
, length
,
8912 SSL_HL_CLIENT_HELLO_HBYTES
+ suite_length
+ sid_length
+
8914 goto loser
; /* malformed */ /* alert_loser */
8917 suites
= buffer
+ SSL_HL_CLIENT_HELLO_HBYTES
;
8918 random
= suites
+ suite_length
+ sid_length
;
8920 if (rand_length
< SSL_MIN_CHALLENGE_BYTES
||
8921 rand_length
> SSL_MAX_CHALLENGE_BYTES
) {
8922 goto loser
; /* malformed */ /* alert_loser */
8925 PORT_Assert(SSL_MAX_CHALLENGE_BYTES
== SSL3_RANDOM_LENGTH
);
8927 PORT_Memset(&ss
->ssl3
.hs
.client_random
, 0, SSL3_RANDOM_LENGTH
);
8929 &ss
->ssl3
.hs
.client_random
.rand
[SSL3_RANDOM_LENGTH
- rand_length
],
8930 random
, rand_length
);
8932 PRINT_BUF(60, (ss
, "client random:", &ss
->ssl3
.hs
.client_random
.rand
[0],
8933 SSL3_RANDOM_LENGTH
));
8934 #ifndef NSS_DISABLE_ECC
8935 /* Disable any ECC cipher suites for which we have no cert. */
8936 ssl3_FilterECCipherSuitesByServerCerts(ss
);
8938 i
= ssl3_config_match_init(ss
);
8940 errCode
= PORT_GetError(); /* error code is already set. */
8944 /* Select a cipher suite.
8946 ** NOTE: This suite selection algorithm should be the same as the one in
8947 ** ssl3_HandleClientHello().
8949 ** See the comments about export cipher suites in ssl3_HandleClientHello().
8951 for (j
= 0; j
< ssl_V3_SUITES_IMPLEMENTED
; j
++) {
8952 ssl3CipherSuiteCfg
*suite
= &ss
->cipherSuites
[j
];
8953 SSLVersionRange vrange
= {ss
->version
, ss
->version
};
8954 if (!config_match(suite
, ss
->ssl3
.policy
, PR_TRUE
, &vrange
)) {
8957 for (i
= 0; i
+2 < suite_length
; i
+= 3) {
8958 PRUint32 suite_i
= (suites
[i
] << 16)|(suites
[i
+1] << 8)|suites
[i
+2];
8959 if (suite_i
== suite
->cipher_suite
) {
8960 ss
->ssl3
.hs
.cipher_suite
= suite
->cipher_suite
;
8961 ss
->ssl3
.hs
.suite_def
=
8962 ssl_LookupCipherSuiteDef(ss
->ssl3
.hs
.cipher_suite
);
8967 errCode
= SSL_ERROR_NO_CYPHER_OVERLAP
;
8972 /* Look for the SCSV, and if found, treat it just like an empty RI
8973 * extension by processing a local copy of an empty RI extension.
8975 for (i
= 0; i
+2 < suite_length
; i
+= 3) {
8976 PRUint32 suite_i
= (suites
[i
] << 16) | (suites
[i
+1] << 8) | suites
[i
+2];
8977 if (suite_i
== TLS_EMPTY_RENEGOTIATION_INFO_SCSV
) {
8978 SSL3Opaque
* b2
= (SSL3Opaque
*)emptyRIext
;
8979 PRUint32 L2
= sizeof emptyRIext
;
8980 (void)ssl3_HandleHelloExtensions(ss
, &b2
, &L2
);
8985 if (ss
->opt
.requireSafeNegotiation
&&
8986 !ssl3_ExtensionNegotiated(ss
, ssl_renegotiation_info_xtn
)) {
8987 desc
= handshake_failure
;
8988 errCode
= SSL_ERROR_UNSAFE_NEGOTIATION
;
8992 ss
->ssl3
.hs
.compression
= ssl_compression_null
;
8993 ss
->sec
.send
= ssl3_SendApplicationData
;
8995 /* we don't even search for a cache hit here. It's just a miss. */
8996 SSL_AtomicIncrementLong(& ssl3stats
.hch_sid_cache_misses
);
8997 sid
= ssl3_NewSessionID(ss
, PR_TRUE
);
8999 errCode
= PORT_GetError();
9000 goto loser
; /* memory error is set. */
9002 ss
->sec
.ci
.sid
= sid
;
9003 /* do not worry about memory leak of sid since it now belongs to ci */
9005 /* We have to update the handshake hashes before we can send stuff */
9006 rv
= ssl3_UpdateHandshakeHashes(ss
, buffer
, length
);
9007 if (rv
!= SECSuccess
) {
9008 errCode
= PORT_GetError();
9012 ssl_GetXmitBufLock(ss
);
9013 rv
= ssl3_SendServerHelloSequence(ss
);
9014 ssl_ReleaseXmitBufLock(ss
);
9015 if (rv
!= SECSuccess
) {
9016 errCode
= PORT_GetError();
9020 /* XXX_1 The call stack to here is:
9021 * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here.
9022 * ssl2_HandleClientHelloMessage returns whatever we return here.
9023 * ssl_Do1stHandshake will continue looping if it gets back either
9024 * SECSuccess or SECWouldBlock.
9025 * SECSuccess is preferable here. See XXX_1 in sslgathr.c.
9027 ssl_ReleaseSSL3HandshakeLock(ss
);
9031 SSL3_SendAlert(ss
, alert_fatal
, desc
);
9033 ssl_ReleaseSSL3HandshakeLock(ss
);
9034 PORT_SetError(errCode
);
9038 /* The negotiated version number has been already placed in ss->version.
9040 ** Called from: ssl3_HandleClientHello (resuming session),
9041 ** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session),
9042 ** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
9045 ssl3_SendServerHello(sslSocket
*ss
)
9049 PRUint32 maxBytes
= 65535;
9051 PRInt32 extensions_len
= 0;
9052 SSL3ProtocolVersion version
;
9054 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
9057 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
9058 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
9061 PORT_Assert(MSB(ss
->version
) == MSB(SSL_LIBRARY_VERSION_3_0
));
9063 if (MSB(ss
->version
) != MSB(SSL_LIBRARY_VERSION_3_0
)) {
9064 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP
);
9068 PORT_Assert(MSB(ss
->version
) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0
));
9070 if (MSB(ss
->version
) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0
)) {
9071 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP
);
9076 sid
= ss
->sec
.ci
.sid
;
9078 extensions_len
= ssl3_CallHelloExtensionSenders(ss
, PR_FALSE
, maxBytes
,
9079 &ss
->xtnData
.serverSenders
[0]);
9080 if (extensions_len
> 0)
9081 extensions_len
+= 2; /* Add sizeof total extension length */
9083 length
= sizeof(SSL3ProtocolVersion
) + SSL3_RANDOM_LENGTH
+ 1 +
9084 ((sid
== NULL
) ? 0: sid
->u
.ssl3
.sessionIDLength
) +
9085 sizeof(ssl3CipherSuite
) + 1 + extensions_len
;
9086 rv
= ssl3_AppendHandshakeHeader(ss
, server_hello
, length
);
9087 if (rv
!= SECSuccess
) {
9088 return rv
; /* err set by AppendHandshake. */
9092 version
= dtls_TLSVersionToDTLSVersion(ss
->version
);
9094 version
= ss
->version
;
9097 rv
= ssl3_AppendHandshakeNumber(ss
, version
, 2);
9098 if (rv
!= SECSuccess
) {
9099 return rv
; /* err set by AppendHandshake. */
9101 rv
= ssl3_GetNewRandom(&ss
->ssl3
.hs
.server_random
);
9102 if (rv
!= SECSuccess
) {
9103 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE
);
9106 rv
= ssl3_AppendHandshake(
9107 ss
, &ss
->ssl3
.hs
.server_random
, SSL3_RANDOM_LENGTH
);
9108 if (rv
!= SECSuccess
) {
9109 return rv
; /* err set by AppendHandshake. */
9113 rv
= ssl3_AppendHandshakeVariable(
9114 ss
, sid
->u
.ssl3
.sessionID
, sid
->u
.ssl3
.sessionIDLength
, 1);
9116 rv
= ssl3_AppendHandshakeNumber(ss
, 0, 1);
9117 if (rv
!= SECSuccess
) {
9118 return rv
; /* err set by AppendHandshake. */
9121 rv
= ssl3_AppendHandshakeNumber(ss
, ss
->ssl3
.hs
.cipher_suite
, 2);
9122 if (rv
!= SECSuccess
) {
9123 return rv
; /* err set by AppendHandshake. */
9125 rv
= ssl3_AppendHandshakeNumber(ss
, ss
->ssl3
.hs
.compression
, 1);
9126 if (rv
!= SECSuccess
) {
9127 return rv
; /* err set by AppendHandshake. */
9129 if (extensions_len
) {
9132 extensions_len
-= 2;
9133 rv
= ssl3_AppendHandshakeNumber(ss
, extensions_len
, 2);
9134 if (rv
!= SECSuccess
)
9135 return rv
; /* err set by ssl3_SetupPendingCipherSpec */
9136 sent_len
= ssl3_CallHelloExtensionSenders(ss
, PR_TRUE
, extensions_len
,
9137 &ss
->xtnData
.serverSenders
[0]);
9138 PORT_Assert(sent_len
== extensions_len
);
9139 if (sent_len
!= extensions_len
) {
9141 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
9145 rv
= ssl3_SetupPendingCipherSpec(ss
);
9146 if (rv
!= SECSuccess
) {
9147 return rv
; /* err set by ssl3_SetupPendingCipherSpec */
9153 /* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing
9154 * elements of the handshake. (The negotiated cipher suite determines the
9155 * signature algorithm.) Prior to TLS 1.2, the MD5/SHA1 combination is always
9156 * used. With TLS 1.2, a client may advertise its support for signature and
9157 * hash combinations. */
9159 ssl3_PickSignatureHashAlgorithm(sslSocket
*ss
,
9160 SSL3SignatureAndHashAlgorithm
* out
)
9162 TLSSignatureAlgorithm sigAlg
;
9164 /* hashPreference expresses our preferences for hash algorithms, most
9165 * preferable first. */
9166 static const SECOidTag hashPreference
[] = {
9173 switch (ss
->ssl3
.hs
.kea_def
->kea
) {
9175 case kea_rsa_export
:
9176 case kea_rsa_export_1024
:
9178 case kea_dh_rsa_export
:
9180 case kea_dhe_rsa_export
:
9184 sigAlg
= tls_sig_rsa
;
9187 case kea_dh_dss_export
:
9189 case kea_dhe_dss_export
:
9190 sigAlg
= tls_sig_dsa
;
9192 case kea_ecdh_ecdsa
:
9193 case kea_ecdhe_ecdsa
:
9194 sigAlg
= tls_sig_ecdsa
;
9197 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG
);
9200 out
->sigAlg
= sigAlg
;
9202 if (ss
->version
<= SSL_LIBRARY_VERSION_TLS_1_1
) {
9203 /* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and
9205 out
->hashAlg
= SEC_OID_UNKNOWN
;
9209 if (ss
->ssl3
.hs
.numClientSigAndHash
== 0) {
9210 /* If the client didn't provide any signature_algorithms extension then
9211 * we can assume that they support SHA-1:
9212 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
9213 out
->hashAlg
= SEC_OID_SHA1
;
9217 for (i
= 0; i
< PR_ARRAY_SIZE(hashPreference
); i
++) {
9218 for (j
= 0; j
< ss
->ssl3
.hs
.numClientSigAndHash
; j
++) {
9219 const SSL3SignatureAndHashAlgorithm
* sh
=
9220 &ss
->ssl3
.hs
.clientSigAndHash
[j
];
9221 if (sh
->sigAlg
== sigAlg
&& sh
->hashAlg
== hashPreference
[i
]) {
9222 out
->hashAlg
= sh
->hashAlg
;
9228 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM
);
9234 ssl3_SendServerKeyExchange(sslSocket
*ss
)
9236 const ssl3KEADef
* kea_def
= ss
->ssl3
.hs
.kea_def
;
9237 SECStatus rv
= SECFailure
;
9240 SECItem signed_hash
= {siBuffer
, NULL
, 0};
9242 SECKEYPublicKey
* sdPub
; /* public key for step-down */
9243 SSL3SignatureAndHashAlgorithm sigAndHash
;
9245 SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
9246 SSL_GETPID(), ss
->fd
));
9248 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
9249 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
9251 if (ssl3_PickSignatureHashAlgorithm(ss
, &sigAndHash
) != SECSuccess
) {
9255 switch (kea_def
->exchKeyType
) {
9257 /* Perform SSL Step-Down here. */
9258 sdPub
= ss
->stepDownKeyPair
->pubKey
;
9259 PORT_Assert(sdPub
!= NULL
);
9261 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
9264 rv
= ssl3_ComputeExportRSAKeyHash(sigAndHash
.hashAlg
,
9265 sdPub
->u
.rsa
.modulus
,
9266 sdPub
->u
.rsa
.publicExponent
,
9267 &ss
->ssl3
.hs
.client_random
,
9268 &ss
->ssl3
.hs
.server_random
,
9269 &hashes
, ss
->opt
.bypassPKCS11
);
9270 if (rv
!= SECSuccess
) {
9271 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
9275 isTLS
= (PRBool
)(ss
->ssl3
.pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
9276 rv
= ssl3_SignHashes(&hashes
, ss
->serverCerts
[kt_rsa
].SERVERKEY
,
9277 &signed_hash
, isTLS
);
9278 if (rv
!= SECSuccess
) {
9279 goto loser
; /* ssl3_SignHashes has set err. */
9281 if (signed_hash
.data
== NULL
) {
9282 /* how can this happen and rv == SECSuccess ?? */
9283 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
9286 length
= 2 + sdPub
->u
.rsa
.modulus
.len
+
9287 2 + sdPub
->u
.rsa
.publicExponent
.len
+
9288 2 + signed_hash
.len
;
9290 rv
= ssl3_AppendHandshakeHeader(ss
, server_key_exchange
, length
);
9291 if (rv
!= SECSuccess
) {
9292 goto loser
; /* err set by AppendHandshake. */
9295 rv
= ssl3_AppendHandshakeVariable(ss
, sdPub
->u
.rsa
.modulus
.data
,
9296 sdPub
->u
.rsa
.modulus
.len
, 2);
9297 if (rv
!= SECSuccess
) {
9298 goto loser
; /* err set by AppendHandshake. */
9301 rv
= ssl3_AppendHandshakeVariable(
9302 ss
, sdPub
->u
.rsa
.publicExponent
.data
,
9303 sdPub
->u
.rsa
.publicExponent
.len
, 2);
9304 if (rv
!= SECSuccess
) {
9305 goto loser
; /* err set by AppendHandshake. */
9308 if (ss
->ssl3
.pwSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_2
) {
9309 rv
= ssl3_AppendSignatureAndHashAlgorithm(ss
, &sigAndHash
);
9310 if (rv
!= SECSuccess
) {
9311 goto loser
; /* err set by AppendHandshake. */
9315 rv
= ssl3_AppendHandshakeVariable(ss
, signed_hash
.data
,
9316 signed_hash
.len
, 2);
9317 if (rv
!= SECSuccess
) {
9318 goto loser
; /* err set by AppendHandshake. */
9320 PORT_Free(signed_hash
.data
);
9323 #ifndef NSS_DISABLE_ECC
9325 rv
= ssl3_SendECDHServerKeyExchange(ss
, &sigAndHash
);
9328 #endif /* NSS_DISABLE_ECC */
9333 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG
);
9337 if (signed_hash
.data
!= NULL
)
9338 PORT_Free(signed_hash
.data
);
9344 ssl3_SendCertificateRequest(sslSocket
*ss
)
9348 CERTDistNames
*ca_list
;
9349 const PRUint8
*certTypes
;
9350 const PRUint8
*sigAlgs
;
9351 SECItem
* names
= NULL
;
9357 int certTypesLength
;
9360 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
9361 SSL_GETPID(), ss
->fd
));
9363 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
9364 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
9366 isTLS12
= (PRBool
)(ss
->ssl3
.pwSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_2
);
9368 /* ssl3.ca_list is initialized to NULL, and never changed. */
9369 ca_list
= ss
->ssl3
.ca_list
;
9371 ca_list
= ssl3_server_ca_list
;
9374 if (ca_list
!= NULL
) {
9375 names
= ca_list
->names
;
9376 nnames
= ca_list
->nnames
;
9379 for (i
= 0, name
= names
; i
< nnames
; i
++, name
++) {
9380 calen
+= 2 + name
->len
;
9383 certTypes
= certificate_types
;
9384 certTypesLength
= sizeof certificate_types
;
9385 sigAlgs
= supported_signature_algorithms
;
9386 sigAlgsLength
= sizeof supported_signature_algorithms
;
9388 length
= 1 + certTypesLength
+ 2 + calen
;
9390 length
+= 2 + sigAlgsLength
;
9393 rv
= ssl3_AppendHandshakeHeader(ss
, certificate_request
, length
);
9394 if (rv
!= SECSuccess
) {
9395 return rv
; /* err set by AppendHandshake. */
9397 rv
= ssl3_AppendHandshakeVariable(ss
, certTypes
, certTypesLength
, 1);
9398 if (rv
!= SECSuccess
) {
9399 return rv
; /* err set by AppendHandshake. */
9402 rv
= ssl3_AppendHandshakeVariable(ss
, sigAlgs
, sigAlgsLength
, 2);
9403 if (rv
!= SECSuccess
) {
9404 return rv
; /* err set by AppendHandshake. */
9407 rv
= ssl3_AppendHandshakeNumber(ss
, calen
, 2);
9408 if (rv
!= SECSuccess
) {
9409 return rv
; /* err set by AppendHandshake. */
9411 for (i
= 0, name
= names
; i
< nnames
; i
++, name
++) {
9412 rv
= ssl3_AppendHandshakeVariable(ss
, name
->data
, name
->len
, 2);
9413 if (rv
!= SECSuccess
) {
9414 return rv
; /* err set by AppendHandshake. */
9422 ssl3_SendServerHelloDone(sslSocket
*ss
)
9426 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
9427 SSL_GETPID(), ss
->fd
));
9429 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
9430 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
9432 rv
= ssl3_AppendHandshakeHeader(ss
, server_hello_done
, 0);
9433 if (rv
!= SECSuccess
) {
9434 return rv
; /* err set by AppendHandshake. */
9436 rv
= ssl3_FlushHandshake(ss
, 0);
9437 if (rv
!= SECSuccess
) {
9438 return rv
; /* error code set by ssl3_FlushHandshake */
9443 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9444 * ssl3 Certificate Verify message
9445 * Caller must hold Handshake and RecvBuf locks.
9448 ssl3_HandleCertificateVerify(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
,
9451 SECItem signed_hash
= {siBuffer
, NULL
, 0};
9453 int errCode
= SSL_ERROR_RX_MALFORMED_CERT_VERIFY
;
9454 SSL3AlertDescription desc
= handshake_failure
;
9455 PRBool isTLS
, isTLS12
;
9456 SSL3SignatureAndHashAlgorithm sigAndHash
;
9458 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
9459 SSL_GETPID(), ss
->fd
));
9460 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
9461 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
9463 isTLS
= (PRBool
)(ss
->ssl3
.prSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
9464 isTLS12
= (PRBool
)(ss
->ssl3
.prSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_2
);
9466 if (ss
->ssl3
.hs
.ws
!= wait_cert_verify
) {
9467 desc
= unexpected_message
;
9468 errCode
= SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY
;
9473 rv
= ssl3_ConsumeSignatureAndHashAlgorithm(ss
, &b
, &length
,
9475 if (rv
!= SECSuccess
) {
9476 goto loser
; /* malformed or unsupported. */
9478 rv
= ssl3_CheckSignatureAndHashAlgorithmConsistency(
9479 &sigAndHash
, ss
->sec
.peerCert
);
9480 if (rv
!= SECSuccess
) {
9481 errCode
= PORT_GetError();
9482 desc
= decrypt_error
;
9486 /* We only support CertificateVerify messages that use the handshake
9488 if (sigAndHash
.hashAlg
!= hashes
->hashAlg
) {
9489 errCode
= SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM
;
9490 desc
= decrypt_error
;
9495 rv
= ssl3_ConsumeHandshakeVariable(ss
, &signed_hash
, 2, &b
, &length
);
9496 if (rv
!= SECSuccess
) {
9497 goto loser
; /* malformed. */
9500 /* XXX verify that the key & kea match */
9501 rv
= ssl3_VerifySignedHashes(hashes
, ss
->sec
.peerCert
, &signed_hash
,
9502 isTLS
, ss
->pkcs11PinArg
);
9503 if (rv
!= SECSuccess
) {
9504 errCode
= PORT_GetError();
9505 desc
= isTLS
? decrypt_error
: handshake_failure
;
9509 signed_hash
.data
= NULL
;
9512 desc
= isTLS
? decode_error
: illegal_parameter
;
9513 goto alert_loser
; /* malformed */
9515 ss
->ssl3
.hs
.ws
= wait_change_cipher
;
9519 SSL3_SendAlert(ss
, alert_fatal
, desc
);
9521 PORT_SetError(errCode
);
9526 /* find a slot that is able to generate a PMS and wrap it with RSA.
9527 * Then generate and return the PMS.
9528 * If the serverKeySlot parameter is non-null, this function will use
9529 * that slot to do the job, otherwise it will find a slot.
9531 * Called from ssl3_DeriveConnectionKeysPKCS11() (above)
9532 * sendRSAClientKeyExchange() (above)
9533 * ssl3_HandleRSAClientKeyExchange() (below)
9534 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
9537 ssl3_GenerateRSAPMS(sslSocket
*ss
, ssl3CipherSpec
*spec
,
9538 PK11SlotInfo
* serverKeySlot
)
9540 PK11SymKey
* pms
= NULL
;
9541 PK11SlotInfo
* slot
= serverKeySlot
;
9542 void * pwArg
= ss
->pkcs11PinArg
;
9545 CK_MECHANISM_TYPE mechanism_array
[3];
9547 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
9550 SSLCipherAlgorithm calg
;
9551 /* The specReadLock would suffice here, but we cannot assert on
9552 ** read locks. Also, all the callers who call with a non-null
9553 ** slot already hold the SpecWriteLock.
9555 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSpecWriteLock(ss
));
9556 PORT_Assert(ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
);
9558 calg
= spec
->cipher_def
->calg
;
9559 PORT_Assert(alg2Mech
[calg
].calg
== calg
);
9561 /* First get an appropriate slot. */
9562 mechanism_array
[0] = CKM_SSL3_PRE_MASTER_KEY_GEN
;
9563 mechanism_array
[1] = CKM_RSA_PKCS
;
9564 mechanism_array
[2] = alg2Mech
[calg
].cmech
;
9566 slot
= PK11_GetBestSlotMultiple(mechanism_array
, 3, pwArg
);
9568 /* can't find a slot with all three, find a slot with the minimum */
9569 slot
= PK11_GetBestSlotMultiple(mechanism_array
, 2, pwArg
);
9571 PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND
);
9572 return pms
; /* which is NULL */
9577 /* Generate the pre-master secret ... */
9579 SSL3ProtocolVersion temp
;
9581 temp
= dtls_TLSVersionToDTLSVersion(ss
->clientHelloVersion
);
9582 version
.major
= MSB(temp
);
9583 version
.minor
= LSB(temp
);
9585 version
.major
= MSB(ss
->clientHelloVersion
);
9586 version
.minor
= LSB(ss
->clientHelloVersion
);
9589 param
.data
= (unsigned char *)&version
;
9590 param
.len
= sizeof version
;
9592 pms
= PK11_KeyGen(slot
, CKM_SSL3_PRE_MASTER_KEY_GEN
, ¶m
, 0, pwArg
);
9594 PK11_FreeSlot(slot
);
9596 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
9601 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
9602 * return any indication of failure of the Client Key Exchange message,
9603 * where that failure is caused by the content of the client's message.
9604 * This function must not return SECFailure for any reason that is directly
9605 * or indirectly caused by the content of the client's encrypted PMS.
9606 * We must not send an alert and also not drop the connection.
9607 * Instead, we generate a random PMS. This will cause a failure
9608 * in the processing the finished message, which is exactly where
9609 * the failure must occur.
9611 * Called from ssl3_HandleClientKeyExchange
9614 ssl3_HandleRSAClientKeyExchange(sslSocket
*ss
,
9617 SECKEYPrivateKey
*serverKey
)
9620 #ifndef NO_PKCS11_BYPASS
9621 unsigned char * cr
= (unsigned char *)&ss
->ssl3
.hs
.client_random
;
9622 unsigned char * sr
= (unsigned char *)&ss
->ssl3
.hs
.server_random
;
9623 ssl3CipherSpec
* pwSpec
= ss
->ssl3
.pwSpec
;
9624 unsigned int outLen
= 0;
9626 PRBool isTLS
= PR_FALSE
;
9629 unsigned char rsaPmsBuf
[SSL3_RSA_PMS_LENGTH
];
9630 SECItem pmsItem
= {siBuffer
, NULL
, 0};
9632 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
9633 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
9634 PORT_Assert( ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
);
9637 enc_pms
.len
= length
;
9638 pmsItem
.data
= rsaPmsBuf
;
9639 pmsItem
.len
= sizeof rsaPmsBuf
;
9641 if (ss
->ssl3
.prSpec
->version
> SSL_LIBRARY_VERSION_3_0
) { /* isTLS */
9643 kLen
= ssl3_ConsumeHandshakeNumber(ss
, 2, &enc_pms
.data
, &enc_pms
.len
);
9645 PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
9648 if ((unsigned)kLen
< enc_pms
.len
) {
9653 isTLS
= (PRBool
)(ss
->ssl3
.hs
.kea_def
->tls_keygen
!= 0);
9656 #ifndef NO_PKCS11_BYPASS
9657 if (ss
->opt
.bypassPKCS11
) {
9658 /* TRIPLE BYPASS, get PMS directly from RSA decryption.
9659 * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer,
9660 * then, check for version rollback attack, then
9661 * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in
9662 * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with
9663 * ss and NULL, so that it will use the MS we've already derived here.
9666 rv
= PK11_PrivDecryptPKCS1(serverKey
, rsaPmsBuf
, &outLen
,
9667 sizeof rsaPmsBuf
, enc_pms
.data
, enc_pms
.len
);
9668 if (rv
!= SECSuccess
) {
9669 /* triple bypass failed. Let's try for a double bypass. */
9671 } else if (ss
->opt
.detectRollBack
) {
9672 SSL3ProtocolVersion client_version
=
9673 (rsaPmsBuf
[0] << 8) | rsaPmsBuf
[1];
9676 client_version
= dtls_DTLSVersionToTLSVersion(client_version
);
9679 if (client_version
!= ss
->clientHelloVersion
) {
9680 /* Version roll-back detected. ensure failure. */
9681 rv
= PK11_GenerateRandom(rsaPmsBuf
, sizeof rsaPmsBuf
);
9684 /* have PMS, build MS without PKCS11 */
9685 rv
= ssl3_MasterKeyDeriveBypass(pwSpec
, cr
, sr
, &pmsItem
, isTLS
,
9687 if (rv
!= SECSuccess
) {
9688 pwSpec
->msItem
.data
= pwSpec
->raw_master_secret
;
9689 pwSpec
->msItem
.len
= SSL3_MASTER_SECRET_LENGTH
;
9690 PK11_GenerateRandom(pwSpec
->msItem
.data
, pwSpec
->msItem
.len
);
9692 rv
= ssl3_InitPendingCipherSpec(ss
, NULL
);
9696 #ifndef NO_PKCS11_BYPASS
9700 * unwrap pms out of the incoming buffer
9701 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
9702 * the unwrap. Rather, it is the mechanism with which the
9703 * unwrapped pms will be used.
9705 pms
= PK11_PubUnwrapSymKey(serverKey
, &enc_pms
,
9706 CKM_SSL3_MASTER_KEY_DERIVE
, CKA_DERIVE
, 0);
9708 PRINT_BUF(60, (ss
, "decrypted premaster secret:",
9709 PK11_GetKeyData(pms
)->data
,
9710 PK11_GetKeyData(pms
)->len
));
9712 /* unwrap failed. Generate a bogus PMS and carry on. */
9713 PK11SlotInfo
* slot
= PK11_GetSlotFromPrivateKey(serverKey
);
9715 ssl_GetSpecWriteLock(ss
);
9716 pms
= ssl3_GenerateRSAPMS(ss
, ss
->ssl3
.prSpec
, slot
);
9717 ssl_ReleaseSpecWriteLock(ss
);
9718 PK11_FreeSlot(slot
);
9723 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
9727 /* This step will derive the MS from the PMS, among other things. */
9728 rv
= ssl3_InitPendingCipherSpec(ss
, pms
);
9729 PK11_FreeSymKey(pms
);
9732 if (rv
!= SECSuccess
) {
9734 return SECFailure
; /* error code set by ssl3_InitPendingCipherSpec */
9740 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9741 * ssl3 ClientKeyExchange message from the remote client
9742 * Caller must hold Handshake and RecvBuf locks.
9745 ssl3_HandleClientKeyExchange(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
9747 SECKEYPrivateKey
*serverKey
= NULL
;
9749 const ssl3KEADef
*kea_def
;
9750 ssl3KeyPair
*serverKeyPair
= NULL
;
9751 #ifndef NSS_DISABLE_ECC
9752 SECKEYPublicKey
*serverPubKey
= NULL
;
9753 #endif /* NSS_DISABLE_ECC */
9755 SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
9756 SSL_GETPID(), ss
->fd
));
9758 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
9759 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
9761 if (ss
->ssl3
.hs
.ws
!= wait_client_key
) {
9762 SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
9763 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH
);
9767 kea_def
= ss
->ssl3
.hs
.kea_def
;
9769 if (ss
->ssl3
.hs
.usedStepDownKey
) {
9770 PORT_Assert(kea_def
->is_limited
/* XXX OR cert is signing only */
9771 && kea_def
->exchKeyType
== kt_rsa
9772 && ss
->stepDownKeyPair
!= NULL
);
9773 if (!kea_def
->is_limited
||
9774 kea_def
->exchKeyType
!= kt_rsa
||
9775 ss
->stepDownKeyPair
== NULL
) {
9776 /* shouldn't happen, don't use step down if it does */
9779 serverKeyPair
= ss
->stepDownKeyPair
;
9780 ss
->sec
.keaKeyBits
= EXPORT_RSA_KEY_LENGTH
* BPB
;
9783 #ifndef NSS_DISABLE_ECC
9784 /* XXX Using SSLKEAType to index server certifiates
9785 * does not work for (EC)DHE ciphers. Until we have
9786 * an indexing mechanism general enough for all key
9787 * exchange algorithms, we'll need to deal with each
9790 if ((kea_def
->kea
== kea_ecdhe_rsa
) ||
9791 (kea_def
->kea
== kea_ecdhe_ecdsa
)) {
9792 if (ss
->ephemeralECDHKeyPair
!= NULL
) {
9793 serverKeyPair
= ss
->ephemeralECDHKeyPair
;
9794 if (serverKeyPair
->pubKey
) {
9795 ss
->sec
.keaKeyBits
=
9796 SECKEY_PublicKeyStrengthInBits(serverKeyPair
->pubKey
);
9802 sslServerCerts
* sc
= ss
->serverCerts
+ kea_def
->exchKeyType
;
9803 serverKeyPair
= sc
->serverKeyPair
;
9804 ss
->sec
.keaKeyBits
= sc
->serverKeyBits
;
9807 if (serverKeyPair
) {
9808 serverKey
= serverKeyPair
->privKey
;
9811 if (serverKey
== NULL
) {
9813 PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG
);
9817 ss
->sec
.keaType
= kea_def
->exchKeyType
;
9819 switch (kea_def
->exchKeyType
) {
9821 rv
= ssl3_HandleRSAClientKeyExchange(ss
, b
, length
, serverKey
);
9822 if (rv
!= SECSuccess
) {
9824 return SECFailure
; /* error code set */
9829 #ifndef NSS_DISABLE_ECC
9831 /* XXX We really ought to be able to store multiple
9832 * EC certs (a requirement if we wish to support both
9833 * ECDH-RSA and ECDH-ECDSA key exchanges concurrently).
9834 * When we make that change, we'll need an index other
9835 * than kt_ecdh to pick the right EC certificate.
9837 if (serverKeyPair
) {
9838 serverPubKey
= serverKeyPair
->pubKey
;
9840 if (serverPubKey
== NULL
) {
9841 /* XXX Is this the right error code? */
9842 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE
);
9845 rv
= ssl3_HandleECDHClientKeyExchange(ss
, b
, length
,
9846 serverPubKey
, serverKey
);
9847 if (ss
->ephemeralECDHKeyPair
) {
9848 ssl3_FreeKeyPair(ss
->ephemeralECDHKeyPair
);
9849 ss
->ephemeralECDHKeyPair
= NULL
;
9851 if (rv
!= SECSuccess
) {
9852 return SECFailure
; /* error code set */
9855 #endif /* NSS_DISABLE_ECC */
9858 (void) ssl3_HandshakeFailure(ss
);
9859 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG
);
9862 ss
->ssl3
.hs
.ws
= ss
->sec
.peerCert
? wait_cert_verify
: wait_change_cipher
;
9867 /* This is TLS's equivalent of sending a no_certificate alert. */
9869 ssl3_SendEmptyCertificate(sslSocket
*ss
)
9873 rv
= ssl3_AppendHandshakeHeader(ss
, certificate
, 3);
9874 if (rv
== SECSuccess
) {
9875 rv
= ssl3_AppendHandshakeNumber(ss
, 0, 3);
9877 return rv
; /* error, if any, set by functions called above. */
9881 ssl3_HandleNewSessionTicket(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
9886 SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
9887 SSL_GETPID(), ss
->fd
));
9889 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
9890 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
9892 PORT_Assert(!ss
->ssl3
.hs
.newSessionTicket
.ticket
.data
);
9893 PORT_Assert(!ss
->ssl3
.hs
.receivedNewSessionTicket
);
9895 if (ss
->ssl3
.hs
.ws
!= wait_new_session_ticket
) {
9896 SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
9897 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET
);
9901 /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid
9902 * until it has verified the server's Finished message." See the comment in
9903 * ssl3_FinishHandshake for more details.
9905 ss
->ssl3
.hs
.newSessionTicket
.received_timestamp
= ssl_Time();
9907 (void)SSL3_SendAlert(ss
, alert_fatal
, decode_error
);
9908 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
);
9911 ss
->ssl3
.hs
.newSessionTicket
.ticket_lifetime_hint
=
9912 (PRUint32
)ssl3_ConsumeHandshakeNumber(ss
, 4, &b
, &length
);
9914 rv
= ssl3_ConsumeHandshakeVariable(ss
, &ticketData
, 2, &b
, &length
);
9915 if (rv
!= SECSuccess
|| length
!= 0) {
9916 (void)SSL3_SendAlert(ss
, alert_fatal
, decode_error
);
9917 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
);
9918 return SECFailure
; /* malformed */
9920 /* If the server sent a zero-length ticket, ignore it and keep the
9921 * existing ticket. */
9922 if (ticketData
.len
!= 0) {
9923 rv
= SECITEM_CopyItem(NULL
, &ss
->ssl3
.hs
.newSessionTicket
.ticket
,
9925 if (rv
!= SECSuccess
) {
9928 ss
->ssl3
.hs
.receivedNewSessionTicket
= PR_TRUE
;
9931 ss
->ssl3
.hs
.ws
= wait_change_cipher
;
9936 static PRInt32 connNum
= 0;
9939 get_fake_cert(SECItem
*pCertItem
, int *pIndex
)
9945 const char *extension
;
9947 PRInt32 numBytes
= 0;
9952 pCertItem
->data
= 0;
9953 if ((testdir
= PR_GetEnv("NISCC_TEST")) == NULL
) {
9956 *pIndex
= (NULL
!= strstr(testdir
, "root"));
9957 extension
= (strstr(testdir
, "simple") ? "" : ".der");
9958 fileNum
= PR_ATOMIC_INCREMENT(&connNum
) - 1;
9959 if ((startat
= PR_GetEnv("START_AT")) != NULL
) {
9960 fileNum
+= atoi(startat
);
9962 if ((stopat
= PR_GetEnv("STOP_AT")) != NULL
&&
9963 fileNum
>= atoi(stopat
)) {
9967 sprintf(cfn
, "%s/%08d%s", testdir
, fileNum
, extension
);
9968 cf
= PR_Open(cfn
, PR_RDONLY
, 0);
9972 prStatus
= PR_GetOpenFileInfo(cf
, &info
);
9973 if (prStatus
!= PR_SUCCESS
) {
9977 pCertItem
= SECITEM_AllocItem(NULL
, pCertItem
, info
.size
);
9979 numBytes
= PR_Read(cf
, pCertItem
->data
, info
.size
);
9982 if (numBytes
!= info
.size
) {
9983 SECITEM_FreeItem(pCertItem
, PR_FALSE
);
9984 PORT_SetError(SEC_ERROR_IO
);
9987 fprintf(stderr
, "using %s\n", cfn
);
9991 fprintf(stderr
, "failed to use %s\n", cfn
);
9998 * Used by both client and server.
9999 * Called from HandleServerHelloDone and from SendServerHelloSequence.
10002 ssl3_SendCertificate(sslSocket
*ss
)
10005 CERTCertificateList
*certChain
;
10008 SSL3KEAType certIndex
;
10014 SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
10015 SSL_GETPID(), ss
->fd
));
10017 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
10018 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
10020 if (ss
->sec
.localCert
)
10021 CERT_DestroyCertificate(ss
->sec
.localCert
);
10022 if (ss
->sec
.isServer
) {
10023 sslServerCerts
* sc
= NULL
;
10025 /* XXX SSLKEAType isn't really a good choice for
10026 * indexing certificates (it breaks when we deal
10027 * with (EC)DHE-* cipher suites. This hack ensures
10028 * the RSA cert is picked for (EC)DHE-RSA.
10029 * Revisit this when we add server side support
10030 * for ECDHE-ECDSA or client-side authentication
10031 * using EC certificates.
10033 if ((ss
->ssl3
.hs
.kea_def
->kea
== kea_ecdhe_rsa
) ||
10034 (ss
->ssl3
.hs
.kea_def
->kea
== kea_dhe_rsa
)) {
10035 certIndex
= kt_rsa
;
10037 certIndex
= ss
->ssl3
.hs
.kea_def
->exchKeyType
;
10039 sc
= ss
->serverCerts
+ certIndex
;
10040 certChain
= sc
->serverCertChain
;
10041 ss
->sec
.authKeyBits
= sc
->serverKeyBits
;
10042 ss
->sec
.authAlgorithm
= ss
->ssl3
.hs
.kea_def
->signKeyType
;
10043 ss
->sec
.localCert
= CERT_DupCertificate(sc
->serverCert
);
10045 certChain
= ss
->ssl3
.clientCertChain
;
10046 ss
->sec
.localCert
= CERT_DupCertificate(ss
->ssl3
.clientCertificate
);
10050 rv
= get_fake_cert(&fakeCert
, &ndex
);
10054 for (i
= 0; i
< certChain
->len
; i
++) {
10056 if (fakeCert
.len
> 0 && i
== ndex
) {
10057 len
+= fakeCert
.len
+ 3;
10059 len
+= certChain
->certs
[i
].len
+ 3;
10062 len
+= certChain
->certs
[i
].len
+ 3;
10067 rv
= ssl3_AppendHandshakeHeader(ss
, certificate
, len
+ 3);
10068 if (rv
!= SECSuccess
) {
10069 return rv
; /* err set by AppendHandshake. */
10071 rv
= ssl3_AppendHandshakeNumber(ss
, len
, 3);
10072 if (rv
!= SECSuccess
) {
10073 return rv
; /* err set by AppendHandshake. */
10076 for (i
= 0; i
< certChain
->len
; i
++) {
10078 if (fakeCert
.len
> 0 && i
== ndex
) {
10079 rv
= ssl3_AppendHandshakeVariable(ss
, fakeCert
.data
,
10081 SECITEM_FreeItem(&fakeCert
, PR_FALSE
);
10083 rv
= ssl3_AppendHandshakeVariable(ss
, certChain
->certs
[i
].data
,
10084 certChain
->certs
[i
].len
, 3);
10087 rv
= ssl3_AppendHandshakeVariable(ss
, certChain
->certs
[i
].data
,
10088 certChain
->certs
[i
].len
, 3);
10090 if (rv
!= SECSuccess
) {
10091 return rv
; /* err set by AppendHandshake. */
10100 * Used by server only.
10101 * single-stapling, send only a single cert status
10104 ssl3_SendCertificateStatus(sslSocket
*ss
)
10108 SECItemArray
*statusToSend
= NULL
;
10109 SSL3KEAType certIndex
;
10111 SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
10112 SSL_GETPID(), ss
->fd
));
10114 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
10115 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
10116 PORT_Assert( ss
->sec
.isServer
);
10118 if (!ssl3_ExtensionNegotiated(ss
, ssl_cert_status_xtn
))
10121 /* Use certStatus based on the cert being used. */
10122 if ((ss
->ssl3
.hs
.kea_def
->kea
== kea_ecdhe_rsa
) ||
10123 (ss
->ssl3
.hs
.kea_def
->kea
== kea_dhe_rsa
)) {
10124 certIndex
= kt_rsa
;
10126 certIndex
= ss
->ssl3
.hs
.kea_def
->exchKeyType
;
10128 if (ss
->certStatusArray
[certIndex
] && ss
->certStatusArray
[certIndex
]->len
) {
10129 statusToSend
= ss
->certStatusArray
[certIndex
];
10134 /* Use the array's first item only (single stapling) */
10135 len
= 1 + statusToSend
->items
[0].len
+ 3;
10137 rv
= ssl3_AppendHandshakeHeader(ss
, certificate_status
, len
);
10138 if (rv
!= SECSuccess
) {
10139 return rv
; /* err set by AppendHandshake. */
10141 rv
= ssl3_AppendHandshakeNumber(ss
, 1 /*ocsp*/, 1);
10142 if (rv
!= SECSuccess
)
10143 return rv
; /* err set by AppendHandshake. */
10145 rv
= ssl3_AppendHandshakeVariable(ss
,
10146 statusToSend
->items
[0].data
,
10147 statusToSend
->items
[0].len
,
10149 if (rv
!= SECSuccess
)
10150 return rv
; /* err set by AppendHandshake. */
10155 /* This is used to delete the CA certificates in the peer certificate chain
10156 * from the cert database after they've been validated.
10159 ssl3_CleanupPeerCerts(sslSocket
*ss
)
10161 PLArenaPool
* arena
= ss
->ssl3
.peerCertArena
;
10162 ssl3CertNode
*certs
= (ssl3CertNode
*)ss
->ssl3
.peerCertChain
;
10164 for (; certs
; certs
= certs
->next
) {
10165 CERT_DestroyCertificate(certs
->cert
);
10167 if (arena
) PORT_FreeArena(arena
, PR_FALSE
);
10168 ss
->ssl3
.peerCertArena
= NULL
;
10169 ss
->ssl3
.peerCertChain
= NULL
;
10173 ssl3_CopyPeerCertsFromSID(sslSocket
*ss
, sslSessionID
*sid
)
10175 PLArenaPool
*arena
;
10176 ssl3CertNode
*lastCert
= NULL
;
10177 ssl3CertNode
*certs
= NULL
;
10180 if (!sid
->peerCertChain
[0])
10182 PORT_Assert(!ss
->ssl3
.peerCertArena
);
10183 PORT_Assert(!ss
->ssl3
.peerCertChain
);
10184 ss
->ssl3
.peerCertArena
= arena
= PORT_NewArena(DER_DEFAULT_CHUNKSIZE
);
10185 for (i
= 0; i
< MAX_PEER_CERT_CHAIN_SIZE
&& sid
->peerCertChain
[i
]; i
++) {
10186 ssl3CertNode
*c
= PORT_ArenaNew(arena
, ssl3CertNode
);
10187 c
->cert
= CERT_DupCertificate(sid
->peerCertChain
[i
]);
10190 lastCert
->next
= c
;
10196 ss
->ssl3
.peerCertChain
= certs
;
10200 ssl3_CopyPeerCertsToSID(ssl3CertNode
*certs
, sslSessionID
*sid
)
10203 ssl3CertNode
*c
= certs
;
10204 for (; i
< MAX_PEER_CERT_CHAIN_SIZE
&& c
; i
++, c
= c
->next
) {
10205 PORT_Assert(!sid
->peerCertChain
[i
]);
10206 sid
->peerCertChain
[i
] = CERT_DupCertificate(c
->cert
);
10210 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
10211 * ssl3 CertificateStatus message.
10212 * Caller must hold Handshake and RecvBuf locks.
10213 * This is always called before ssl3_HandleCertificate, even if the Certificate
10214 * message is sent first.
10217 ssl3_HandleCertificateStatus(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
10219 PRInt32 status
, len
;
10221 if (ss
->ssl3
.hs
.ws
!= wait_certificate_status
) {
10222 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
10223 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS
);
10227 PORT_Assert(!ss
->sec
.isServer
);
10229 /* Consume the CertificateStatusType enum */
10230 status
= ssl3_ConsumeHandshakeNumber(ss
, 1, &b
, &length
);
10231 if (status
!= 1 /* ocsp */) {
10235 len
= ssl3_ConsumeHandshakeNumber(ss
, 3, &b
, &length
);
10236 if (len
!= length
) {
10240 #define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */
10241 if (length
> MAX_CERTSTATUS_LEN
)
10243 #undef MAX_CERTSTATUS_LEN
10245 /* Array size 1, because we currently implement single-stapling only */
10246 SECITEM_AllocArray(NULL
, &ss
->sec
.ci
.sid
->peerCertStatus
, 1);
10247 if (!ss
->sec
.ci
.sid
->peerCertStatus
.items
)
10250 ss
->sec
.ci
.sid
->peerCertStatus
.items
[0].data
= PORT_Alloc(length
);
10252 if (!ss
->sec
.ci
.sid
->peerCertStatus
.items
[0].data
) {
10253 SECITEM_FreeArray(&ss
->sec
.ci
.sid
->peerCertStatus
, PR_FALSE
);
10257 PORT_Memcpy(ss
->sec
.ci
.sid
->peerCertStatus
.items
[0].data
, b
, length
);
10258 ss
->sec
.ci
.sid
->peerCertStatus
.items
[0].len
= length
;
10259 ss
->sec
.ci
.sid
->peerCertStatus
.items
[0].type
= siBuffer
;
10261 return ssl3_AuthCertificate(ss
);
10264 return ssl3_DecodeError(ss
);
10267 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
10268 * ssl3 Certificate message.
10269 * Caller must hold Handshake and RecvBuf locks.
10272 ssl3_HandleCertificate(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
10275 ssl3CertNode
* lastCert
= NULL
;
10276 PRInt32 remaining
= 0;
10279 PRBool isServer
= (PRBool
)(!!ss
->sec
.isServer
);
10281 SSL3AlertDescription desc
;
10282 int errCode
= SSL_ERROR_RX_MALFORMED_CERTIFICATE
;
10285 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
10286 SSL_GETPID(), ss
->fd
));
10287 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
10288 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
10290 if ((isServer
&& ss
->ssl3
.hs
.ws
!= wait_client_cert
) ||
10291 (!isServer
&& ss
->ssl3
.hs
.ws
!= wait_server_cert
)) {
10292 desc
= unexpected_message
;
10293 errCode
= SSL_ERROR_RX_UNEXPECTED_CERTIFICATE
;
10297 if (ss
->sec
.peerCert
!= NULL
) {
10298 if (ss
->sec
.peerKey
) {
10299 SECKEY_DestroyPublicKey(ss
->sec
.peerKey
);
10300 ss
->sec
.peerKey
= NULL
;
10302 CERT_DestroyCertificate(ss
->sec
.peerCert
);
10303 ss
->sec
.peerCert
= NULL
;
10306 ssl3_CleanupPeerCerts(ss
);
10307 isTLS
= (PRBool
)(ss
->ssl3
.prSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
10309 /* It is reported that some TLS client sends a Certificate message
10310 ** with a zero-length message body. We'll treat that case like a
10311 ** normal no_certificates message to maximize interoperability.
10314 remaining
= ssl3_ConsumeHandshakeNumber(ss
, 3, &b
, &length
);
10316 goto loser
; /* fatal alert already sent by ConsumeHandshake. */
10317 if ((PRUint32
)remaining
> length
)
10322 if (!(isTLS
&& isServer
)) {
10323 desc
= bad_certificate
;
10326 /* This is TLS's version of a no_certificate alert. */
10327 /* I'm a server. I've requested a client cert. He hasn't got one. */
10328 rv
= ssl3_HandleNoCertificate(ss
);
10329 if (rv
!= SECSuccess
) {
10330 errCode
= PORT_GetError();
10333 ss
->ssl3
.hs
.ws
= wait_client_key
;
10337 ss
->ssl3
.peerCertArena
= PORT_NewArena(DER_DEFAULT_CHUNKSIZE
);
10338 if (ss
->ssl3
.peerCertArena
== NULL
) {
10339 goto loser
; /* don't send alerts on memory errors */
10342 /* First get the peer cert. */
10347 size
= ssl3_ConsumeHandshakeNumber(ss
, 3, &b
, &length
);
10349 goto loser
; /* fatal alert already sent by ConsumeHandshake. */
10351 if (remaining
< size
)
10355 certItem
.len
= size
;
10360 ss
->sec
.peerCert
= CERT_NewTempCertificate(ss
->dbHandle
, &certItem
, NULL
,
10361 PR_FALSE
, PR_TRUE
);
10362 if (ss
->sec
.peerCert
== NULL
) {
10363 /* We should report an alert if the cert was bad, but not if the
10364 * problem was just some local problem, like memory error.
10366 goto ambiguous_err
;
10369 /* Now get all of the CA certs. */
10370 while (remaining
> 0) {
10375 size
= ssl3_ConsumeHandshakeNumber(ss
, 3, &b
, &length
);
10377 goto loser
; /* fatal alert already sent by ConsumeHandshake. */
10379 if (remaining
< size
)
10383 certItem
.len
= size
;
10388 c
= PORT_ArenaNew(ss
->ssl3
.peerCertArena
, ssl3CertNode
);
10390 goto loser
; /* don't send alerts on memory errors */
10393 c
->cert
= CERT_NewTempCertificate(ss
->dbHandle
, &certItem
, NULL
,
10394 PR_FALSE
, PR_TRUE
);
10395 if (c
->cert
== NULL
) {
10396 goto ambiguous_err
;
10401 lastCert
->next
= c
;
10403 ss
->ssl3
.peerCertChain
= c
;
10408 if (remaining
!= 0)
10411 SECKEY_UpdateCertPQG(ss
->sec
.peerCert
);
10413 if (!isServer
&& ssl3_ExtensionNegotiated(ss
, ssl_cert_status_xtn
)) {
10414 ss
->ssl3
.hs
.ws
= wait_certificate_status
;
10417 rv
= ssl3_AuthCertificate(ss
); /* sets ss->ssl3.hs.ws */
10423 errCode
= PORT_GetError();
10425 case PR_OUT_OF_MEMORY_ERROR
:
10426 case SEC_ERROR_BAD_DATABASE
:
10427 case SEC_ERROR_NO_MEMORY
:
10429 desc
= internal_error
;
10434 ssl3_SendAlertForCertError(ss
, errCode
);
10438 desc
= isTLS
? decode_error
: bad_certificate
;
10441 (void)SSL3_SendAlert(ss
, alert_fatal
, desc
);
10444 (void)ssl_MapLowLevelError(errCode
);
10449 ssl3_AuthCertificate(sslSocket
*ss
)
10452 PRBool isServer
= (PRBool
)(!!ss
->sec
.isServer
);
10455 ss
->ssl3
.hs
.authCertificatePending
= PR_FALSE
;
10458 * Ask caller-supplied callback function to validate cert chain.
10460 rv
= (SECStatus
)(*ss
->authCertificate
)(ss
->authCertificateArg
, ss
->fd
,
10461 PR_TRUE
, isServer
);
10463 errCode
= PORT_GetError();
10464 if (rv
!= SECWouldBlock
) {
10465 if (ss
->handleBadCert
) {
10466 rv
= (*ss
->handleBadCert
)(ss
->badCertArg
, ss
->fd
);
10470 if (rv
== SECWouldBlock
) {
10471 if (ss
->sec
.isServer
) {
10472 errCode
= SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS
;
10477 ss
->ssl3
.hs
.authCertificatePending
= PR_TRUE
;
10481 if (rv
!= SECSuccess
) {
10482 ssl3_SendAlertForCertError(ss
, errCode
);
10487 ss
->sec
.ci
.sid
->peerCert
= CERT_DupCertificate(ss
->sec
.peerCert
);
10488 ssl3_CopyPeerCertsToSID(ss
->ssl3
.peerCertChain
, ss
->sec
.ci
.sid
);
10490 if (!ss
->sec
.isServer
) {
10491 CERTCertificate
*cert
= ss
->sec
.peerCert
;
10493 /* set the server authentication and key exchange types and sizes
10494 ** from the value in the cert. If the key exchange key is different,
10495 ** it will get fixed when we handle the server key exchange message.
10497 SECKEYPublicKey
* pubKey
= CERT_ExtractPublicKey(cert
);
10498 ss
->sec
.authAlgorithm
= ss
->ssl3
.hs
.kea_def
->signKeyType
;
10499 ss
->sec
.keaType
= ss
->ssl3
.hs
.kea_def
->exchKeyType
;
10501 ss
->sec
.keaKeyBits
= ss
->sec
.authKeyBits
=
10502 SECKEY_PublicKeyStrengthInBits(pubKey
);
10503 #ifndef NSS_DISABLE_ECC
10504 if (ss
->sec
.keaType
== kt_ecdh
) {
10505 /* Get authKeyBits from signing key.
10506 * XXX The code below uses a quick approximation of
10507 * key size based on cert->signatureWrap.signature.data
10508 * (which contains the DER encoded signature). The field
10509 * cert->signatureWrap.signature.len contains the
10510 * length of the encoded signature in bits.
10512 if (ss
->ssl3
.hs
.kea_def
->kea
== kea_ecdh_ecdsa
) {
10513 ss
->sec
.authKeyBits
=
10514 cert
->signatureWrap
.signature
.data
[3]*8;
10515 if (cert
->signatureWrap
.signature
.data
[4] == 0x00)
10516 ss
->sec
.authKeyBits
-= 8;
10518 * XXX: if cert is not signed by ecdsa we should
10519 * destroy pubKey and goto bad_cert
10521 } else if (ss
->ssl3
.hs
.kea_def
->kea
== kea_ecdh_rsa
) {
10522 ss
->sec
.authKeyBits
= cert
->signatureWrap
.signature
.len
;
10524 * XXX: if cert is not signed by rsa we should
10525 * destroy pubKey and goto bad_cert
10529 #endif /* NSS_DISABLE_ECC */
10530 SECKEY_DestroyPublicKey(pubKey
);
10534 if (ss
->ssl3
.hs
.kea_def
->ephemeral
) {
10535 ss
->ssl3
.hs
.ws
= wait_server_key
; /* require server_key_exchange */
10537 ss
->ssl3
.hs
.ws
= wait_cert_request
; /* disallow server_key_exchange */
10540 ss
->ssl3
.hs
.ws
= wait_client_key
;
10543 PORT_Assert(rv
== SECSuccess
);
10544 if (rv
!= SECSuccess
) {
10545 errCode
= SEC_ERROR_LIBRARY_FAILURE
;
10553 (void)ssl_MapLowLevelError(errCode
);
10557 static SECStatus
ssl3_FinishHandshake(sslSocket
*ss
);
10560 ssl3_AlwaysFail(sslSocket
* ss
)
10562 PORT_SetError(PR_INVALID_STATE_ERROR
);
10566 /* Caller must hold 1stHandshakeLock.
10569 ssl3_AuthCertificateComplete(sslSocket
*ss
, PRErrorCode error
)
10573 PORT_Assert(ss
->opt
.noLocks
|| ssl_Have1stHandshakeLock(ss
));
10575 if (ss
->sec
.isServer
) {
10576 PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS
);
10580 ssl_GetRecvBufLock(ss
);
10581 ssl_GetSSL3HandshakeLock(ss
);
10583 if (!ss
->ssl3
.hs
.authCertificatePending
) {
10584 PORT_SetError(PR_INVALID_STATE_ERROR
);
10589 ss
->ssl3
.hs
.authCertificatePending
= PR_FALSE
;
10592 ss
->ssl3
.hs
.restartTarget
= ssl3_AlwaysFail
;
10593 ssl3_SendAlertForCertError(ss
, error
);
10595 } else if (ss
->ssl3
.hs
.restartTarget
!= NULL
) {
10596 sslRestartTarget target
= ss
->ssl3
.hs
.restartTarget
;
10597 ss
->ssl3
.hs
.restartTarget
= NULL
;
10599 if (target
== ssl3_FinishHandshake
) {
10600 SSL_TRC(3,("%d: SSL3[%p]: certificate authentication lost the race"
10601 " with peer's finished message", SSL_GETPID(), ss
->fd
));
10605 /* Even if we blocked here, we have accomplished enough to claim
10606 * success. Any remaining work will be taken care of by subsequent
10607 * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc.
10609 if (rv
== SECWouldBlock
) {
10613 SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with"
10614 " peer's finished message", SSL_GETPID(), ss
->fd
));
10616 PORT_Assert(!ss
->ssl3
.hs
.isResuming
);
10617 PORT_Assert(ss
->ssl3
.hs
.ws
!= idle_handshake
);
10619 if (ss
->opt
.enableFalseStart
&&
10620 !ss
->firstHsDone
&&
10621 !ss
->ssl3
.hs
.isResuming
&&
10622 ssl3_WaitingForStartOfServerSecondRound(ss
)) {
10623 /* ssl3_SendClientSecondRound deferred the false start check because
10624 * certificate authentication was pending, so we do it now if we still
10625 * haven't received any of the server's second round yet.
10627 rv
= ssl3_CheckFalseStart(ss
);
10634 ssl_ReleaseSSL3HandshakeLock(ss
);
10635 ssl_ReleaseRecvBufLock(ss
);
10641 ssl3_ComputeTLSFinished(ssl3CipherSpec
*spec
,
10643 const SSL3Hashes
* hashes
,
10644 TLSFinished
* tlsFinished
)
10646 const char * label
;
10650 label
= isServer
? "server finished" : "client finished";
10653 rv
= ssl3_TLSPRFWithMasterSecret(spec
, label
, len
, hashes
->u
.raw
,
10654 hashes
->len
, tlsFinished
->verify_data
,
10655 sizeof tlsFinished
->verify_data
);
10660 /* The calling function must acquire and release the appropriate
10661 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
10662 * ss->ssl3.crSpec).
10665 ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec
*spec
, const char *label
,
10666 unsigned int labelLen
, const unsigned char *val
, unsigned int valLen
,
10667 unsigned char *out
, unsigned int outLen
)
10669 SECStatus rv
= SECSuccess
;
10671 if (spec
->master_secret
&& !spec
->bypassCiphers
) {
10672 SECItem param
= {siBuffer
, NULL
, 0};
10673 CK_MECHANISM_TYPE mech
= CKM_TLS_PRF_GENERAL
;
10674 PK11Context
*prf_context
;
10675 unsigned int retLen
;
10677 if (spec
->version
>= SSL_LIBRARY_VERSION_TLS_1_2
) {
10678 mech
= CKM_NSS_TLS_PRF_GENERAL_SHA256
;
10680 prf_context
= PK11_CreateContextBySymKey(mech
, CKA_SIGN
,
10681 spec
->master_secret
, ¶m
);
10685 rv
= PK11_DigestBegin(prf_context
);
10686 rv
|= PK11_DigestOp(prf_context
, (unsigned char *) label
, labelLen
);
10687 rv
|= PK11_DigestOp(prf_context
, val
, valLen
);
10688 rv
|= PK11_DigestFinal(prf_context
, out
, &retLen
, outLen
);
10689 PORT_Assert(rv
!= SECSuccess
|| retLen
== outLen
);
10691 PK11_DestroyContext(prf_context
, PR_TRUE
);
10693 /* bypass PKCS11 */
10694 #ifdef NO_PKCS11_BYPASS
10695 PORT_Assert(spec
->master_secret
);
10696 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
10699 SECItem inData
= { siBuffer
, };
10700 SECItem outData
= { siBuffer
, };
10701 PRBool isFIPS
= PR_FALSE
;
10703 inData
.data
= (unsigned char *) val
;
10704 inData
.len
= valLen
;
10705 outData
.data
= out
;
10706 outData
.len
= outLen
;
10707 if (spec
->version
>= SSL_LIBRARY_VERSION_TLS_1_2
) {
10708 rv
= TLS_P_hash(HASH_AlgSHA256
, &spec
->msItem
, label
, &inData
,
10711 rv
= TLS_PRF(&spec
->msItem
, label
, &inData
, &outData
, isFIPS
);
10713 PORT_Assert(rv
!= SECSuccess
|| outData
.len
== outLen
);
10719 /* called from ssl3_SendClientSecondRound
10720 * ssl3_HandleFinished
10723 ssl3_SendNextProto(sslSocket
*ss
)
10727 static const unsigned char padding
[32] = {0};
10729 if (ss
->ssl3
.nextProto
.len
== 0 ||
10730 ss
->ssl3
.nextProtoState
== SSL_NEXT_PROTO_SELECTED
) {
10734 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
10735 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
10737 padding_len
= 32 - ((ss
->ssl3
.nextProto
.len
+ 2) % 32);
10739 rv
= ssl3_AppendHandshakeHeader(ss
, next_proto
, ss
->ssl3
.nextProto
.len
+
10741 if (rv
!= SECSuccess
) {
10742 return rv
; /* error code set by AppendHandshakeHeader */
10744 rv
= ssl3_AppendHandshakeVariable(ss
, ss
->ssl3
.nextProto
.data
,
10745 ss
->ssl3
.nextProto
.len
, 1);
10746 if (rv
!= SECSuccess
) {
10747 return rv
; /* error code set by AppendHandshake */
10749 rv
= ssl3_AppendHandshakeVariable(ss
, padding
, padding_len
, 1);
10750 if (rv
!= SECSuccess
) {
10751 return rv
; /* error code set by AppendHandshake */
10756 /* called from ssl3_SendFinished
10758 * This function is simply a debugging aid and therefore does not return a
10761 ssl3_RecordKeyLog(sslSocket
*ss
)
10765 char buf
[14 /* "CLIENT_RANDOM " */ +
10766 SSL3_RANDOM_LENGTH
*2 /* client_random */ +
10768 48*2 /* master secret */ +
10772 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
10774 if (!ssl_keylog_iob
)
10777 rv
= PK11_ExtractKeyValue(ss
->ssl3
.cwSpec
->master_secret
);
10778 if (rv
!= SECSuccess
)
10781 ssl_GetSpecReadLock(ss
);
10783 /* keyData does not need to be freed. */
10784 keyData
= PK11_GetKeyData(ss
->ssl3
.cwSpec
->master_secret
);
10785 if (!keyData
|| !keyData
->data
|| keyData
->len
!= 48) {
10786 ssl_ReleaseSpecReadLock(ss
);
10790 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
10792 /* There could be multiple, concurrent writers to the
10793 * keylog, so we have to do everything in a single call to
10796 memcpy(buf
, "CLIENT_RANDOM ", 14);
10798 hexEncode(buf
+ j
, ss
->ssl3
.hs
.client_random
.rand
, SSL3_RANDOM_LENGTH
);
10799 j
+= SSL3_RANDOM_LENGTH
*2;
10801 hexEncode(buf
+ j
, keyData
->data
, 48);
10805 PORT_Assert(j
== sizeof(buf
));
10807 ssl_ReleaseSpecReadLock(ss
);
10809 if (fwrite(buf
, sizeof(buf
), 1, ssl_keylog_iob
) != 1)
10811 fflush(ssl_keylog_iob
);
10815 /* called from ssl3_SendClientSecondRound
10816 * ssl3_HandleFinished
10819 ssl3_SendEncryptedExtensions(sslSocket
*ss
)
10821 static const char CHANNEL_ID_MAGIC
[] = "TLS Channel ID signature";
10822 static const char CHANNEL_ID_RESUMPTION_MAGIC
[] = "Resumption";
10823 /* This is the ASN.1 prefix for a P-256 public key. Specifically it's:
10826 * OID id-ecPublicKey
10828 * BIT STRING, length 66, 0 trailing bits: 0x04
10830 * The 0x04 in the BIT STRING is the prefix for an uncompressed, X9.62
10831 * public key. Following that are the two field elements as 32-byte,
10832 * big-endian numbers, as required by the Channel ID. */
10833 static const unsigned char P256_SPKI_PREFIX
[] = {
10834 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
10835 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
10836 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
10839 /* ChannelIDs are always 128 bytes long: 64 bytes of P-256 public key and 64
10840 * bytes of ECDSA signature. */
10841 static const int CHANNEL_ID_PUBLIC_KEY_LENGTH
= 64;
10842 static const int CHANNEL_ID_LENGTH
= 128;
10844 SECStatus rv
= SECFailure
;
10845 SECItem
*spki
= NULL
;
10847 const unsigned char *pub_bytes
;
10848 unsigned char signed_data
[sizeof(CHANNEL_ID_MAGIC
) +
10849 sizeof(CHANNEL_ID_RESUMPTION_MAGIC
) +
10850 sizeof(SSL3Hashes
)*2];
10851 size_t signed_data_len
;
10852 unsigned char digest
[SHA256_LENGTH
];
10853 SECItem digest_item
;
10854 unsigned char signature
[64];
10855 SECItem signature_item
;
10857 PORT_Assert(ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
10858 PORT_Assert(ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
10860 if (ss
->ssl3
.channelID
== NULL
)
10863 PORT_Assert(ssl3_ExtensionNegotiated(ss
, ssl_channel_id_xtn
));
10865 if (SECKEY_GetPrivateKeyType(ss
->ssl3
.channelID
) != ecKey
||
10866 PK11_SignatureLen(ss
->ssl3
.channelID
) != sizeof(signature
)) {
10867 PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY
);
10872 ssl_GetSpecReadLock(ss
);
10873 rv
= ssl3_ComputeHandshakeHashes(ss
, ss
->ssl3
.cwSpec
, &hashes
, 0);
10874 ssl_ReleaseSpecReadLock(ss
);
10876 if (rv
!= SECSuccess
)
10879 rv
= ssl3_AppendHandshakeHeader(ss
, encrypted_extensions
,
10880 2 + 2 + CHANNEL_ID_LENGTH
);
10881 if (rv
!= SECSuccess
)
10882 goto loser
; /* error code set by AppendHandshakeHeader */
10883 rv
= ssl3_AppendHandshakeNumber(ss
, ssl_channel_id_xtn
, 2);
10884 if (rv
!= SECSuccess
)
10885 goto loser
; /* error code set by AppendHandshake */
10886 rv
= ssl3_AppendHandshakeNumber(ss
, CHANNEL_ID_LENGTH
, 2);
10887 if (rv
!= SECSuccess
)
10888 goto loser
; /* error code set by AppendHandshake */
10890 spki
= SECKEY_EncodeDERSubjectPublicKeyInfo(ss
->ssl3
.channelIDPub
);
10892 if (spki
->len
!= sizeof(P256_SPKI_PREFIX
) + CHANNEL_ID_PUBLIC_KEY_LENGTH
||
10893 memcmp(spki
->data
, P256_SPKI_PREFIX
, sizeof(P256_SPKI_PREFIX
)) != 0) {
10894 PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY
);
10899 pub_bytes
= spki
->data
+ sizeof(P256_SPKI_PREFIX
);
10901 signed_data_len
= 0;
10902 memcpy(signed_data
+ signed_data_len
, CHANNEL_ID_MAGIC
,
10903 sizeof(CHANNEL_ID_MAGIC
));
10904 signed_data_len
+= sizeof(CHANNEL_ID_MAGIC
);
10905 if (ss
->ssl3
.hs
.isResuming
) {
10906 SECItem
*originalHandshakeHash
=
10907 &ss
->sec
.ci
.sid
->u
.ssl3
.originalHandshakeHash
;
10908 PORT_Assert(originalHandshakeHash
->len
> 0);
10910 memcpy(signed_data
+ signed_data_len
, CHANNEL_ID_RESUMPTION_MAGIC
,
10911 sizeof(CHANNEL_ID_RESUMPTION_MAGIC
));
10912 signed_data_len
+= sizeof(CHANNEL_ID_RESUMPTION_MAGIC
);
10913 memcpy(signed_data
+ signed_data_len
, originalHandshakeHash
->data
,
10914 originalHandshakeHash
->len
);
10915 signed_data_len
+= originalHandshakeHash
->len
;
10917 memcpy(signed_data
+ signed_data_len
, hashes
.u
.raw
, hashes
.len
);
10918 signed_data_len
+= hashes
.len
;
10920 rv
= PK11_HashBuf(SEC_OID_SHA256
, digest
, signed_data
, signed_data_len
);
10921 if (rv
!= SECSuccess
)
10924 digest_item
.data
= digest
;
10925 digest_item
.len
= sizeof(digest
);
10927 signature_item
.data
= signature
;
10928 signature_item
.len
= sizeof(signature
);
10930 rv
= PK11_Sign(ss
->ssl3
.channelID
, &signature_item
, &digest_item
);
10931 if (rv
!= SECSuccess
)
10934 rv
= ssl3_AppendHandshake(ss
, pub_bytes
, CHANNEL_ID_PUBLIC_KEY_LENGTH
);
10935 if (rv
!= SECSuccess
)
10937 rv
= ssl3_AppendHandshake(ss
, signature
, sizeof(signature
));
10941 SECITEM_FreeItem(spki
, PR_TRUE
);
10942 if (ss
->ssl3
.channelID
) {
10943 SECKEY_DestroyPrivateKey(ss
->ssl3
.channelID
);
10944 ss
->ssl3
.channelID
= NULL
;
10946 if (ss
->ssl3
.channelIDPub
) {
10947 SECKEY_DestroyPublicKey(ss
->ssl3
.channelIDPub
);
10948 ss
->ssl3
.channelIDPub
= NULL
;
10954 /* ssl3_RestartHandshakeAfterChannelIDReq is called to restart a handshake
10955 * after a ChannelID callback returned SECWouldBlock. At this point we have
10956 * processed the server's ServerHello but not yet any further messages. We will
10957 * always get a message from the server after a ServerHello so either they are
10958 * waiting in the buffer or we'll get network I/O. */
10960 ssl3_RestartHandshakeAfterChannelIDReq(sslSocket
*ss
,
10961 SECKEYPublicKey
*channelIDPub
,
10962 SECKEYPrivateKey
*channelID
)
10964 if (ss
->handshake
== 0) {
10965 SECKEY_DestroyPublicKey(channelIDPub
);
10966 SECKEY_DestroyPrivateKey(channelID
);
10967 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
10971 if (channelIDPub
== NULL
||
10972 channelID
== NULL
) {
10974 SECKEY_DestroyPublicKey(channelIDPub
);
10976 SECKEY_DestroyPrivateKey(channelID
);
10977 PORT_SetError(PR_INVALID_ARGUMENT_ERROR
);
10981 if (ss
->ssl3
.channelID
)
10982 SECKEY_DestroyPrivateKey(ss
->ssl3
.channelID
);
10983 if (ss
->ssl3
.channelIDPub
)
10984 SECKEY_DestroyPublicKey(ss
->ssl3
.channelIDPub
);
10986 ss
->handshake
= ssl_GatherRecord1stHandshake
;
10987 ss
->ssl3
.channelID
= channelID
;
10988 ss
->ssl3
.channelIDPub
= channelIDPub
;
10993 /* called from ssl3_SendClientSecondRound
10994 * ssl3_HandleClientHello
10995 * ssl3_HandleFinished
10998 ssl3_SendFinished(sslSocket
*ss
, PRInt32 flags
)
11000 ssl3CipherSpec
*cwSpec
;
11002 PRBool isServer
= ss
->sec
.isServer
;
11004 SSL3Sender sender
= isServer
? sender_server
: sender_client
;
11006 TLSFinished tlsFinished
;
11008 SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss
->fd
));
11010 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
11011 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
11013 ssl_GetSpecReadLock(ss
);
11014 cwSpec
= ss
->ssl3
.cwSpec
;
11015 isTLS
= (PRBool
)(cwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
11016 rv
= ssl3_ComputeHandshakeHashes(ss
, cwSpec
, &hashes
, sender
);
11017 if (isTLS
&& rv
== SECSuccess
) {
11018 rv
= ssl3_ComputeTLSFinished(cwSpec
, isServer
, &hashes
, &tlsFinished
);
11020 ssl_ReleaseSpecReadLock(ss
);
11021 if (rv
!= SECSuccess
) {
11022 goto fail
; /* err code was set by ssl3_ComputeHandshakeHashes */
11027 ss
->ssl3
.hs
.finishedMsgs
.tFinished
[1] = tlsFinished
;
11029 ss
->ssl3
.hs
.finishedMsgs
.tFinished
[0] = tlsFinished
;
11030 ss
->ssl3
.hs
.finishedBytes
= sizeof tlsFinished
;
11031 rv
= ssl3_AppendHandshakeHeader(ss
, finished
, sizeof tlsFinished
);
11032 if (rv
!= SECSuccess
)
11033 goto fail
; /* err set by AppendHandshake. */
11034 rv
= ssl3_AppendHandshake(ss
, &tlsFinished
, sizeof tlsFinished
);
11035 if (rv
!= SECSuccess
)
11036 goto fail
; /* err set by AppendHandshake. */
11039 ss
->ssl3
.hs
.finishedMsgs
.sFinished
[1] = hashes
.u
.s
;
11041 ss
->ssl3
.hs
.finishedMsgs
.sFinished
[0] = hashes
.u
.s
;
11042 PORT_Assert(hashes
.len
== sizeof hashes
.u
.s
);
11043 ss
->ssl3
.hs
.finishedBytes
= sizeof hashes
.u
.s
;
11044 rv
= ssl3_AppendHandshakeHeader(ss
, finished
, sizeof hashes
.u
.s
);
11045 if (rv
!= SECSuccess
)
11046 goto fail
; /* err set by AppendHandshake. */
11047 rv
= ssl3_AppendHandshake(ss
, &hashes
.u
.s
, sizeof hashes
.u
.s
);
11048 if (rv
!= SECSuccess
)
11049 goto fail
; /* err set by AppendHandshake. */
11051 rv
= ssl3_FlushHandshake(ss
, flags
);
11052 if (rv
!= SECSuccess
) {
11053 goto fail
; /* error code set by ssl3_FlushHandshake */
11056 ssl3_RecordKeyLog(ss
);
11064 /* wrap the master secret, and put it into the SID.
11065 * Caller holds the Spec read lock.
11068 ssl3_CacheWrappedMasterSecret(sslSocket
*ss
, sslSessionID
*sid
,
11069 ssl3CipherSpec
*spec
, SSL3KEAType effectiveExchKeyType
)
11071 PK11SymKey
* wrappingKey
= NULL
;
11072 PK11SlotInfo
* symKeySlot
;
11073 void * pwArg
= ss
->pkcs11PinArg
;
11074 SECStatus rv
= SECFailure
;
11075 PRBool isServer
= ss
->sec
.isServer
;
11076 CK_MECHANISM_TYPE mechanism
= CKM_INVALID_MECHANISM
;
11077 symKeySlot
= PK11_GetSlotFromKey(spec
->master_secret
);
11082 /* these next few functions are mere accessors and don't fail. */
11083 sid
->u
.ssl3
.masterWrapIndex
= wrapKeyIndex
=
11084 PK11_GetCurrentWrapIndex(symKeySlot
);
11085 PORT_Assert(wrapKeyIndex
== 0); /* array has only one entry! */
11087 sid
->u
.ssl3
.masterWrapSeries
= incarnation
=
11088 PK11_GetSlotSeries(symKeySlot
);
11089 sid
->u
.ssl3
.masterSlotID
= PK11_GetSlotID(symKeySlot
);
11090 sid
->u
.ssl3
.masterModuleID
= PK11_GetModuleID(symKeySlot
);
11091 sid
->u
.ssl3
.masterValid
= PR_TRUE
;
11092 /* Get the default wrapping key, for wrapping the master secret before
11093 * placing it in the SID cache entry. */
11094 wrappingKey
= PK11_GetWrapKey(symKeySlot
, wrapKeyIndex
,
11095 CKM_INVALID_MECHANISM
, incarnation
,
11098 mechanism
= PK11_GetMechanism(wrappingKey
); /* can't fail. */
11101 /* if the wrappingKey doesn't exist, attempt to create it.
11102 * Note: we intentionally ignore errors here. If we cannot
11103 * generate a wrapping key, it is not fatal to this SSL connection,
11104 * but we will not be able to restart this session.
11106 mechanism
= PK11_GetBestWrapMechanism(symKeySlot
);
11107 keyLength
= PK11_GetBestKeyLength(symKeySlot
, mechanism
);
11108 /* Zero length means fixed key length algorithm, or error.
11111 wrappingKey
= PK11_KeyGen(symKeySlot
, mechanism
, NULL
,
11114 PK11_SetWrapKey(symKeySlot
, wrapKeyIndex
, wrappingKey
);
11118 /* server socket using session cache. */
11119 mechanism
= PK11_GetBestWrapMechanism(symKeySlot
);
11120 if (mechanism
!= CKM_INVALID_MECHANISM
) {
11122 getWrappingKey(ss
, symKeySlot
, effectiveExchKeyType
,
11125 mechanism
= PK11_GetMechanism(wrappingKey
); /* can't fail. */
11130 sid
->u
.ssl3
.masterWrapMech
= mechanism
;
11131 PK11_FreeSlot(symKeySlot
);
11136 wmsItem
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
11137 wmsItem
.len
= sizeof sid
->u
.ssl3
.keys
.wrapped_master_secret
;
11138 rv
= PK11_WrapSymKey(mechanism
, NULL
, wrappingKey
,
11139 spec
->master_secret
, &wmsItem
);
11140 /* rv is examined below. */
11141 sid
->u
.ssl3
.keys
.wrapped_master_secret_len
= wmsItem
.len
;
11142 PK11_FreeSymKey(wrappingKey
);
11147 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
11148 * ssl3 Finished message from the peer.
11149 * Caller must hold Handshake and RecvBuf locks.
11152 ssl3_HandleFinished(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
,
11153 const SSL3Hashes
*hashes
)
11155 sslSessionID
* sid
= ss
->sec
.ci
.sid
;
11156 SECStatus rv
= SECSuccess
;
11157 PRBool isServer
= ss
->sec
.isServer
;
11159 SSL3KEAType effectiveExchKeyType
;
11161 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
11162 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
11164 SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
11165 SSL_GETPID(), ss
->fd
));
11167 if (ss
->ssl3
.hs
.ws
!= wait_finished
) {
11168 SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
11169 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED
);
11173 isTLS
= (PRBool
)(ss
->ssl3
.crSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
11175 TLSFinished tlsFinished
;
11177 if (length
!= sizeof tlsFinished
) {
11178 (void)SSL3_SendAlert(ss
, alert_fatal
, decode_error
);
11179 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED
);
11182 rv
= ssl3_ComputeTLSFinished(ss
->ssl3
.crSpec
, !isServer
,
11183 hashes
, &tlsFinished
);
11185 ss
->ssl3
.hs
.finishedMsgs
.tFinished
[1] = tlsFinished
;
11187 ss
->ssl3
.hs
.finishedMsgs
.tFinished
[0] = tlsFinished
;
11188 ss
->ssl3
.hs
.finishedBytes
= sizeof tlsFinished
;
11189 if (rv
!= SECSuccess
||
11190 0 != NSS_SecureMemcmp(&tlsFinished
, b
, length
)) {
11191 (void)SSL3_SendAlert(ss
, alert_fatal
, decrypt_error
);
11192 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
);
11196 if (length
!= sizeof(SSL3Finished
)) {
11197 (void)ssl3_IllegalParameter(ss
);
11198 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED
);
11203 ss
->ssl3
.hs
.finishedMsgs
.sFinished
[1] = hashes
->u
.s
;
11205 ss
->ssl3
.hs
.finishedMsgs
.sFinished
[0] = hashes
->u
.s
;
11206 PORT_Assert(hashes
->len
== sizeof hashes
->u
.s
);
11207 ss
->ssl3
.hs
.finishedBytes
= sizeof hashes
->u
.s
;
11208 if (0 != NSS_SecureMemcmp(&hashes
->u
.s
, b
, length
)) {
11209 (void)ssl3_HandshakeFailure(ss
);
11210 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
);
11215 ssl_GetXmitBufLock(ss
); /*************************************/
11217 if ((isServer
&& !ss
->ssl3
.hs
.isResuming
) ||
11218 (!isServer
&& ss
->ssl3
.hs
.isResuming
)) {
11221 /* Send a NewSessionTicket message if the client sent us
11222 * either an empty session ticket, or one that did not verify.
11223 * (Note that if either of these conditions was met, then the
11224 * server has sent a SessionTicket extension in the
11225 * ServerHello message.)
11227 if (isServer
&& !ss
->ssl3
.hs
.isResuming
&&
11228 ssl3_ExtensionNegotiated(ss
, ssl_session_ticket_xtn
)) {
11229 /* RFC 5077 Section 3.3: "In the case of a full handshake, the
11230 * server MUST verify the client's Finished message before sending
11231 * the ticket." Presumably, this also means that the client's
11232 * certificate, if any, must be verified beforehand too.
11234 rv
= ssl3_SendNewSessionTicket(ss
);
11235 if (rv
!= SECSuccess
) {
11240 rv
= ssl3_SendChangeCipherSpecs(ss
);
11241 if (rv
!= SECSuccess
) {
11242 goto xmit_loser
; /* err is set. */
11244 /* If this thread is in SSL_SecureSend (trying to write some data)
11245 ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
11246 ** last two handshake messages (change cipher spec and finished)
11247 ** will be sent in the same send/write call as the application data.
11249 if (ss
->writerThread
== PR_GetCurrentThread()) {
11250 flags
= ssl_SEND_FLAG_FORCE_INTO_BUFFER
;
11254 if (!ss
->firstHsDone
) {
11255 rv
= ssl3_SendNextProto(ss
);
11256 if (rv
!= SECSuccess
) {
11257 goto xmit_loser
; /* err code was set. */
11260 rv
= ssl3_SendEncryptedExtensions(ss
);
11261 if (rv
!= SECSuccess
)
11262 goto xmit_loser
; /* err code was set. */
11266 flags
|= ssl_SEND_FLAG_NO_RETRANSMIT
;
11269 rv
= ssl3_SendFinished(ss
, flags
);
11270 if (rv
!= SECSuccess
) {
11271 goto xmit_loser
; /* err is set. */
11276 ssl_ReleaseXmitBufLock(ss
); /*************************************/
11277 if (rv
!= SECSuccess
) {
11281 if (ss
->ssl3
.hs
.kea_def
->kea
== kea_ecdhe_rsa
) {
11282 effectiveExchKeyType
= kt_rsa
;
11284 effectiveExchKeyType
= ss
->ssl3
.hs
.kea_def
->exchKeyType
;
11287 if (sid
->cached
== never_cached
&& !ss
->opt
.noCache
&& ss
->sec
.cache
) {
11288 /* fill in the sid */
11289 sid
->u
.ssl3
.cipherSuite
= ss
->ssl3
.hs
.cipher_suite
;
11290 sid
->u
.ssl3
.compression
= ss
->ssl3
.hs
.compression
;
11291 sid
->u
.ssl3
.policy
= ss
->ssl3
.policy
;
11292 #ifndef NSS_DISABLE_ECC
11293 sid
->u
.ssl3
.negotiatedECCurves
= ss
->ssl3
.hs
.negotiatedECCurves
;
11295 sid
->u
.ssl3
.exchKeyType
= effectiveExchKeyType
;
11296 sid
->version
= ss
->version
;
11297 sid
->authAlgorithm
= ss
->sec
.authAlgorithm
;
11298 sid
->authKeyBits
= ss
->sec
.authKeyBits
;
11299 sid
->keaType
= ss
->sec
.keaType
;
11300 sid
->keaKeyBits
= ss
->sec
.keaKeyBits
;
11301 sid
->lastAccessTime
= sid
->creationTime
= ssl_Time();
11302 sid
->expirationTime
= sid
->creationTime
+ ssl3_sid_timeout
;
11303 sid
->localCert
= CERT_DupCertificate(ss
->sec
.localCert
);
11305 ssl_GetSpecReadLock(ss
); /*************************************/
11307 /* Copy the master secret (wrapped or unwrapped) into the sid */
11308 if (ss
->ssl3
.crSpec
->msItem
.len
&& ss
->ssl3
.crSpec
->msItem
.data
) {
11309 sid
->u
.ssl3
.keys
.wrapped_master_secret_len
=
11310 ss
->ssl3
.crSpec
->msItem
.len
;
11311 memcpy(sid
->u
.ssl3
.keys
.wrapped_master_secret
,
11312 ss
->ssl3
.crSpec
->msItem
.data
, ss
->ssl3
.crSpec
->msItem
.len
);
11313 sid
->u
.ssl3
.masterValid
= PR_TRUE
;
11314 sid
->u
.ssl3
.keys
.msIsWrapped
= PR_FALSE
;
11317 rv
= ssl3_CacheWrappedMasterSecret(ss
, ss
->sec
.ci
.sid
,
11319 effectiveExchKeyType
);
11320 sid
->u
.ssl3
.keys
.msIsWrapped
= PR_TRUE
;
11322 ssl_ReleaseSpecReadLock(ss
); /*************************************/
11324 /* If the wrap failed, we don't cache the sid.
11325 * The connection continues normally however.
11327 ss
->ssl3
.hs
.cacheSID
= rv
== SECSuccess
;
11330 if (ss
->ssl3
.hs
.authCertificatePending
) {
11331 if (ss
->ssl3
.hs
.restartTarget
) {
11332 PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
11333 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
11337 ss
->ssl3
.hs
.restartTarget
= ssl3_FinishHandshake
;
11338 return SECWouldBlock
;
11341 rv
= ssl3_FinishHandshake(ss
);
11345 /* The return type is SECStatus instead of void because this function needs
11346 * to have type sslRestartTarget.
11349 ssl3_FinishHandshake(sslSocket
* ss
)
11351 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
11352 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
11353 PORT_Assert( ss
->ssl3
.hs
.restartTarget
== NULL
);
11355 /* The first handshake is now completed. */
11356 ss
->handshake
= NULL
;
11358 /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid
11359 * until it has verified the server's Finished message." When the server
11360 * sends a NewSessionTicket in a resumption handshake, we must wait until
11361 * the handshake is finished (we have verified the server's Finished
11362 * AND the server's certificate) before we update the ticket in the sid.
11364 * This must be done before we call (*ss->sec.cache)(ss->sec.ci.sid)
11365 * because CacheSID requires the session ticket to already be set, and also
11366 * because of the lazy lock creation scheme used by CacheSID and
11367 * ssl3_SetSIDSessionTicket.
11369 if (ss
->ssl3
.hs
.receivedNewSessionTicket
) {
11370 PORT_Assert(!ss
->sec
.isServer
);
11371 ssl3_SetSIDSessionTicket(ss
->sec
.ci
.sid
, &ss
->ssl3
.hs
.newSessionTicket
);
11372 /* The sid took over the ticket data */
11373 PORT_Assert(!ss
->ssl3
.hs
.newSessionTicket
.ticket
.data
);
11374 ss
->ssl3
.hs
.receivedNewSessionTicket
= PR_FALSE
;
11377 if (ss
->ssl3
.hs
.cacheSID
&& ss
->sec
.isServer
) {
11378 PORT_Assert(ss
->sec
.ci
.sid
->cached
== never_cached
);
11379 (*ss
->sec
.cache
)(ss
->sec
.ci
.sid
);
11380 ss
->ssl3
.hs
.cacheSID
= PR_FALSE
;
11383 ss
->ssl3
.hs
.canFalseStart
= PR_FALSE
; /* False Start phase is complete */
11384 ss
->ssl3
.hs
.ws
= idle_handshake
;
11386 ssl_FinishHandshake(ss
);
11391 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
11392 * hanshake message.
11393 * Caller must hold Handshake and RecvBuf locks.
11396 ssl3_HandleHandshakeMessage(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
11398 SECStatus rv
= SECSuccess
;
11399 SSL3HandshakeType type
= ss
->ssl3
.hs
.msg_type
;
11400 SSL3Hashes hashes
; /* computed hashes are put here. */
11402 PRUint8 dtlsData
[8];
11404 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
11405 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
11407 * We have to compute the hashes before we update them with the
11410 ssl_GetSpecReadLock(ss
); /************************************/
11411 if((type
== finished
) || (type
== certificate_verify
)) {
11412 SSL3Sender sender
= (SSL3Sender
)0;
11413 ssl3CipherSpec
*rSpec
= ss
->ssl3
.prSpec
;
11415 if (type
== finished
) {
11416 sender
= ss
->sec
.isServer
? sender_client
: sender_server
;
11417 rSpec
= ss
->ssl3
.crSpec
;
11419 rv
= ssl3_ComputeHandshakeHashes(ss
, rSpec
, &hashes
, sender
);
11421 ssl_ReleaseSpecReadLock(ss
); /************************************/
11422 if (rv
!= SECSuccess
) {
11423 return rv
; /* error code was set by ssl3_ComputeHandshakeHashes*/
11425 SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
11426 ss
->fd
, ssl3_DecodeHandshakeType(ss
->ssl3
.hs
.msg_type
)));
11428 hdr
[0] = (PRUint8
)ss
->ssl3
.hs
.msg_type
;
11429 hdr
[1] = (PRUint8
)(length
>> 16);
11430 hdr
[2] = (PRUint8
)(length
>> 8);
11431 hdr
[3] = (PRUint8
)(length
);
11433 /* Start new handshake hashes when we start a new handshake */
11434 if (ss
->ssl3
.hs
.msg_type
== client_hello
) {
11435 rv
= ssl3_RestartHandshakeHashes(ss
);
11436 if (rv
!= SECSuccess
) {
11440 /* We should not include hello_request and hello_verify_request messages
11441 * in the handshake hashes */
11442 if ((ss
->ssl3
.hs
.msg_type
!= hello_request
) &&
11443 (ss
->ssl3
.hs
.msg_type
!= hello_verify_request
)) {
11444 rv
= ssl3_UpdateHandshakeHashes(ss
, (unsigned char*) hdr
, 4);
11445 if (rv
!= SECSuccess
) return rv
; /* err code already set. */
11447 /* Extra data to simulate a complete DTLS handshake fragment */
11449 /* Sequence number */
11450 dtlsData
[0] = MSB(ss
->ssl3
.hs
.recvMessageSeq
);
11451 dtlsData
[1] = LSB(ss
->ssl3
.hs
.recvMessageSeq
);
11453 /* Fragment offset */
11458 /* Fragment length */
11459 dtlsData
[5] = (PRUint8
)(length
>> 16);
11460 dtlsData
[6] = (PRUint8
)(length
>> 8);
11461 dtlsData
[7] = (PRUint8
)(length
);
11463 rv
= ssl3_UpdateHandshakeHashes(ss
, (unsigned char*) dtlsData
,
11465 if (rv
!= SECSuccess
) return rv
; /* err code already set. */
11468 /* The message body */
11469 rv
= ssl3_UpdateHandshakeHashes(ss
, b
, length
);
11470 if (rv
!= SECSuccess
) return rv
; /* err code already set. */
11473 PORT_SetError(0); /* each message starts with no error. */
11475 if (ss
->ssl3
.hs
.ws
== wait_certificate_status
&&
11476 ss
->ssl3
.hs
.msg_type
!= certificate_status
) {
11477 /* If we negotiated the certificate_status extension then we deferred
11478 * certificate validation until we get the CertificateStatus messsage.
11479 * But the CertificateStatus message is optional. If the server did
11480 * not send it then we need to validate the certificate now. If the
11481 * server does send the CertificateStatus message then we will
11482 * authenticate the certificate in ssl3_HandleCertificateStatus.
11484 rv
= ssl3_AuthCertificate(ss
); /* sets ss->ssl3.hs.ws */
11485 PORT_Assert(rv
!= SECWouldBlock
);
11486 if (rv
!= SECSuccess
) {
11491 switch (ss
->ssl3
.hs
.msg_type
) {
11492 case hello_request
:
11494 (void)ssl3_DecodeError(ss
);
11495 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST
);
11498 if (ss
->sec
.isServer
) {
11499 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
11500 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST
);
11503 rv
= ssl3_HandleHelloRequest(ss
);
11506 if (!ss
->sec
.isServer
) {
11507 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
11508 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO
);
11511 rv
= ssl3_HandleClientHello(ss
, b
, length
);
11514 if (ss
->sec
.isServer
) {
11515 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
11516 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO
);
11519 rv
= ssl3_HandleServerHello(ss
, b
, length
);
11521 case hello_verify_request
:
11522 if (!IS_DTLS(ss
) || ss
->sec
.isServer
) {
11523 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
11524 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST
);
11527 rv
= dtls_HandleHelloVerifyRequest(ss
, b
, length
);
11530 rv
= ssl3_HandleCertificate(ss
, b
, length
);
11532 case certificate_status
:
11533 rv
= ssl3_HandleCertificateStatus(ss
, b
, length
);
11535 case server_key_exchange
:
11536 if (ss
->sec
.isServer
) {
11537 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
11538 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH
);
11541 rv
= ssl3_HandleServerKeyExchange(ss
, b
, length
);
11543 case certificate_request
:
11544 if (ss
->sec
.isServer
) {
11545 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
11546 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST
);
11549 rv
= ssl3_HandleCertificateRequest(ss
, b
, length
);
11551 case server_hello_done
:
11553 (void)ssl3_DecodeError(ss
);
11554 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE
);
11557 if (ss
->sec
.isServer
) {
11558 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
11559 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE
);
11562 rv
= ssl3_HandleServerHelloDone(ss
);
11564 case certificate_verify
:
11565 if (!ss
->sec
.isServer
) {
11566 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
11567 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY
);
11570 rv
= ssl3_HandleCertificateVerify(ss
, b
, length
, &hashes
);
11572 case client_key_exchange
:
11573 if (!ss
->sec
.isServer
) {
11574 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
11575 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH
);
11578 rv
= ssl3_HandleClientKeyExchange(ss
, b
, length
);
11580 case new_session_ticket
:
11581 if (ss
->sec
.isServer
) {
11582 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
11583 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET
);
11586 rv
= ssl3_HandleNewSessionTicket(ss
, b
, length
);
11589 rv
= ssl3_HandleFinished(ss
, b
, length
, &hashes
);
11592 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
11593 PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE
);
11597 if (IS_DTLS(ss
) && (rv
!= SECFailure
)) {
11598 /* Increment the expected sequence number */
11599 ss
->ssl3
.hs
.recvMessageSeq
++;
11605 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
11606 * origBuf is the decrypted ssl record content.
11607 * Caller must hold the handshake and RecvBuf locks.
11610 ssl3_HandleHandshake(sslSocket
*ss
, sslBuffer
*origBuf
)
11613 * There may be a partial handshake message already in the handshake
11614 * state. The incoming buffer may contain another portion, or a
11615 * complete message or several messages followed by another portion.
11617 * Each message is made contiguous before being passed to the actual
11620 sslBuffer
*buf
= &ss
->ssl3
.hs
.msgState
; /* do not lose the original buffer pointer */
11623 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
11624 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
11626 if (buf
->buf
== NULL
) {
11629 while (buf
->len
> 0) {
11630 if (ss
->ssl3
.hs
.header_bytes
< 4) {
11634 if (ss
->ssl3
.hs
.header_bytes
++ == 0)
11635 ss
->ssl3
.hs
.msg_type
= (SSL3HandshakeType
)t
;
11637 ss
->ssl3
.hs
.msg_len
= (ss
->ssl3
.hs
.msg_len
<< 8) + t
;
11638 if (ss
->ssl3
.hs
.header_bytes
< 4)
11641 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
11642 if (ss
->ssl3
.hs
.msg_len
> MAX_HANDSHAKE_MSG_LEN
) {
11643 (void)ssl3_DecodeError(ss
);
11644 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG
);
11647 #undef MAX_HANDSHAKE_MSG_LEN
11649 /* If msg_len is zero, be sure we fall through,
11650 ** even if buf->len is zero.
11652 if (ss
->ssl3
.hs
.msg_len
> 0)
11657 * Header has been gathered and there is at least one byte of new
11658 * data available for this message. If it can be done right out
11659 * of the original buffer, then use it from there.
11661 if (ss
->ssl3
.hs
.msg_body
.len
== 0 && buf
->len
>= ss
->ssl3
.hs
.msg_len
) {
11662 /* handle it from input buffer */
11663 rv
= ssl3_HandleHandshakeMessage(ss
, buf
->buf
, ss
->ssl3
.hs
.msg_len
);
11664 if (rv
== SECFailure
) {
11665 /* This test wants to fall through on either
11666 * SECSuccess or SECWouldBlock.
11667 * ssl3_HandleHandshakeMessage MUST set the error code.
11671 buf
->buf
+= ss
->ssl3
.hs
.msg_len
;
11672 buf
->len
-= ss
->ssl3
.hs
.msg_len
;
11673 ss
->ssl3
.hs
.msg_len
= 0;
11674 ss
->ssl3
.hs
.header_bytes
= 0;
11675 if (rv
!= SECSuccess
) { /* return if SECWouldBlock. */
11679 /* must be copied to msg_body and dealt with from there */
11680 unsigned int bytes
;
11682 PORT_Assert(ss
->ssl3
.hs
.msg_body
.len
< ss
->ssl3
.hs
.msg_len
);
11683 bytes
= PR_MIN(buf
->len
, ss
->ssl3
.hs
.msg_len
- ss
->ssl3
.hs
.msg_body
.len
);
11685 /* Grow the buffer if needed */
11686 rv
= sslBuffer_Grow(&ss
->ssl3
.hs
.msg_body
, ss
->ssl3
.hs
.msg_len
);
11687 if (rv
!= SECSuccess
) {
11688 /* sslBuffer_Grow has set a memory error code. */
11692 PORT_Memcpy(ss
->ssl3
.hs
.msg_body
.buf
+ ss
->ssl3
.hs
.msg_body
.len
,
11694 ss
->ssl3
.hs
.msg_body
.len
+= bytes
;
11698 PORT_Assert(ss
->ssl3
.hs
.msg_body
.len
<= ss
->ssl3
.hs
.msg_len
);
11700 /* if we have a whole message, do it */
11701 if (ss
->ssl3
.hs
.msg_body
.len
== ss
->ssl3
.hs
.msg_len
) {
11702 rv
= ssl3_HandleHandshakeMessage(
11703 ss
, ss
->ssl3
.hs
.msg_body
.buf
, ss
->ssl3
.hs
.msg_len
);
11704 if (rv
== SECFailure
) {
11705 /* This test wants to fall through on either
11706 * SECSuccess or SECWouldBlock.
11707 * ssl3_HandleHandshakeMessage MUST set error code.
11711 ss
->ssl3
.hs
.msg_body
.len
= 0;
11712 ss
->ssl3
.hs
.msg_len
= 0;
11713 ss
->ssl3
.hs
.header_bytes
= 0;
11714 if (rv
!= SECSuccess
) { /* return if SECWouldBlock. */
11718 PORT_Assert(buf
->len
== 0);
11724 origBuf
->len
= 0; /* So ssl3_GatherAppDataRecord will keep looping. */
11725 buf
->buf
= NULL
; /* not a leak. */
11729 /* These macros return the given value with the MSB copied to all the other
11730 * bits. They use the fact that arithmetic shift shifts-in the sign bit.
11731 * However, this is not ensured by the C standard so you may need to replace
11732 * them with something else for odd compilers. */
11733 #define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) )
11734 #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x)))
11736 /* SECStatusToMask returns, in constant time, a mask value of all ones if
11737 * rv == SECSuccess. Otherwise it returns zero. */
11738 static unsigned int
11739 SECStatusToMask(SECStatus rv
)
11742 /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results
11743 * in the MSB being set to one iff it was zero before. */
11744 good
= rv
^ SECSuccess
;
11746 return DUPLICATE_MSB_TO_ALL(good
);
11749 /* ssl_ConstantTimeGE returns 0xff if a>=b and 0x00 otherwise. */
11750 static unsigned char
11751 ssl_ConstantTimeGE(unsigned int a
, unsigned int b
)
11754 return DUPLICATE_MSB_TO_ALL(~a
);
11757 /* ssl_ConstantTimeEQ8 returns 0xff if a==b and 0x00 otherwise. */
11758 static unsigned char
11759 ssl_ConstantTimeEQ8(unsigned char a
, unsigned char b
)
11761 unsigned int c
= a
^ b
;
11763 return DUPLICATE_MSB_TO_ALL_8(c
);
11767 ssl_RemoveSSLv3CBCPadding(sslBuffer
*plaintext
,
11768 unsigned int blockSize
,
11769 unsigned int macSize
)
11771 unsigned int paddingLength
, good
, t
;
11772 const unsigned int overhead
= 1 /* padding length byte */ + macSize
;
11774 /* These lengths are all public so we can test them in non-constant
11776 if (overhead
> plaintext
->len
) {
11780 paddingLength
= plaintext
->buf
[plaintext
->len
-1];
11781 /* SSLv3 padding bytes are random and cannot be checked. */
11782 t
= plaintext
->len
;
11783 t
-= paddingLength
+overhead
;
11784 /* If len >= paddingLength+overhead then the MSB of t is zero. */
11785 good
= DUPLICATE_MSB_TO_ALL(~t
);
11786 /* SSLv3 requires that the padding is minimal. */
11787 t
= blockSize
- (paddingLength
+1);
11788 good
&= DUPLICATE_MSB_TO_ALL(~t
);
11789 plaintext
->len
-= good
& (paddingLength
+1);
11790 return (good
& SECSuccess
) | (~good
& SECFailure
);
11794 ssl_RemoveTLSCBCPadding(sslBuffer
*plaintext
, unsigned int macSize
)
11796 unsigned int paddingLength
, good
, t
, toCheck
, i
;
11797 const unsigned int overhead
= 1 /* padding length byte */ + macSize
;
11799 /* These lengths are all public so we can test them in non-constant
11801 if (overhead
> plaintext
->len
) {
11805 paddingLength
= plaintext
->buf
[plaintext
->len
-1];
11806 t
= plaintext
->len
;
11807 t
-= paddingLength
+overhead
;
11808 /* If len >= paddingLength+overhead then the MSB of t is zero. */
11809 good
= DUPLICATE_MSB_TO_ALL(~t
);
11811 /* The padding consists of a length byte at the end of the record and then
11812 * that many bytes of padding, all with the same value as the length byte.
11813 * Thus, with the length byte included, there are paddingLength+1 bytes of
11816 * We can't check just |paddingLength+1| bytes because that leaks
11817 * decrypted information. Therefore we always have to check the maximum
11818 * amount of padding possible. (Again, the length of the record is
11819 * public information so we can use it.) */
11820 toCheck
= 255; /* maximum amount of padding. */
11821 if (toCheck
> plaintext
->len
-1) {
11822 toCheck
= plaintext
->len
-1;
11825 for (i
= 0; i
< toCheck
; i
++) {
11826 unsigned int t
= paddingLength
- i
;
11827 /* If i <= paddingLength then the MSB of t is zero and mask is
11828 * 0xff. Otherwise, mask is 0. */
11829 unsigned char mask
= DUPLICATE_MSB_TO_ALL(~t
);
11830 unsigned char b
= plaintext
->buf
[plaintext
->len
-1-i
];
11831 /* The final |paddingLength+1| bytes should all have the value
11832 * |paddingLength|. Therefore the XOR should be zero. */
11833 good
&= ~(mask
&(paddingLength
^ b
));
11836 /* If any of the final |paddingLength+1| bytes had the wrong value,
11837 * one or more of the lower eight bits of |good| will be cleared. We
11838 * AND the bottom 8 bits together and duplicate the result to all the
11843 good
<<= sizeof(good
)*8-1;
11844 good
= DUPLICATE_MSB_TO_ALL(good
);
11846 plaintext
->len
-= good
& (paddingLength
+1);
11847 return (good
& SECSuccess
) | (~good
& SECFailure
);
11851 * originalLength >= macSize
11852 * macSize <= MAX_MAC_LENGTH
11853 * plaintext->len >= macSize
11856 ssl_CBCExtractMAC(sslBuffer
*plaintext
,
11857 unsigned int originalLength
,
11859 unsigned int macSize
)
11861 unsigned char rotatedMac
[MAX_MAC_LENGTH
];
11862 /* macEnd is the index of |plaintext->buf| just after the end of the
11864 unsigned macEnd
= plaintext
->len
;
11865 unsigned macStart
= macEnd
- macSize
;
11866 /* scanStart contains the number of bytes that we can ignore because
11867 * the MAC's position can only vary by 255 bytes. */
11868 unsigned scanStart
= 0;
11869 unsigned i
, j
, divSpoiler
;
11870 unsigned char rotateOffset
;
11872 if (originalLength
> macSize
+ 255 + 1)
11873 scanStart
= originalLength
- (macSize
+ 255 + 1);
11875 /* divSpoiler contains a multiple of macSize that is used to cause the
11876 * modulo operation to be constant time. Without this, the time varies
11877 * based on the amount of padding when running on Intel chips at least.
11879 * The aim of right-shifting macSize is so that the compiler doesn't
11880 * figure out that it can remove divSpoiler as that would require it
11881 * to prove that macSize is always even, which I hope is beyond it. */
11882 divSpoiler
= macSize
>> 1;
11883 divSpoiler
<<= (sizeof(divSpoiler
)-1)*8;
11884 rotateOffset
= (divSpoiler
+ macStart
- scanStart
) % macSize
;
11886 memset(rotatedMac
, 0, macSize
);
11887 for (i
= scanStart
; i
< originalLength
;) {
11888 for (j
= 0; j
< macSize
&& i
< originalLength
; i
++, j
++) {
11889 unsigned char macStarted
= ssl_ConstantTimeGE(i
, macStart
);
11890 unsigned char macEnded
= ssl_ConstantTimeGE(i
, macEnd
);
11891 unsigned char b
= 0;
11892 b
= plaintext
->buf
[i
];
11893 rotatedMac
[j
] |= b
& macStarted
& ~macEnded
;
11897 /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
11898 * we could line-align |rotatedMac| and rotate in place. */
11899 memset(out
, 0, macSize
);
11900 for (i
= 0; i
< macSize
; i
++) {
11901 unsigned char offset
=
11902 (divSpoiler
+ macSize
- rotateOffset
+ i
) % macSize
;
11903 for (j
= 0; j
< macSize
; j
++) {
11904 out
[j
] |= rotatedMac
[i
] & ssl_ConstantTimeEQ8(j
, offset
);
11909 /* if cText is non-null, then decipher, check MAC, and decompress the
11910 * SSL record from cText->buf (typically gs->inbuf)
11911 * into databuf (typically gs->buf), and any previous contents of databuf
11912 * is lost. Then handle databuf according to its SSL record type,
11913 * unless it's an application record.
11915 * If cText is NULL, then the ciphertext has previously been deciphered and
11916 * checked, and is already sitting in databuf. It is processed as an SSL
11917 * Handshake message.
11919 * DOES NOT process the decrypted/decompressed application data.
11920 * On return, databuf contains the decrypted/decompressed record.
11922 * Called from ssl3_GatherCompleteHandshake
11923 * ssl3_RestartHandshakeAfterCertReq
11925 * Caller must hold the RecvBufLock.
11927 * This function aquires and releases the SSL3Handshake Lock, holding the
11928 * lock around any calls to functions that handle records other than
11929 * Application Data records.
11932 ssl3_HandleRecord(sslSocket
*ss
, SSL3Ciphertext
*cText
, sslBuffer
*databuf
)
11934 const ssl3BulkCipherDef
*cipher_def
;
11935 ssl3CipherSpec
* crSpec
;
11937 unsigned int hashBytes
= MAX_MAC_LENGTH
+ 1;
11939 SSL3ContentType rType
;
11940 SSL3Opaque hash
[MAX_MAC_LENGTH
];
11941 SSL3Opaque givenHashBuf
[MAX_MAC_LENGTH
];
11942 SSL3Opaque
*givenHash
;
11943 sslBuffer
*plaintext
;
11944 sslBuffer temp_buf
;
11945 PRUint64 dtls_seq_num
;
11946 unsigned int ivLen
= 0;
11947 unsigned int originalLen
= 0;
11949 unsigned int minLength
;
11950 unsigned char header
[13];
11951 unsigned int headerLen
;
11953 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
11955 if (!ss
->ssl3
.initialized
) {
11956 ssl_GetSSL3HandshakeLock(ss
);
11957 rv
= ssl3_InitState(ss
);
11958 ssl_ReleaseSSL3HandshakeLock(ss
);
11959 if (rv
!= SECSuccess
) {
11960 return rv
; /* ssl3_InitState has set the error code. */
11964 /* check for Token Presence */
11965 if (!ssl3_ClientAuthTokenPresent(ss
->sec
.ci
.sid
)) {
11966 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL
);
11970 /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX().
11971 * This implies that databuf holds a previously deciphered SSL Handshake
11974 if (cText
== NULL
) {
11975 SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake",
11976 SSL_GETPID(), ss
->fd
));
11977 rType
= content_handshake
;
11981 ssl_GetSpecReadLock(ss
); /******************************************/
11983 crSpec
= ss
->ssl3
.crSpec
;
11984 cipher_def
= crSpec
->cipher_def
;
11987 * DTLS relevance checks:
11988 * Note that this code currently ignores all out-of-epoch packets,
11989 * which means we lose some in the case of rehandshake +
11990 * loss/reordering. Since DTLS is explicitly unreliable, this
11991 * seems like a good tradeoff for implementation effort and is
11992 * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1
11995 DTLSEpoch epoch
= (cText
->seq_num
.high
>> 16) & 0xffff;
11997 if (crSpec
->epoch
!= epoch
) {
11998 ssl_ReleaseSpecReadLock(ss
);
11999 SSL_DBG(("%d: SSL3[%d]: HandleRecord, received packet "
12000 "from irrelevant epoch %d", SSL_GETPID(), ss
->fd
, epoch
));
12001 /* Silently drop the packet */
12002 databuf
->len
= 0; /* Needed to ensure data not left around */
12006 dtls_seq_num
= (((PRUint64
)(cText
->seq_num
.high
& 0xffff)) << 32) |
12007 ((PRUint64
)cText
->seq_num
.low
);
12009 if (dtls_RecordGetRecvd(&crSpec
->recvdRecords
, dtls_seq_num
) != 0) {
12010 ssl_ReleaseSpecReadLock(ss
);
12011 SSL_DBG(("%d: SSL3[%d]: HandleRecord, rejecting "
12012 "potentially replayed packet", SSL_GETPID(), ss
->fd
));
12013 /* Silently drop the packet */
12014 databuf
->len
= 0; /* Needed to ensure data not left around */
12020 minLength
= crSpec
->mac_size
;
12021 if (cipher_def
->type
== type_block
) {
12022 /* CBC records have a padding length byte at the end. */
12024 if (crSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_1
) {
12025 /* With >= TLS 1.1, CBC records have an explicit IV. */
12026 minLength
+= cipher_def
->iv_size
;
12028 } else if (cipher_def
->type
== type_aead
) {
12029 minLength
= cipher_def
->explicit_nonce_size
+ cipher_def
->tag_size
;
12032 /* We can perform this test in variable time because the record's total
12033 * length and the ciphersuite are both public knowledge. */
12034 if (cText
->buf
->len
< minLength
) {
12035 goto decrypt_loser
;
12038 if (cipher_def
->type
== type_block
&&
12039 crSpec
->version
>= SSL_LIBRARY_VERSION_TLS_1_1
) {
12040 /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
12041 * "The receiver decrypts the entire GenericBlockCipher structure and
12042 * then discards the first cipher block corresponding to the IV
12043 * component." Instead, we decrypt the first cipher block and then
12044 * discard it before decrypting the rest.
12046 SSL3Opaque iv
[MAX_IV_LENGTH
];
12049 ivLen
= cipher_def
->iv_size
;
12050 if (ivLen
< 8 || ivLen
> sizeof(iv
)) {
12051 ssl_ReleaseSpecReadLock(ss
);
12052 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
12056 PRINT_BUF(80, (ss
, "IV (ciphertext):", cText
->buf
->buf
, ivLen
));
12058 /* The decryption result is garbage, but since we just throw away
12059 * the block it doesn't matter. The decryption of the next block
12060 * depends only on the ciphertext of the IV block.
12062 rv
= crSpec
->decode(crSpec
->decodeContext
, iv
, &decoded
,
12063 sizeof(iv
), cText
->buf
->buf
, ivLen
);
12065 good
&= SECStatusToMask(rv
);
12068 /* If we will be decompressing the buffer we need to decrypt somewhere
12069 * other than into databuf */
12070 if (crSpec
->decompressor
) {
12071 temp_buf
.buf
= NULL
;
12072 temp_buf
.space
= 0;
12073 plaintext
= &temp_buf
;
12075 plaintext
= databuf
;
12078 plaintext
->len
= 0; /* filled in by decode call below. */
12079 if (plaintext
->space
< MAX_FRAGMENT_LENGTH
) {
12080 rv
= sslBuffer_Grow(plaintext
, MAX_FRAGMENT_LENGTH
+ 2048);
12081 if (rv
!= SECSuccess
) {
12082 ssl_ReleaseSpecReadLock(ss
);
12083 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
12084 SSL_GETPID(), ss
->fd
, MAX_FRAGMENT_LENGTH
+ 2048));
12085 /* sslBuffer_Grow has set a memory error code. */
12086 /* Perhaps we should send an alert. (but we have no memory!) */
12091 PRINT_BUF(80, (ss
, "ciphertext:", cText
->buf
->buf
+ ivLen
,
12092 cText
->buf
->len
- ivLen
));
12094 isTLS
= (PRBool
)(crSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
12096 if (isTLS
&& cText
->buf
->len
- ivLen
> (MAX_FRAGMENT_LENGTH
+ 2048)) {
12097 ssl_ReleaseSpecReadLock(ss
);
12098 SSL3_SendAlert(ss
, alert_fatal
, record_overflow
);
12099 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG
);
12103 rType
= cText
->type
;
12104 if (cipher_def
->type
== type_aead
) {
12105 /* XXX For many AEAD ciphers, the plaintext is shorter than the
12106 * ciphertext by a fixed byte count, but it is not true in general.
12107 * Each AEAD cipher should provide a function that returns the
12108 * plaintext length for a given ciphertext. */
12109 unsigned int decryptedLen
=
12110 cText
->buf
->len
- cipher_def
->explicit_nonce_size
-
12111 cipher_def
->tag_size
;
12112 headerLen
= ssl3_BuildRecordPseudoHeader(
12113 header
, IS_DTLS(ss
) ? cText
->seq_num
: crSpec
->read_seq_num
,
12114 rType
, isTLS
, cText
->version
, IS_DTLS(ss
), decryptedLen
);
12115 PORT_Assert(headerLen
<= sizeof(header
));
12117 ss
->sec
.isServer
? &crSpec
->client
: &crSpec
->server
,
12118 PR_TRUE
, /* do decrypt */
12119 plaintext
->buf
, /* out */
12120 (int*) &plaintext
->len
, /* outlen */
12121 plaintext
->space
, /* maxout */
12122 cText
->buf
->buf
, /* in */
12123 cText
->buf
->len
, /* inlen */
12124 header
, headerLen
);
12125 if (rv
!= SECSuccess
) {
12129 if (cipher_def
->type
== type_block
&&
12130 ((cText
->buf
->len
- ivLen
) % cipher_def
->block_size
) != 0) {
12131 goto decrypt_loser
;
12134 /* decrypt from cText buf to plaintext. */
12135 rv
= crSpec
->decode(
12136 crSpec
->decodeContext
, plaintext
->buf
, (int *)&plaintext
->len
,
12137 plaintext
->space
, cText
->buf
->buf
+ ivLen
, cText
->buf
->len
- ivLen
);
12138 if (rv
!= SECSuccess
) {
12139 goto decrypt_loser
;
12142 PRINT_BUF(80, (ss
, "cleartext:", plaintext
->buf
, plaintext
->len
));
12144 originalLen
= plaintext
->len
;
12146 /* If it's a block cipher, check and strip the padding. */
12147 if (cipher_def
->type
== type_block
) {
12148 const unsigned int blockSize
= cipher_def
->block_size
;
12149 const unsigned int macSize
= crSpec
->mac_size
;
12152 good
&= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
12153 plaintext
, blockSize
, macSize
));
12155 good
&= SECStatusToMask(ssl_RemoveTLSCBCPadding(
12156 plaintext
, macSize
));
12160 /* compute the MAC */
12161 headerLen
= ssl3_BuildRecordPseudoHeader(
12162 header
, IS_DTLS(ss
) ? cText
->seq_num
: crSpec
->read_seq_num
,
12163 rType
, isTLS
, cText
->version
, IS_DTLS(ss
),
12164 plaintext
->len
- crSpec
->mac_size
);
12165 PORT_Assert(headerLen
<= sizeof(header
));
12166 if (cipher_def
->type
== type_block
) {
12167 rv
= ssl3_ComputeRecordMACConstantTime(
12168 crSpec
, (PRBool
)(!ss
->sec
.isServer
), header
, headerLen
,
12169 plaintext
->buf
, plaintext
->len
, originalLen
,
12172 ssl_CBCExtractMAC(plaintext
, originalLen
, givenHashBuf
,
12174 givenHash
= givenHashBuf
;
12176 /* plaintext->len will always have enough space to remove the MAC
12177 * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
12178 * plaintext->len if the result has enough space for the MAC and we
12179 * tested the unadjusted size against minLength, above. */
12180 plaintext
->len
-= crSpec
->mac_size
;
12182 /* This is safe because we checked the minLength above. */
12183 plaintext
->len
-= crSpec
->mac_size
;
12185 rv
= ssl3_ComputeRecordMAC(
12186 crSpec
, (PRBool
)(!ss
->sec
.isServer
), header
, headerLen
,
12187 plaintext
->buf
, plaintext
->len
, hash
, &hashBytes
);
12189 /* We can read the MAC directly from the record because its location
12190 * is public when a stream cipher is used. */
12191 givenHash
= plaintext
->buf
+ plaintext
->len
;
12194 good
&= SECStatusToMask(rv
);
12196 if (hashBytes
!= (unsigned)crSpec
->mac_size
||
12197 NSS_SecureMemcmp(givenHash
, hash
, crSpec
->mac_size
) != 0) {
12198 /* We're allowed to leak whether or not the MAC check was correct */
12205 /* must not hold spec lock when calling SSL3_SendAlert. */
12206 ssl_ReleaseSpecReadLock(ss
);
12208 SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss
->fd
));
12210 if (!IS_DTLS(ss
)) {
12211 SSL3_SendAlert(ss
, alert_fatal
, bad_record_mac
);
12212 /* always log mac error, in case attacker can read server logs. */
12213 PORT_SetError(SSL_ERROR_BAD_MAC_READ
);
12216 /* Silently drop the packet */
12217 databuf
->len
= 0; /* Needed to ensure data not left around */
12222 if (!IS_DTLS(ss
)) {
12223 ssl3_BumpSequenceNumber(&crSpec
->read_seq_num
);
12225 dtls_RecordSetRecvd(&crSpec
->recvdRecords
, dtls_seq_num
);
12228 ssl_ReleaseSpecReadLock(ss
); /*****************************************/
12231 * The decrypted data is now in plaintext.
12234 /* possibly decompress the record. If we aren't using compression then
12235 * plaintext == databuf and so the uncompressed data is already in
12237 if (crSpec
->decompressor
) {
12238 if (databuf
->space
< plaintext
->len
+ SSL3_COMPRESSION_MAX_EXPANSION
) {
12239 rv
= sslBuffer_Grow(
12240 databuf
, plaintext
->len
+ SSL3_COMPRESSION_MAX_EXPANSION
);
12241 if (rv
!= SECSuccess
) {
12242 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
12243 SSL_GETPID(), ss
->fd
,
12244 plaintext
->len
+ SSL3_COMPRESSION_MAX_EXPANSION
));
12245 /* sslBuffer_Grow has set a memory error code. */
12246 /* Perhaps we should send an alert. (but we have no memory!) */
12247 PORT_Free(plaintext
->buf
);
12252 rv
= crSpec
->decompressor(crSpec
->decompressContext
,
12254 (int*) &databuf
->len
,
12259 if (rv
!= SECSuccess
) {
12260 int err
= ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE
);
12261 SSL3_SendAlert(ss
, alert_fatal
,
12262 isTLS
? decompression_failure
: bad_record_mac
);
12264 /* There appears to be a bug with (at least) Apache + OpenSSL where
12265 * resumed SSLv3 connections don't actually use compression. See
12266 * comments 93-95 of
12267 * https://bugzilla.mozilla.org/show_bug.cgi?id=275744
12269 * So, if we get a decompression error, and the record appears to
12270 * be already uncompressed, then we return a more specific error
12271 * code to hopefully save somebody some debugging time in the
12274 if (plaintext
->len
>= 4) {
12275 unsigned int len
= ((unsigned int) plaintext
->buf
[1] << 16) |
12276 ((unsigned int) plaintext
->buf
[2] << 8) |
12277 (unsigned int) plaintext
->buf
[3];
12278 if (len
== plaintext
->len
- 4) {
12279 /* This appears to be uncompressed already */
12280 err
= SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD
;
12284 PORT_Free(plaintext
->buf
);
12285 PORT_SetError(err
);
12289 PORT_Free(plaintext
->buf
);
12293 ** Having completed the decompression, check the length again.
12295 if (isTLS
&& databuf
->len
> (MAX_FRAGMENT_LENGTH
+ 1024)) {
12296 SSL3_SendAlert(ss
, alert_fatal
, record_overflow
);
12297 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG
);
12301 /* Application data records are processed by the caller of this
12302 ** function, not by this function.
12304 if (rType
== content_application_data
) {
12305 if (ss
->firstHsDone
)
12307 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
12308 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA
);
12312 /* It's a record that must be handled by ssl itself, not the application.
12315 /* XXX Get the xmit lock here. Odds are very high that we'll be xmiting
12316 * data ang getting the xmit lock here prevents deadlocks.
12318 ssl_GetSSL3HandshakeLock(ss
);
12320 /* All the functions called in this switch MUST set error code if
12321 ** they return SECFailure or SECWouldBlock.
12324 case content_change_cipher_spec
:
12325 rv
= ssl3_HandleChangeCipherSpecs(ss
, databuf
);
12327 case content_alert
:
12328 rv
= ssl3_HandleAlert(ss
, databuf
);
12330 case content_handshake
:
12331 if (!IS_DTLS(ss
)) {
12332 rv
= ssl3_HandleHandshake(ss
, databuf
);
12334 rv
= dtls_HandleHandshake(ss
, databuf
);
12338 case content_application_data is handled before this switch
12341 SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
12342 SSL_GETPID(), ss
->fd
, cText
->type
));
12343 /* XXX Send an alert ??? */
12344 PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE
);
12349 ssl_ReleaseSSL3HandshakeLock(ss
);
12354 * Initialization functions
12357 /* Called from ssl3_InitState, immediately below. */
12358 /* Caller must hold the SpecWriteLock. */
12360 ssl3_InitCipherSpec(sslSocket
*ss
, ssl3CipherSpec
*spec
)
12362 spec
->cipher_def
= &bulk_cipher_defs
[cipher_null
];
12363 PORT_Assert(spec
->cipher_def
->cipher
== cipher_null
);
12364 spec
->mac_def
= &mac_defs
[mac_null
];
12365 PORT_Assert(spec
->mac_def
->mac
== mac_null
);
12366 spec
->encode
= Null_Cipher
;
12367 spec
->decode
= Null_Cipher
;
12368 spec
->destroy
= NULL
;
12369 spec
->compressor
= NULL
;
12370 spec
->decompressor
= NULL
;
12371 spec
->destroyCompressContext
= NULL
;
12372 spec
->destroyDecompressContext
= NULL
;
12373 spec
->mac_size
= 0;
12374 spec
->master_secret
= NULL
;
12375 spec
->bypassCiphers
= PR_FALSE
;
12377 spec
->msItem
.data
= NULL
;
12378 spec
->msItem
.len
= 0;
12380 spec
->client
.write_key
= NULL
;
12381 spec
->client
.write_mac_key
= NULL
;
12382 spec
->client
.write_mac_context
= NULL
;
12384 spec
->server
.write_key
= NULL
;
12385 spec
->server
.write_mac_key
= NULL
;
12386 spec
->server
.write_mac_context
= NULL
;
12388 spec
->write_seq_num
.high
= 0;
12389 spec
->write_seq_num
.low
= 0;
12391 spec
->read_seq_num
.high
= 0;
12392 spec
->read_seq_num
.low
= 0;
12395 dtls_InitRecvdRecords(&spec
->recvdRecords
);
12397 spec
->version
= ss
->vrange
.max
;
12400 /* Called from: ssl3_SendRecord
12401 ** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake()
12402 ** ssl3_SendClientHello()
12403 ** ssl3_HandleV2ClientHello()
12404 ** ssl3_HandleRecord()
12406 ** This function should perhaps acquire and release the SpecWriteLock.
12411 ssl3_InitState(sslSocket
*ss
)
12413 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
12415 if (ss
->ssl3
.initialized
)
12416 return SECSuccess
; /* Function should be idempotent */
12418 ss
->ssl3
.policy
= SSL_ALLOWED
;
12420 ssl_GetSpecWriteLock(ss
);
12421 ss
->ssl3
.crSpec
= ss
->ssl3
.cwSpec
= &ss
->ssl3
.specs
[0];
12422 ss
->ssl3
.prSpec
= ss
->ssl3
.pwSpec
= &ss
->ssl3
.specs
[1];
12423 ss
->ssl3
.hs
.sendingSCSV
= PR_FALSE
;
12424 ssl3_InitCipherSpec(ss
, ss
->ssl3
.crSpec
);
12425 ssl3_InitCipherSpec(ss
, ss
->ssl3
.prSpec
);
12427 ss
->ssl3
.hs
.ws
= (ss
->sec
.isServer
) ? wait_client_hello
: wait_server_hello
;
12428 #ifndef NSS_DISABLE_ECC
12429 ss
->ssl3
.hs
.negotiatedECCurves
= ssl3_GetSupportedECCurveMask(ss
);
12431 ssl_ReleaseSpecWriteLock(ss
);
12433 PORT_Memset(&ss
->xtnData
, 0, sizeof(TLSExtensionData
));
12436 ss
->ssl3
.hs
.sendMessageSeq
= 0;
12437 ss
->ssl3
.hs
.recvMessageSeq
= 0;
12438 ss
->ssl3
.hs
.rtTimeoutMs
= INITIAL_DTLS_TIMEOUT_MS
;
12439 ss
->ssl3
.hs
.rtRetries
= 0;
12440 ss
->ssl3
.hs
.recvdHighWater
= -1;
12441 PR_INIT_CLIST(&ss
->ssl3
.hs
.lastMessageFlight
);
12442 dtls_SetMTU(ss
, 0); /* Set the MTU to the highest plateau */
12445 PORT_Assert(!ss
->ssl3
.hs
.messages
.buf
&& !ss
->ssl3
.hs
.messages
.space
);
12446 ss
->ssl3
.hs
.messages
.buf
= NULL
;
12447 ss
->ssl3
.hs
.messages
.space
= 0;
12449 ss
->ssl3
.hs
.receivedNewSessionTicket
= PR_FALSE
;
12450 PORT_Memset(&ss
->ssl3
.hs
.newSessionTicket
, 0,
12451 sizeof(ss
->ssl3
.hs
.newSessionTicket
));
12453 ss
->ssl3
.initialized
= PR_TRUE
;
12457 /* Returns a reference counted object that contains a key pair.
12458 * Or NULL on failure. Initial ref count is 1.
12459 * Uses the keys in the pair as input.
12462 ssl3_NewKeyPair( SECKEYPrivateKey
* privKey
, SECKEYPublicKey
* pubKey
)
12464 ssl3KeyPair
* pair
;
12466 if (!privKey
|| !pubKey
) {
12467 PORT_SetError(PR_INVALID_ARGUMENT_ERROR
);
12470 pair
= PORT_ZNew(ssl3KeyPair
);
12472 return NULL
; /* error code is set. */
12473 pair
->refCount
= 1;
12474 pair
->privKey
= privKey
;
12475 pair
->pubKey
= pubKey
;
12476 return pair
; /* success */
12480 ssl3_GetKeyPairRef(ssl3KeyPair
* keyPair
)
12482 PR_ATOMIC_INCREMENT(&keyPair
->refCount
);
12487 ssl3_FreeKeyPair(ssl3KeyPair
* keyPair
)
12489 PRInt32 newCount
= PR_ATOMIC_DECREMENT(&keyPair
->refCount
);
12491 if (keyPair
->privKey
)
12492 SECKEY_DestroyPrivateKey(keyPair
->privKey
);
12493 if (keyPair
->pubKey
)
12494 SECKEY_DestroyPublicKey( keyPair
->pubKey
);
12495 PORT_Free(keyPair
);
12502 * Creates the public and private RSA keys for SSL Step down.
12503 * Called from SSL_ConfigSecureServer in sslsecur.c
12506 ssl3_CreateRSAStepDownKeys(sslSocket
*ss
)
12508 SECStatus rv
= SECSuccess
;
12509 SECKEYPrivateKey
* privKey
; /* RSA step down key */
12510 SECKEYPublicKey
* pubKey
; /* RSA step down key */
12512 if (ss
->stepDownKeyPair
)
12513 ssl3_FreeKeyPair(ss
->stepDownKeyPair
);
12514 ss
->stepDownKeyPair
= NULL
;
12515 #ifndef HACKED_EXPORT_SERVER
12516 /* Sigh, should have a get key strength call for private keys */
12517 if (PK11_GetPrivateModulusLen(ss
->serverCerts
[kt_rsa
].SERVERKEY
) >
12518 EXPORT_RSA_KEY_LENGTH
) {
12519 /* need to ask for the key size in bits */
12520 privKey
= SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH
* BPB
,
12522 if (!privKey
|| !pubKey
||
12523 !(ss
->stepDownKeyPair
= ssl3_NewKeyPair(privKey
, pubKey
))) {
12524 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL
);
12533 /* record the export policy for this cipher suite */
12535 ssl3_SetPolicy(ssl3CipherSuite which
, int policy
)
12537 ssl3CipherSuiteCfg
*suite
;
12539 suite
= ssl_LookupCipherSuiteCfg(which
, cipherSuites
);
12540 if (suite
== NULL
) {
12541 return SECFailure
; /* err code was set by ssl_LookupCipherSuiteCfg */
12543 suite
->policy
= policy
;
12549 ssl3_GetPolicy(ssl3CipherSuite which
, PRInt32
*oPolicy
)
12551 ssl3CipherSuiteCfg
*suite
;
12555 suite
= ssl_LookupCipherSuiteCfg(which
, cipherSuites
);
12557 policy
= suite
->policy
;
12560 policy
= SSL_NOT_ALLOWED
;
12561 rv
= SECFailure
; /* err code was set by Lookup. */
12567 /* record the user preference for this suite */
12569 ssl3_CipherPrefSetDefault(ssl3CipherSuite which
, PRBool enabled
)
12571 ssl3CipherSuiteCfg
*suite
;
12573 suite
= ssl_LookupCipherSuiteCfg(which
, cipherSuites
);
12574 if (suite
== NULL
) {
12575 return SECFailure
; /* err code was set by ssl_LookupCipherSuiteCfg */
12577 suite
->enabled
= enabled
;
12581 /* return the user preference for this suite */
12583 ssl3_CipherPrefGetDefault(ssl3CipherSuite which
, PRBool
*enabled
)
12585 ssl3CipherSuiteCfg
*suite
;
12589 suite
= ssl_LookupCipherSuiteCfg(which
, cipherSuites
);
12591 pref
= suite
->enabled
;
12594 pref
= SSL_NOT_ALLOWED
;
12595 rv
= SECFailure
; /* err code was set by Lookup. */
12602 ssl3_CipherPrefSet(sslSocket
*ss
, ssl3CipherSuite which
, PRBool enabled
)
12604 ssl3CipherSuiteCfg
*suite
;
12606 suite
= ssl_LookupCipherSuiteCfg(which
, ss
->cipherSuites
);
12607 if (suite
== NULL
) {
12608 return SECFailure
; /* err code was set by ssl_LookupCipherSuiteCfg */
12610 suite
->enabled
= enabled
;
12615 ssl3_CipherPrefGet(sslSocket
*ss
, ssl3CipherSuite which
, PRBool
*enabled
)
12617 ssl3CipherSuiteCfg
*suite
;
12621 suite
= ssl_LookupCipherSuiteCfg(which
, ss
->cipherSuites
);
12623 pref
= suite
->enabled
;
12626 pref
= SSL_NOT_ALLOWED
;
12627 rv
= SECFailure
; /* err code was set by Lookup. */
12634 ssl3_CipherOrderSet(sslSocket
*ss
, const ssl3CipherSuite
*ciphers
, unsigned int len
)
12636 /* |i| iterates over |ciphers| while |done| and |j| iterate over
12637 * |ss->cipherSuites|. */
12638 unsigned int i
, done
;
12640 for (i
= done
= 0; i
< len
; i
++) {
12641 PRUint16 id
= ciphers
[i
];
12642 unsigned int existingIndex
, j
;
12643 PRBool found
= PR_FALSE
;
12645 for (j
= done
; j
< ssl_V3_SUITES_IMPLEMENTED
; j
++) {
12646 if (ss
->cipherSuites
[j
].cipher_suite
== id
) {
12657 if (existingIndex
!= done
) {
12658 const ssl3CipherSuiteCfg temp
= ss
->cipherSuites
[done
];
12659 ss
->cipherSuites
[done
] = ss
->cipherSuites
[existingIndex
];
12660 ss
->cipherSuites
[existingIndex
] = temp
;
12665 /* Disable all cipher suites that weren't included. */
12666 for (; done
< ssl_V3_SUITES_IMPLEMENTED
; done
++) {
12667 ss
->cipherSuites
[done
].enabled
= 0;
12673 /* copy global default policy into socket. */
12675 ssl3_InitSocketPolicy(sslSocket
*ss
)
12677 PORT_Memcpy(ss
->cipherSuites
, cipherSuites
, sizeof cipherSuites
);
12681 ssl3_GetTLSUniqueChannelBinding(sslSocket
*ss
,
12682 unsigned char *out
,
12683 unsigned int *outLen
,
12684 unsigned int outLenMax
) {
12688 SECStatus rv
= SECFailure
;
12692 ssl_GetSSL3HandshakeLock(ss
);
12694 ssl_GetSpecReadLock(ss
);
12695 isTLS
= (PRBool
)(ss
->ssl3
.cwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
12696 ssl_ReleaseSpecReadLock(ss
);
12698 /* The tls-unique channel binding is the first Finished structure in the
12699 * handshake. In the case of a resumption, that's the server's Finished.
12700 * Otherwise, it's the client's Finished. */
12701 len
= ss
->ssl3
.hs
.finishedBytes
;
12703 /* Sending or receiving a Finished message will set finishedBytes to a
12704 * non-zero value. */
12706 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED
);
12710 /* If we are in the middle of a renegotiation then the channel binding
12711 * value is poorly defined and depends on the direction that it will be
12712 * used on. Therefore we simply return an error in this case. */
12713 if (ss
->firstHsDone
&& ss
->ssl3
.hs
.ws
!= idle_handshake
) {
12714 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
);
12718 /* If resuming, then we want the second Finished value in the array, which
12719 * is the server's */
12720 if (ss
->ssl3
.hs
.isResuming
)
12724 if (outLenMax
< len
) {
12725 PORT_SetError(SEC_ERROR_OUTPUT_LEN
);
12730 memcpy(out
, &ss
->ssl3
.hs
.finishedMsgs
.tFinished
[index
], len
);
12732 memcpy(out
, &ss
->ssl3
.hs
.finishedMsgs
.sFinished
[index
], len
);
12738 ssl_ReleaseSSL3HandshakeLock(ss
);
12742 /* ssl3_config_match_init must have already been called by
12743 * the caller of this function.
12746 ssl3_ConstructV2CipherSpecsHack(sslSocket
*ss
, unsigned char *cs
, int *size
)
12750 PORT_Assert(ss
!= 0);
12752 PORT_SetError(PR_INVALID_ARGUMENT_ERROR
);
12755 if (SSL3_ALL_VERSIONS_DISABLED(&ss
->vrange
)) {
12760 *size
= count_cipher_suites(ss
, SSL_ALLOWED
, PR_TRUE
);
12764 /* ssl3_config_match_init was called by the caller of this function. */
12765 for (i
= 0; i
< ssl_V3_SUITES_IMPLEMENTED
; i
++) {
12766 ssl3CipherSuiteCfg
*suite
= &ss
->cipherSuites
[i
];
12767 if (config_match(suite
, SSL_ALLOWED
, PR_TRUE
, &ss
->vrange
)) {
12770 *cs
++ = (suite
->cipher_suite
>> 8) & 0xFF;
12771 *cs
++ = suite
->cipher_suite
& 0xFF;
12781 ** If ssl3 socket has completed the first handshake, and is in idle state,
12782 ** then start a new handshake.
12783 ** If flushCache is true, the SID cache will be flushed first, forcing a
12784 ** "Full" handshake (not a session restart handshake), to be done.
12786 ** called from SSL_RedoHandshake(), which already holds the handshake locks.
12789 ssl3_RedoHandshake(sslSocket
*ss
, PRBool flushCache
)
12791 sslSessionID
* sid
= ss
->sec
.ci
.sid
;
12794 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
12796 if (!ss
->firstHsDone
||
12797 ((ss
->version
>= SSL_LIBRARY_VERSION_3_0
) &&
12798 ss
->ssl3
.initialized
&&
12799 (ss
->ssl3
.hs
.ws
!= idle_handshake
))) {
12800 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED
);
12805 dtls_RehandshakeCleanup(ss
);
12808 if (ss
->opt
.enableRenegotiation
== SSL_RENEGOTIATE_NEVER
) {
12809 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
);
12812 if (sid
&& flushCache
) {
12813 if (ss
->sec
.uncache
)
12814 ss
->sec
.uncache(sid
); /* remove it from whichever cache it's in. */
12815 ssl_FreeSID(sid
); /* dec ref count and free if zero. */
12816 ss
->sec
.ci
.sid
= NULL
;
12819 ssl_GetXmitBufLock(ss
); /**************************************/
12821 /* start off a new handshake. */
12822 rv
= (ss
->sec
.isServer
) ? ssl3_SendHelloRequest(ss
)
12823 : ssl3_SendClientHello(ss
, PR_FALSE
);
12825 ssl_ReleaseXmitBufLock(ss
); /**************************************/
12829 /* Called from ssl_DestroySocketContents() in sslsock.c */
12831 ssl3_DestroySSL3Info(sslSocket
*ss
)
12834 if (ss
->ssl3
.clientCertificate
!= NULL
)
12835 CERT_DestroyCertificate(ss
->ssl3
.clientCertificate
);
12837 if (ss
->ssl3
.clientPrivateKey
!= NULL
)
12838 SECKEY_DestroyPrivateKey(ss
->ssl3
.clientPrivateKey
);
12839 #ifdef NSS_PLATFORM_CLIENT_AUTH
12840 if (ss
->ssl3
.platformClientKey
)
12841 ssl_FreePlatformKey(ss
->ssl3
.platformClientKey
);
12842 #endif /* NSS_PLATFORM_CLIENT_AUTH */
12844 if (ss
->ssl3
.channelID
)
12845 SECKEY_DestroyPrivateKey(ss
->ssl3
.channelID
);
12846 if (ss
->ssl3
.channelIDPub
)
12847 SECKEY_DestroyPublicKey(ss
->ssl3
.channelIDPub
);
12849 if (ss
->ssl3
.peerCertArena
!= NULL
)
12850 ssl3_CleanupPeerCerts(ss
);
12852 if (ss
->ssl3
.clientCertChain
!= NULL
) {
12853 CERT_DestroyCertificateList(ss
->ssl3
.clientCertChain
);
12854 ss
->ssl3
.clientCertChain
= NULL
;
12857 /* clean up handshake */
12858 #ifndef NO_PKCS11_BYPASS
12859 if (ss
->opt
.bypassPKCS11
) {
12860 if (ss
->ssl3
.hs
.hashType
== handshake_hash_combo
) {
12861 SHA1_DestroyContext((SHA1Context
*)ss
->ssl3
.hs
.sha_cx
, PR_FALSE
);
12862 MD5_DestroyContext((MD5Context
*)ss
->ssl3
.hs
.md5_cx
, PR_FALSE
);
12863 } else if (ss
->ssl3
.hs
.hashType
== handshake_hash_single
) {
12864 ss
->ssl3
.hs
.sha_obj
->destroy(ss
->ssl3
.hs
.sha_cx
, PR_FALSE
);
12868 if (ss
->ssl3
.hs
.md5
) {
12869 PK11_DestroyContext(ss
->ssl3
.hs
.md5
,PR_TRUE
);
12871 if (ss
->ssl3
.hs
.sha
) {
12872 PK11_DestroyContext(ss
->ssl3
.hs
.sha
,PR_TRUE
);
12874 if (ss
->ssl3
.hs
.clientSigAndHash
) {
12875 PORT_Free(ss
->ssl3
.hs
.clientSigAndHash
);
12877 if (ss
->ssl3
.hs
.messages
.buf
) {
12878 PORT_Free(ss
->ssl3
.hs
.messages
.buf
);
12879 ss
->ssl3
.hs
.messages
.buf
= NULL
;
12880 ss
->ssl3
.hs
.messages
.len
= 0;
12881 ss
->ssl3
.hs
.messages
.space
= 0;
12884 /* free the SSL3Buffer (msg_body) */
12885 PORT_Free(ss
->ssl3
.hs
.msg_body
.buf
);
12887 SECITEM_FreeItem(&ss
->ssl3
.hs
.newSessionTicket
.ticket
, PR_FALSE
);
12889 /* free up the CipherSpecs */
12890 ssl3_DestroyCipherSpec(&ss
->ssl3
.specs
[0], PR_TRUE
/*freeSrvName*/);
12891 ssl3_DestroyCipherSpec(&ss
->ssl3
.specs
[1], PR_TRUE
/*freeSrvName*/);
12893 /* Destroy the DTLS data */
12895 dtls_FreeHandshakeMessages(&ss
->ssl3
.hs
.lastMessageFlight
);
12896 if (ss
->ssl3
.hs
.recvdFragments
.buf
) {
12897 PORT_Free(ss
->ssl3
.hs
.recvdFragments
.buf
);
12901 ss
->ssl3
.initialized
= PR_FALSE
;
12903 SECITEM_FreeItem(&ss
->ssl3
.nextProto
, PR_FALSE
);
12906 /* End of ssl3con.c */