OLD | NEW |
| (Empty) |
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ | |
2 /* | |
3 * SSL3 Protocol | |
4 * | |
5 * This Source Code Form is subject to the terms of the Mozilla Public | |
6 * License, v. 2.0. If a copy of the MPL was not distributed with this | |
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | |
8 | |
9 /* TODO(ekr): Implement HelloVerifyRequest on server side. OK for now. */ | |
10 | |
11 #include "cert.h" | |
12 #include "ssl.h" | |
13 #include "cryptohi.h" /* for DSAU_ stuff */ | |
14 #include "keyhi.h" | |
15 #include "secder.h" | |
16 #include "secitem.h" | |
17 #include "sechash.h" | |
18 | |
19 #include "sslimpl.h" | |
20 #include "sslproto.h" | |
21 #include "sslerr.h" | |
22 #include "prtime.h" | |
23 #include "prinrval.h" | |
24 #include "prerror.h" | |
25 #include "pratom.h" | |
26 #include "prthread.h" | |
27 | |
28 #include "pk11func.h" | |
29 #include "secmod.h" | |
30 #ifndef NO_PKCS11_BYPASS | |
31 #include "blapi.h" | |
32 #endif | |
33 | |
34 /* This is a bodge to allow this code to be compiled against older NSS headers | |
35 * that don't contain the TLS 1.2 changes. */ | |
36 #ifndef CKM_NSS_TLS_PRF_GENERAL_SHA256 | |
37 #define CKM_NSS_TLS_PRF_GENERAL_SHA256 (CKM_NSS + 21) | |
38 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256 (CKM_NSS + 22) | |
39 #define CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256 (CKM_NSS + 23) | |
40 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24) | |
41 #endif | |
42 | |
43 /* This is a bodge to allow this code to be compiled against older NSS | |
44 * headers. */ | |
45 #ifndef CKM_NSS_CHACHA20_POLY1305 | |
46 #define CKM_NSS_CHACHA20_POLY1305 (CKM_NSS + 26) | |
47 | |
48 typedef struct CK_NSS_AEAD_PARAMS { | |
49 CK_BYTE_PTR pIv; /* This is the nonce. */ | |
50 CK_ULONG ulIvLen; | |
51 CK_BYTE_PTR pAAD; | |
52 CK_ULONG ulAADLen; | |
53 CK_ULONG ulTagLen; | |
54 } CK_NSS_AEAD_PARAMS; | |
55 | |
56 #endif | |
57 | |
58 #include <stdio.h> | |
59 #ifdef NSS_ENABLE_ZLIB | |
60 #include "zlib.h" | |
61 #endif | |
62 #ifdef LINUX | |
63 #include <dlfcn.h> | |
64 #endif | |
65 | |
66 #ifndef PK11_SETATTRS | |
67 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \ | |
68 (x)->pValue=(v); (x)->ulValueLen = (l); | |
69 #endif | |
70 | |
71 static SECStatus ssl3_AuthCertificate(sslSocket *ss); | |
72 static void ssl3_CleanupPeerCerts(sslSocket *ss); | |
73 static void ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid); | |
74 static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, | |
75 PK11SlotInfo * serverKeySlot); | |
76 static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms); | |
77 static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss); | |
78 static SECStatus ssl3_HandshakeFailure( sslSocket *ss); | |
79 static SECStatus ssl3_InitState( sslSocket *ss); | |
80 static SECStatus ssl3_SendCertificate( sslSocket *ss); | |
81 static SECStatus ssl3_SendCertificateStatus( sslSocket *ss); | |
82 static SECStatus ssl3_SendEmptyCertificate( sslSocket *ss); | |
83 static SECStatus ssl3_SendCertificateRequest(sslSocket *ss); | |
84 static SECStatus ssl3_SendNextProto( sslSocket *ss); | |
85 static SECStatus ssl3_SendEncryptedExtensions(sslSocket *ss); | |
86 static SECStatus ssl3_SendFinished( sslSocket *ss, PRInt32 flags); | |
87 static SECStatus ssl3_SendServerHello( sslSocket *ss); | |
88 static SECStatus ssl3_SendServerHelloDone( sslSocket *ss); | |
89 static SECStatus ssl3_SendServerKeyExchange( sslSocket *ss); | |
90 static SECStatus ssl3_UpdateHandshakeHashes( sslSocket *ss, | |
91 const unsigned char *b, | |
92 unsigned int l); | |
93 static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags); | |
94 static int ssl3_OIDToTLSHashAlgorithm(SECOidTag oid); | |
95 | |
96 static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen, | |
97 int maxOutputLen, const unsigned char *input, | |
98 int inputLen); | |
99 #ifndef NO_PKCS11_BYPASS | |
100 static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt, | |
101 unsigned char *out, int *outlen, int maxout, | |
102 const unsigned char *in, int inlen, | |
103 const unsigned char *additionalData, | |
104 int additionalDataLen); | |
105 #endif | |
106 | |
107 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */ | |
108 #define MIN_SEND_BUF_LENGTH 4000 | |
109 | |
110 /* This list of SSL3 cipher suites is sorted in descending order of | |
111 * precedence (desirability). It only includes cipher suites we implement. | |
112 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites | |
113 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c) | |
114 * | |
115 * Important: See bug 946147 before enabling, reordering, or adding any cipher | |
116 * suites to this list. | |
117 */ | |
118 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { | |
119 /* cipher_suite policy enabled isPresent */ | |
120 | |
121 #ifdef NSS_ENABLE_ECC | |
122 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
123 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
124 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
125 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
126 /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around | |
127 * bug 946147. | |
128 */ | |
129 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
130 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
131 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
132 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
133 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
134 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
135 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
136 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
137 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
138 { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
139 #endif /* NSS_ENABLE_ECC */ | |
140 | |
141 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
142 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
143 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
144 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
145 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
146 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
147 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
148 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
149 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
150 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
151 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
152 { SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
153 { SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
154 { TLS_DHE_DSS_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
155 | |
156 #ifdef NSS_ENABLE_ECC | |
157 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
158 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
159 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
160 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
161 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
162 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
163 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
164 { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
165 #endif /* NSS_ENABLE_ECC */ | |
166 | |
167 /* RSA */ | |
168 { TLS_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
169 { TLS_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
170 { TLS_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
171 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
172 { TLS_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
173 { TLS_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
174 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
175 { TLS_RSA_WITH_SEED_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
176 { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
177 { SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
178 { SSL_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
179 { SSL_RSA_WITH_RC4_128_MD5, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
180 | |
181 /* 56-bit DES "domestic" cipher suites */ | |
182 { SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
183 { SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
184 { SSL_RSA_FIPS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
185 { SSL_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
186 | |
187 /* export ciphersuites with 1024-bit public key exchange keys */ | |
188 { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
189 { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
190 | |
191 /* export ciphersuites with 512-bit public key exchange keys */ | |
192 { SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
193 { SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
194 | |
195 /* ciphersuites with no encryption */ | |
196 #ifdef NSS_ENABLE_ECC | |
197 { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
198 { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
199 { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
200 { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
201 #endif /* NSS_ENABLE_ECC */ | |
202 { SSL_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
203 { TLS_RSA_WITH_NULL_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
204 { SSL_RSA_WITH_NULL_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
205 }; | |
206 | |
207 /* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order. | |
208 */ | |
209 #ifdef DEBUG | |
210 void ssl3_CheckCipherSuiteOrderConsistency() | |
211 { | |
212 unsigned int i; | |
213 | |
214 /* Note that SSL_ImplementedCiphers has more elements than cipherSuites | |
215 * because it SSL_ImplementedCiphers includes SSL 2.0 cipher suites. | |
216 */ | |
217 PORT_Assert(SSL_NumImplementedCiphers >= PR_ARRAY_SIZE(cipherSuites)); | |
218 | |
219 for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) { | |
220 PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite); | |
221 } | |
222 } | |
223 #endif | |
224 | |
225 /* This list of SSL3 compression methods is sorted in descending order of | |
226 * precedence (desirability). It only includes compression methods we | |
227 * implement. | |
228 */ | |
229 static const /*SSLCompressionMethod*/ PRUint8 compressions [] = { | |
230 #ifdef NSS_ENABLE_ZLIB | |
231 ssl_compression_deflate, | |
232 #endif | |
233 ssl_compression_null | |
234 }; | |
235 | |
236 static const int compressionMethodsCount = | |
237 sizeof(compressions) / sizeof(compressions[0]); | |
238 | |
239 /* compressionEnabled returns true iff the compression algorithm is enabled | |
240 * for the given SSL socket. */ | |
241 static PRBool | |
242 compressionEnabled(sslSocket *ss, SSLCompressionMethod compression) | |
243 { | |
244 switch (compression) { | |
245 case ssl_compression_null: | |
246 return PR_TRUE; /* Always enabled */ | |
247 #ifdef NSS_ENABLE_ZLIB | |
248 case ssl_compression_deflate: | |
249 return ss->opt.enableDeflate; | |
250 #endif | |
251 default: | |
252 return PR_FALSE; | |
253 } | |
254 } | |
255 | |
256 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = { | |
257 ct_RSA_sign, | |
258 #ifdef NSS_ENABLE_ECC | |
259 ct_ECDSA_sign, | |
260 #endif /* NSS_ENABLE_ECC */ | |
261 ct_DSS_sign, | |
262 }; | |
263 | |
264 /* This block is the contents of the supported_signature_algorithms field of | |
265 * our TLS 1.2 CertificateRequest message, in wire format. See | |
266 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 | |
267 * | |
268 * This block contains only sha256 entries because we only support TLS 1.2 | |
269 * CertificateVerify messages that use the handshake hash. */ | |
270 static const PRUint8 supported_signature_algorithms[] = { | |
271 tls_hash_sha256, tls_sig_rsa, | |
272 #ifdef NSS_ENABLE_ECC | |
273 tls_hash_sha256, tls_sig_ecdsa, | |
274 #endif | |
275 tls_hash_sha256, tls_sig_dsa, | |
276 }; | |
277 | |
278 #define EXPORT_RSA_KEY_LENGTH 64 /* bytes */ | |
279 | |
280 | |
281 /* This global item is used only in servers. It is is initialized by | |
282 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest(). | |
283 */ | |
284 CERTDistNames *ssl3_server_ca_list = NULL; | |
285 static SSL3Statistics ssl3stats; | |
286 | |
287 /* indexed by SSL3BulkCipher */ | |
288 static const ssl3BulkCipherDef bulk_cipher_defs[] = { | |
289 /* |--------- Lengths --------| */ | |
290 /* cipher calg k s type i b t n */ | |
291 /* e e v l a o */ | |
292 /* y c | o g n */ | |
293 /* | r | c | c */ | |
294 /* | e | k | e */ | |
295 /* | t | | | | */ | |
296 {cipher_null, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, | |
297 {cipher_rc4, calg_rc4, 16,16, type_stream, 0, 0, 0, 0}, | |
298 {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, 0, 0}, | |
299 {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, 0, 0}, | |
300 {cipher_rc2, calg_rc2, 16,16, type_block, 8, 8, 0, 0}, | |
301 {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, 0, 0}, | |
302 {cipher_des, calg_des, 8, 8, type_block, 8, 8, 0, 0}, | |
303 {cipher_3des, calg_3des, 24,24, type_block, 8, 8, 0, 0}, | |
304 {cipher_des40, calg_des, 8, 5, type_block, 8, 8, 0, 0}, | |
305 {cipher_idea, calg_idea, 16,16, type_block, 8, 8, 0, 0}, | |
306 {cipher_aes_128, calg_aes, 16,16, type_block, 16,16, 0, 0}, | |
307 {cipher_aes_256, calg_aes, 32,32, type_block, 16,16, 0, 0}, | |
308 {cipher_camellia_128, calg_camellia, 16,16, type_block, 16,16, 0, 0}, | |
309 {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0}, | |
310 {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0}, | |
311 {cipher_aes_128_gcm, calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8}, | |
312 {cipher_chacha20, calg_chacha20, 32,32, type_aead, 0, 0,16, 0}, | |
313 {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, | |
314 }; | |
315 | |
316 static const ssl3KEADef kea_defs[] = | |
317 { /* indexed by SSL3KeyExchangeAlgorithm */ | |
318 /* kea exchKeyType signKeyType is_limited limit tls_keygen */ | |
319 {kea_null, kt_null, sign_null, PR_FALSE, 0, PR_FALSE}, | |
320 {kea_rsa, kt_rsa, sign_rsa, PR_FALSE, 0, PR_FALSE}, | |
321 {kea_rsa_export, kt_rsa, sign_rsa, PR_TRUE, 512, PR_FALSE}, | |
322 {kea_rsa_export_1024,kt_rsa, sign_rsa, PR_TRUE, 1024, PR_FALSE}, | |
323 {kea_dh_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE}, | |
324 {kea_dh_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE}, | |
325 {kea_dh_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE}, | |
326 {kea_dh_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE}, | |
327 {kea_dhe_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE}, | |
328 {kea_dhe_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE}, | |
329 {kea_dhe_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE}, | |
330 {kea_dhe_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE}, | |
331 {kea_dh_anon, kt_dh, sign_null, PR_FALSE, 0, PR_FALSE}, | |
332 {kea_dh_anon_export, kt_dh, sign_null, PR_TRUE, 512, PR_FALSE}, | |
333 {kea_rsa_fips, kt_rsa, sign_rsa, PR_FALSE, 0, PR_TRUE }, | |
334 #ifdef NSS_ENABLE_ECC | |
335 {kea_ecdh_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE}, | |
336 {kea_ecdhe_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE}, | |
337 {kea_ecdh_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE}, | |
338 {kea_ecdhe_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE}, | |
339 {kea_ecdh_anon, kt_ecdh, sign_null, PR_FALSE, 0, PR_FALSE}, | |
340 #endif /* NSS_ENABLE_ECC */ | |
341 }; | |
342 | |
343 /* must use ssl_LookupCipherSuiteDef to access */ | |
344 static const ssl3CipherSuiteDef cipher_suite_defs[] = | |
345 { | |
346 /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg */ | |
347 | |
348 {SSL_NULL_WITH_NULL_NULL, cipher_null, mac_null, kea_null}, | |
349 {SSL_RSA_WITH_NULL_MD5, cipher_null, mac_md5, kea_rsa}, | |
350 {SSL_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_rsa}, | |
351 {TLS_RSA_WITH_NULL_SHA256, cipher_null, hmac_sha256, kea_rsa}, | |
352 {SSL_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export}, | |
353 {SSL_RSA_WITH_RC4_128_MD5, cipher_rc4, mac_md5, kea_rsa}, | |
354 {SSL_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_rsa}, | |
355 {SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, | |
356 cipher_rc2_40, mac_md5, kea_rsa_export}, | |
357 #if 0 /* not implemented */ | |
358 {SSL_RSA_WITH_IDEA_CBC_SHA, cipher_idea, mac_sha, kea_rsa}, | |
359 {SSL_RSA_EXPORT_WITH_DES40_CBC_SHA, | |
360 cipher_des40, mac_sha, kea_rsa_export}, | |
361 #endif | |
362 {SSL_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa}, | |
363 {SSL_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa}, | |
364 {SSL_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_dss}, | |
365 {SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, | |
366 cipher_3des, mac_sha, kea_dhe_dss}, | |
367 {TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_dhe_dss}, | |
368 #if 0 /* not implemented */ | |
369 {SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA, | |
370 cipher_des40, mac_sha, kea_dh_dss_export}, | |
371 {SSL_DH_DSS_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_dss}, | |
372 {SSL_DH_DSS_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_dss}, | |
373 {SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA, | |
374 cipher_des40, mac_sha, kea_dh_rsa_export}, | |
375 {SSL_DH_RSA_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_rsa}, | |
376 {SSL_DH_RSA_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_rsa}, | |
377 {SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, | |
378 cipher_des40, mac_sha, kea_dh_dss_export}, | |
379 {SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, | |
380 cipher_des40, mac_sha, kea_dh_rsa_export}, | |
381 #endif | |
382 {SSL_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_rsa}, | |
383 {SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, | |
384 cipher_3des, mac_sha, kea_dhe_rsa}, | |
385 #if 0 | |
386 {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export}, | |
387 {SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA, | |
388 cipher_des40, mac_sha, kea_dh_anon_export}, | |
389 {SSL_DH_ANON_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_anon}, | |
390 {SSL_DH_ANON_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_anon}, | |
391 #endif | |
392 | |
393 | |
394 /* New TLS cipher suites */ | |
395 {TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_rsa}, | |
396 {TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_rsa}, | |
397 {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_dss}, | |
398 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_rsa}, | |
399 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_r
sa}, | |
400 {TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_rsa}, | |
401 {TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_rsa}, | |
402 {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_dss}, | |
403 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_rsa}, | |
404 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_r
sa}, | |
405 #if 0 | |
406 {TLS_DH_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_dss}, | |
407 {TLS_DH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_rsa}, | |
408 {TLS_DH_ANON_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_anon}, | |
409 {TLS_DH_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_dss}, | |
410 {TLS_DH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_rsa}, | |
411 {TLS_DH_ANON_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_anon}, | |
412 #endif | |
413 | |
414 {TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, mac_sha, kea_rsa}, | |
415 | |
416 {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa}, | |
417 {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, | |
418 cipher_camellia_128, mac_sha, kea_dhe_dss}, | |
419 {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, | |
420 cipher_camellia_128, mac_sha, kea_dhe_rsa}, | |
421 {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa}, | |
422 {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, | |
423 cipher_camellia_256, mac_sha, kea_dhe_dss}, | |
424 {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, | |
425 cipher_camellia_256, mac_sha, kea_dhe_rsa}, | |
426 | |
427 {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, | |
428 cipher_des, mac_sha,kea_rsa_export_1024}, | |
429 {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, | |
430 cipher_rc4_56, mac_sha,kea_rsa_export_1024}, | |
431 | |
432 {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips}, | |
433 {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa_fips}, | |
434 | |
435 {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_
rsa}, | |
436 {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_rsa}, | |
437 {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ec
dhe_rsa}, | |
438 {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_
ecdhe_ecdsa}, | |
439 {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, cipher_chacha20, mac_aead, kea_ecdhe_
rsa}, | |
440 {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, cipher_chacha20, mac_aead, kea_ecdh
e_ecdsa}, | |
441 | |
442 #ifdef NSS_ENABLE_ECC | |
443 {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa}, | |
444 {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa}, | |
445 {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa}
, | |
446 {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecds
a}, | |
447 {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecds
a}, | |
448 | |
449 {TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_ecdsa
}, | |
450 {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_ecdsa
}, | |
451 {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecds
a}, | |
452 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ec
dsa}, | |
453 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_e
cdhe_ecdsa}, | |
454 {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ec
dsa}, | |
455 | |
456 {TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_rsa}, | |
457 {TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_rsa}, | |
458 {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_rsa}, | |
459 {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_rsa}, | |
460 {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_rsa}, | |
461 | |
462 {TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_rsa
}, | |
463 {TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_rsa
}, | |
464 {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_rsa
}, | |
465 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_rsa
}, | |
466 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecd
he_rsa}, | |
467 {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_rsa
}, | |
468 | |
469 #if 0 | |
470 {TLS_ECDH_anon_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_anon
}, | |
471 {TLS_ECDH_anon_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_anon
}, | |
472 {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_anon
}, | |
473 {TLS_ECDH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_anon
}, | |
474 {TLS_ECDH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_anon
}, | |
475 #endif | |
476 #endif /* NSS_ENABLE_ECC */ | |
477 }; | |
478 | |
479 static const CK_MECHANISM_TYPE kea_alg_defs[] = { | |
480 0x80000000L, | |
481 CKM_RSA_PKCS, | |
482 CKM_DH_PKCS_DERIVE, | |
483 CKM_KEA_KEY_DERIVE, | |
484 CKM_ECDH1_DERIVE | |
485 }; | |
486 | |
487 typedef struct SSLCipher2MechStr { | |
488 SSLCipherAlgorithm calg; | |
489 CK_MECHANISM_TYPE cmech; | |
490 } SSLCipher2Mech; | |
491 | |
492 /* indexed by type SSLCipherAlgorithm */ | |
493 static const SSLCipher2Mech alg2Mech[] = { | |
494 /* calg, cmech */ | |
495 { calg_null , (CK_MECHANISM_TYPE)0x80000000L }, | |
496 { calg_rc4 , CKM_RC4 }, | |
497 { calg_rc2 , CKM_RC2_CBC }, | |
498 { calg_des , CKM_DES_CBC }, | |
499 { calg_3des , CKM_DES3_CBC }, | |
500 { calg_idea , CKM_IDEA_CBC }, | |
501 { calg_fortezza , CKM_SKIPJACK_CBC64 }, | |
502 { calg_aes , CKM_AES_CBC }, | |
503 { calg_camellia , CKM_CAMELLIA_CBC }, | |
504 { calg_seed , CKM_SEED_CBC }, | |
505 { calg_aes_gcm , CKM_AES_GCM }, | |
506 { calg_chacha20 , CKM_NSS_CHACHA20_POLY1305 }, | |
507 /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */ | |
508 }; | |
509 | |
510 #define mmech_invalid (CK_MECHANISM_TYPE)0x80000000L | |
511 #define mmech_md5 CKM_SSL3_MD5_MAC | |
512 #define mmech_sha CKM_SSL3_SHA1_MAC | |
513 #define mmech_md5_hmac CKM_MD5_HMAC | |
514 #define mmech_sha_hmac CKM_SHA_1_HMAC | |
515 #define mmech_sha256_hmac CKM_SHA256_HMAC | |
516 | |
517 static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */ | |
518 /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */ | |
519 /* mac mmech pad_size mac_size */ | |
520 { mac_null, mmech_invalid, 0, 0 }, | |
521 { mac_md5, mmech_md5, 48, MD5_LENGTH }, | |
522 { mac_sha, mmech_sha, 40, SHA1_LENGTH}, | |
523 {hmac_md5, mmech_md5_hmac, 0, MD5_LENGTH }, | |
524 {hmac_sha, mmech_sha_hmac, 0, SHA1_LENGTH}, | |
525 {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH}, | |
526 { mac_aead, mmech_invalid, 0, 0 }, | |
527 }; | |
528 | |
529 /* indexed by SSL3BulkCipher */ | |
530 const char * const ssl3_cipherName[] = { | |
531 "NULL", | |
532 "RC4", | |
533 "RC4-40", | |
534 "RC4-56", | |
535 "RC2-CBC", | |
536 "RC2-CBC-40", | |
537 "DES-CBC", | |
538 "3DES-EDE-CBC", | |
539 "DES-CBC-40", | |
540 "IDEA-CBC", | |
541 "AES-128", | |
542 "AES-256", | |
543 "Camellia-128", | |
544 "Camellia-256", | |
545 "SEED-CBC", | |
546 "AES-128-GCM", | |
547 "missing" | |
548 }; | |
549 | |
550 #ifdef NSS_ENABLE_ECC | |
551 /* The ECCWrappedKeyInfo structure defines how various pieces of | |
552 * information are laid out within wrappedSymmetricWrappingkey | |
553 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is | |
554 * a 512-byte buffer (see sslimpl.h), the variable length field | |
555 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes. | |
556 * | |
557 * XXX For now, NSS only supports named elliptic curves of size 571 bits | |
558 * or smaller. The public value will fit within 145 bytes and EC params | |
559 * will fit within 12 bytes. We'll need to revisit this when NSS | |
560 * supports arbitrary curves. | |
561 */ | |
562 #define MAX_EC_WRAPPED_KEY_BUFLEN 504 | |
563 | |
564 typedef struct ECCWrappedKeyInfoStr { | |
565 PRUint16 size; /* EC public key size in bits */ | |
566 PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */ | |
567 PRUint16 pubValueLen; /* length (in bytes) of EC public value */ | |
568 PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */ | |
569 PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */ | |
570 /* EC public-key params, the EC public value and the wrapped key */ | |
571 } ECCWrappedKeyInfo; | |
572 #endif /* NSS_ENABLE_ECC */ | |
573 | |
574 #if defined(TRACE) | |
575 | |
576 static char * | |
577 ssl3_DecodeHandshakeType(int msgType) | |
578 { | |
579 char * rv; | |
580 static char line[40]; | |
581 | |
582 switch(msgType) { | |
583 case hello_request: rv = "hello_request (0)"; break; | |
584 case client_hello: rv = "client_hello (1)"; break; | |
585 case server_hello: rv = "server_hello (2)"; break; | |
586 case hello_verify_request: rv = "hello_verify_request (3)"; break; | |
587 case certificate: rv = "certificate (11)"; break; | |
588 case server_key_exchange: rv = "server_key_exchange (12)"; break; | |
589 case certificate_request: rv = "certificate_request (13)"; break; | |
590 case server_hello_done: rv = "server_hello_done (14)"; break; | |
591 case certificate_verify: rv = "certificate_verify (15)"; break; | |
592 case client_key_exchange: rv = "client_key_exchange (16)"; break; | |
593 case finished: rv = "finished (20)"; break; | |
594 default: | |
595 sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType); | |
596 rv = line; | |
597 } | |
598 return rv; | |
599 } | |
600 | |
601 static char * | |
602 ssl3_DecodeContentType(int msgType) | |
603 { | |
604 char * rv; | |
605 static char line[40]; | |
606 | |
607 switch(msgType) { | |
608 case content_change_cipher_spec: | |
609 rv = "change_cipher_spec (20)"; break; | |
610 case content_alert: rv = "alert (21)"; break; | |
611 case content_handshake: rv = "handshake (22)"; break; | |
612 case content_application_data: | |
613 rv = "application_data (23)"; break; | |
614 default: | |
615 sprintf(line, "*UNKNOWN* record type! (%d)", msgType); | |
616 rv = line; | |
617 } | |
618 return rv; | |
619 } | |
620 | |
621 #endif | |
622 | |
623 SSL3Statistics * | |
624 SSL_GetStatistics(void) | |
625 { | |
626 return &ssl3stats; | |
627 } | |
628 | |
629 typedef struct tooLongStr { | |
630 #if defined(IS_LITTLE_ENDIAN) | |
631 PRInt32 low; | |
632 PRInt32 high; | |
633 #else | |
634 PRInt32 high; | |
635 PRInt32 low; | |
636 #endif | |
637 } tooLong; | |
638 | |
639 void SSL_AtomicIncrementLong(long * x) | |
640 { | |
641 if ((sizeof *x) == sizeof(PRInt32)) { | |
642 PR_ATOMIC_INCREMENT((PRInt32 *)x); | |
643 } else { | |
644 tooLong * tl = (tooLong *)x; | |
645 if (PR_ATOMIC_INCREMENT(&tl->low) == 0) | |
646 PR_ATOMIC_INCREMENT(&tl->high); | |
647 } | |
648 } | |
649 | |
650 static PRBool | |
651 ssl3_CipherSuiteAllowedForVersionRange( | |
652 ssl3CipherSuite cipherSuite, | |
653 const SSLVersionRange *vrange) | |
654 { | |
655 switch (cipherSuite) { | |
656 /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or | |
657 * later. This set of cipher suites is similar to, but different from, the | |
658 * set of cipher suites considered exportable by SSL_IsExportCipherSuite. | |
659 */ | |
660 case SSL_RSA_EXPORT_WITH_RC4_40_MD5: | |
661 case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5: | |
662 /* SSL_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented | |
663 * SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented | |
664 * SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented | |
665 * SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented | |
666 * SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented | |
667 * SSL_DH_ANON_EXPORT_WITH_RC4_40_MD5: never implemented | |
668 * SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA: never implemented | |
669 */ | |
670 return vrange->min <= SSL_LIBRARY_VERSION_TLS_1_0; | |
671 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305: | |
672 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: | |
673 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: | |
674 case TLS_RSA_WITH_AES_256_CBC_SHA256: | |
675 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: | |
676 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: | |
677 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: | |
678 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: | |
679 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: | |
680 case TLS_DHE_RSA_WITH_AES_128_GCM_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; | |
685 default: | |
686 return PR_TRUE; | |
687 } | |
688 } | |
689 | |
690 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */ | |
691 /* XXX This does a linear search. A binary search would be better. */ | |
692 static const ssl3CipherSuiteDef * | |
693 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite) | |
694 { | |
695 int cipher_suite_def_len = | |
696 sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]); | |
697 int i; | |
698 | |
699 for (i = 0; i < cipher_suite_def_len; i++) { | |
700 if (cipher_suite_defs[i].cipher_suite == suite) | |
701 return &cipher_suite_defs[i]; | |
702 } | |
703 PORT_Assert(PR_FALSE); /* We should never get here. */ | |
704 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); | |
705 return NULL; | |
706 } | |
707 | |
708 /* Find the cipher configuration struct associate with suite */ | |
709 /* XXX This does a linear search. A binary search would be better. */ | |
710 static ssl3CipherSuiteCfg * | |
711 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites) | |
712 { | |
713 int i; | |
714 | |
715 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { | |
716 if (suites[i].cipher_suite == suite) | |
717 return &suites[i]; | |
718 } | |
719 /* return NULL and let the caller handle it. */ | |
720 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); | |
721 return NULL; | |
722 } | |
723 | |
724 | |
725 /* Initialize the suite->isPresent value for config_match | |
726 * Returns count of enabled ciphers supported by extant tokens, | |
727 * regardless of policy or user preference. | |
728 * If this returns zero, the user cannot do SSL v3. | |
729 */ | |
730 int | |
731 ssl3_config_match_init(sslSocket *ss) | |
732 { | |
733 ssl3CipherSuiteCfg * suite; | |
734 const ssl3CipherSuiteDef *cipher_def; | |
735 SSLCipherAlgorithm cipher_alg; | |
736 CK_MECHANISM_TYPE cipher_mech; | |
737 SSL3KEAType exchKeyType; | |
738 int i; | |
739 int numPresent = 0; | |
740 int numEnabled = 0; | |
741 PRBool isServer; | |
742 sslServerCerts *svrAuth; | |
743 | |
744 PORT_Assert(ss); | |
745 if (!ss) { | |
746 PORT_SetError(SEC_ERROR_INVALID_ARGS); | |
747 return 0; | |
748 } | |
749 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { | |
750 return 0; | |
751 } | |
752 isServer = (PRBool)(ss->sec.isServer != 0); | |
753 | |
754 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { | |
755 suite = &ss->cipherSuites[i]; | |
756 if (suite->enabled) { | |
757 ++numEnabled; | |
758 /* We need the cipher defs to see if we have a token that can handle | |
759 * this cipher. It isn't part of the static definition. | |
760 */ | |
761 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite); | |
762 if (!cipher_def) { | |
763 suite->isPresent = PR_FALSE; | |
764 continue; | |
765 } | |
766 cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg; | |
767 PORT_Assert( alg2Mech[cipher_alg].calg == cipher_alg); | |
768 cipher_mech = alg2Mech[cipher_alg].cmech; | |
769 exchKeyType = | |
770 kea_defs[cipher_def->key_exchange_alg].exchKeyType; | |
771 #ifndef NSS_ENABLE_ECC | |
772 svrAuth = ss->serverCerts + exchKeyType; | |
773 #else | |
774 /* XXX SSLKEAType isn't really a good choice for | |
775 * indexing certificates. It doesn't work for | |
776 * (EC)DHE-* ciphers. Here we use a hack to ensure | |
777 * that the server uses an RSA cert for (EC)DHE-RSA. | |
778 */ | |
779 switch (cipher_def->key_exchange_alg) { | |
780 case kea_ecdhe_rsa: | |
781 #if NSS_SERVER_DHE_IMPLEMENTED | |
782 /* XXX NSS does not yet implement the server side of _DHE_ | |
783 * cipher suites. Correcting the computation for svrAuth, | |
784 * as the case below does, causes NSS SSL servers to begin to | |
785 * negotiate cipher suites they do not implement. So, until | |
786 * server side _DHE_ is implemented, keep this disabled. | |
787 */ | |
788 case kea_dhe_rsa: | |
789 #endif | |
790 svrAuth = ss->serverCerts + kt_rsa; | |
791 break; | |
792 case kea_ecdh_ecdsa: | |
793 case kea_ecdh_rsa: | |
794 /* | |
795 * XXX We ought to have different indices for | |
796 * ECDSA- and RSA-signed EC certificates so | |
797 * we could support both key exchange mechanisms | |
798 * simultaneously. For now, both of them use | |
799 * whatever is in the certificate slot for kt_ecdh | |
800 */ | |
801 default: | |
802 svrAuth = ss->serverCerts + exchKeyType; | |
803 break; | |
804 } | |
805 #endif /* NSS_ENABLE_ECC */ | |
806 | |
807 /* Mark the suites that are backed by real tokens, certs and keys */ | |
808 suite->isPresent = (PRBool) | |
809 (((exchKeyType == kt_null) || | |
810 ((!isServer || (svrAuth->serverKeyPair && | |
811 svrAuth->SERVERKEY && | |
812 svrAuth->serverCertChain)) && | |
813 PK11_TokenExists(kea_alg_defs[exchKeyType]))) && | |
814 ((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech))); | |
815 if (suite->isPresent) | |
816 ++numPresent; | |
817 } | |
818 } | |
819 PORT_Assert(numPresent > 0 || numEnabled == 0); | |
820 if (numPresent <= 0) { | |
821 PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED); | |
822 } | |
823 return numPresent; | |
824 } | |
825 | |
826 | |
827 /* return PR_TRUE if suite matches policy, enabled state and is applicable to | |
828 * the given version range. */ | |
829 /* It would be a REALLY BAD THING (tm) if we ever permitted the use | |
830 ** of a cipher that was NOT_ALLOWED. So, if this is ever called with | |
831 ** policy == SSL_NOT_ALLOWED, report no match. | |
832 */ | |
833 /* adjust suite enabled to the availability of a token that can do the | |
834 * cipher suite. */ | |
835 static PRBool | |
836 config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled, | |
837 const SSLVersionRange *vrange) | |
838 { | |
839 PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE); | |
840 if (policy == SSL_NOT_ALLOWED || !enabled) | |
841 return PR_FALSE; | |
842 return (PRBool)(suite->enabled && | |
843 suite->isPresent && | |
844 suite->policy != SSL_NOT_ALLOWED && | |
845 suite->policy <= policy && | |
846 ssl3_CipherSuiteAllowedForVersionRange( | |
847 suite->cipher_suite, vrange)); | |
848 } | |
849 | |
850 /* return number of cipher suites that match policy, enabled state and are | |
851 * applicable for the configured protocol version range. */ | |
852 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */ | |
853 static int | |
854 count_cipher_suites(sslSocket *ss, int policy, PRBool enabled) | |
855 { | |
856 int i, count = 0; | |
857 | |
858 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { | |
859 return 0; | |
860 } | |
861 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { | |
862 if (config_match(&ss->cipherSuites[i], policy, enabled, &ss->vrange)) | |
863 count++; | |
864 } | |
865 if (count <= 0) { | |
866 PORT_SetError(SSL_ERROR_SSL_DISABLED); | |
867 } | |
868 return count; | |
869 } | |
870 | |
871 /* | |
872 * Null compression, mac and encryption functions | |
873 */ | |
874 | |
875 static SECStatus | |
876 Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen, | |
877 const unsigned char *input, int inputLen) | |
878 { | |
879 if (inputLen > maxOutputLen) { | |
880 *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */ | |
881 PORT_SetError(SEC_ERROR_OUTPUT_LEN); | |
882 return SECFailure; | |
883 } | |
884 *outputLen = inputLen; | |
885 if (input != output) | |
886 PORT_Memcpy(output, input, inputLen); | |
887 return SECSuccess; | |
888 } | |
889 | |
890 /* | |
891 * SSL3 Utility functions | |
892 */ | |
893 | |
894 /* allowLargerPeerVersion controls whether the function will select the | |
895 * highest enabled SSL version or fail when peerVersion is greater than the | |
896 * highest enabled version. | |
897 * | |
898 * If allowLargerPeerVersion is true, peerVersion is the peer's highest | |
899 * enabled version rather than the peer's selected version. | |
900 */ | |
901 SECStatus | |
902 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion, | |
903 PRBool allowLargerPeerVersion) | |
904 { | |
905 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { | |
906 PORT_SetError(SSL_ERROR_SSL_DISABLED); | |
907 return SECFailure; | |
908 } | |
909 | |
910 if (peerVersion < ss->vrange.min || | |
911 (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) { | |
912 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); | |
913 return SECFailure; | |
914 } | |
915 | |
916 ss->version = PR_MIN(peerVersion, ss->vrange.max); | |
917 PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, ss->version)); | |
918 | |
919 return SECSuccess; | |
920 } | |
921 | |
922 static SECStatus | |
923 ssl3_GetNewRandom(SSL3Random *random) | |
924 { | |
925 SECStatus rv; | |
926 | |
927 /* first 4 bytes are reserverd for time */ | |
928 rv = PK11_GenerateRandom(random->rand, SSL3_RANDOM_LENGTH); | |
929 if (rv != SECSuccess) { | |
930 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); | |
931 } | |
932 return rv; | |
933 } | |
934 | |
935 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */ | |
936 SECStatus | |
937 ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf, | |
938 PRBool isTLS) | |
939 { | |
940 SECStatus rv = SECFailure; | |
941 PRBool doDerEncode = PR_FALSE; | |
942 int signatureLen; | |
943 SECItem hashItem; | |
944 | |
945 buf->data = NULL; | |
946 | |
947 switch (key->keyType) { | |
948 case rsaKey: | |
949 hashItem.data = hash->u.raw; | |
950 hashItem.len = hash->len; | |
951 break; | |
952 case dsaKey: | |
953 doDerEncode = isTLS; | |
954 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash. | |
955 * In that case, we use just the SHA1 part. */ | |
956 if (hash->hashAlg == SEC_OID_UNKNOWN) { | |
957 hashItem.data = hash->u.s.sha; | |
958 hashItem.len = sizeof(hash->u.s.sha); | |
959 } else { | |
960 hashItem.data = hash->u.raw; | |
961 hashItem.len = hash->len; | |
962 } | |
963 break; | |
964 #ifdef NSS_ENABLE_ECC | |
965 case ecKey: | |
966 doDerEncode = PR_TRUE; | |
967 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash. | |
968 * In that case, we use just the SHA1 part. */ | |
969 if (hash->hashAlg == SEC_OID_UNKNOWN) { | |
970 hashItem.data = hash->u.s.sha; | |
971 hashItem.len = sizeof(hash->u.s.sha); | |
972 } else { | |
973 hashItem.data = hash->u.raw; | |
974 hashItem.len = hash->len; | |
975 } | |
976 break; | |
977 #endif /* NSS_ENABLE_ECC */ | |
978 default: | |
979 PORT_SetError(SEC_ERROR_INVALID_KEY); | |
980 goto done; | |
981 } | |
982 PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len)); | |
983 | |
984 if (hash->hashAlg == SEC_OID_UNKNOWN) { | |
985 signatureLen = PK11_SignatureLen(key); | |
986 if (signatureLen <= 0) { | |
987 PORT_SetError(SEC_ERROR_INVALID_KEY); | |
988 goto done; | |
989 } | |
990 | |
991 buf->len = (unsigned)signatureLen; | |
992 buf->data = (unsigned char *)PORT_Alloc(signatureLen); | |
993 if (!buf->data) | |
994 goto done; /* error code was set. */ | |
995 | |
996 rv = PK11_Sign(key, buf, &hashItem); | |
997 } else { | |
998 rv = SGN_Digest(key, hash->hashAlg, buf, &hashItem); | |
999 } | |
1000 if (rv != SECSuccess) { | |
1001 ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE); | |
1002 } else if (doDerEncode) { | |
1003 SECItem derSig = {siBuffer, NULL, 0}; | |
1004 | |
1005 /* This also works for an ECDSA signature */ | |
1006 rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len); | |
1007 if (rv == SECSuccess) { | |
1008 PORT_Free(buf->data); /* discard unencoded signature. */ | |
1009 *buf = derSig; /* give caller encoded signature. */ | |
1010 } else if (derSig.data) { | |
1011 PORT_Free(derSig.data); | |
1012 } | |
1013 } | |
1014 | |
1015 PRINT_BUF(60, (NULL, "signed hashes", (unsigned char*)buf->data, buf->len)); | |
1016 done: | |
1017 if (rv != SECSuccess && buf->data) { | |
1018 PORT_Free(buf->data); | |
1019 buf->data = NULL; | |
1020 } | |
1021 return rv; | |
1022 } | |
1023 | |
1024 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */ | |
1025 SECStatus | |
1026 ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert, | |
1027 SECItem *buf, PRBool isTLS, void *pwArg) | |
1028 { | |
1029 SECKEYPublicKey * key; | |
1030 SECItem * signature = NULL; | |
1031 SECStatus rv; | |
1032 SECItem hashItem; | |
1033 SECOidTag encAlg; | |
1034 SECOidTag hashAlg; | |
1035 | |
1036 | |
1037 PRINT_BUF(60, (NULL, "check signed hashes", | |
1038 buf->data, buf->len)); | |
1039 | |
1040 key = CERT_ExtractPublicKey(cert); | |
1041 if (key == NULL) { | |
1042 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); | |
1043 return SECFailure; | |
1044 } | |
1045 | |
1046 hashAlg = hash->hashAlg; | |
1047 switch (key->keyType) { | |
1048 case rsaKey: | |
1049 encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION; | |
1050 hashItem.data = hash->u.raw; | |
1051 hashItem.len = hash->len; | |
1052 break; | |
1053 case dsaKey: | |
1054 encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE; | |
1055 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash. | |
1056 * In that case, we use just the SHA1 part. */ | |
1057 if (hash->hashAlg == SEC_OID_UNKNOWN) { | |
1058 hashItem.data = hash->u.s.sha; | |
1059 hashItem.len = sizeof(hash->u.s.sha); | |
1060 } else { | |
1061 hashItem.data = hash->u.raw; | |
1062 hashItem.len = hash->len; | |
1063 } | |
1064 /* Allow DER encoded DSA signatures in SSL 3.0 */ | |
1065 if (isTLS || buf->len != SECKEY_SignatureLen(key)) { | |
1066 signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key)); | |
1067 if (!signature) { | |
1068 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); | |
1069 return SECFailure; | |
1070 } | |
1071 buf = signature; | |
1072 } | |
1073 break; | |
1074 | |
1075 #ifdef NSS_ENABLE_ECC | |
1076 case ecKey: | |
1077 encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY; | |
1078 /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash. | |
1079 * In that case, we use just the SHA1 part. | |
1080 * ECDSA signatures always encode the integers r and s using ASN.1 | |
1081 * (unlike DSA where ASN.1 encoding is used with TLS but not with | |
1082 * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA. | |
1083 */ | |
1084 if (hash->hashAlg == SEC_OID_UNKNOWN) { | |
1085 hashAlg = SEC_OID_SHA1; | |
1086 hashItem.data = hash->u.s.sha; | |
1087 hashItem.len = sizeof(hash->u.s.sha); | |
1088 } else { | |
1089 hashItem.data = hash->u.raw; | |
1090 hashItem.len = hash->len; | |
1091 } | |
1092 break; | |
1093 #endif /* NSS_ENABLE_ECC */ | |
1094 | |
1095 default: | |
1096 SECKEY_DestroyPublicKey(key); | |
1097 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); | |
1098 return SECFailure; | |
1099 } | |
1100 | |
1101 PRINT_BUF(60, (NULL, "hash(es) to be verified", | |
1102 hashItem.data, hashItem.len)); | |
1103 | |
1104 if (hashAlg == SEC_OID_UNKNOWN || key->keyType == dsaKey) { | |
1105 /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded. | |
1106 * DSA signatures are DER-encoded in TLS but not in SSL3 and the code | |
1107 * above always removes the DER encoding of DSA signatures when | |
1108 * present. Thus DSA signatures are always verified with PK11_Verify. | |
1109 */ | |
1110 rv = PK11_Verify(key, buf, &hashItem, pwArg); | |
1111 } else { | |
1112 rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg, | |
1113 pwArg); | |
1114 } | |
1115 SECKEY_DestroyPublicKey(key); | |
1116 if (signature) { | |
1117 SECITEM_FreeItem(signature, PR_TRUE); | |
1118 } | |
1119 if (rv != SECSuccess) { | |
1120 ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); | |
1121 } | |
1122 return rv; | |
1123 } | |
1124 | |
1125 | |
1126 /* Caller must set hiLevel error code. */ | |
1127 /* Called from ssl3_ComputeExportRSAKeyHash | |
1128 * ssl3_ComputeDHKeyHash | |
1129 * which are called from ssl3_HandleServerKeyExchange. | |
1130 * | |
1131 * hashAlg: either the OID for a hash algorithm or SEC_OID_UNKNOWN to specify | |
1132 * the pre-1.2, MD5/SHA1 combination hash. | |
1133 */ | |
1134 SECStatus | |
1135 ssl3_ComputeCommonKeyHash(SECOidTag hashAlg, | |
1136 PRUint8 * hashBuf, unsigned int bufLen, | |
1137 SSL3Hashes *hashes, PRBool bypassPKCS11) | |
1138 { | |
1139 SECStatus rv = SECSuccess; | |
1140 | |
1141 #ifndef NO_PKCS11_BYPASS | |
1142 if (bypassPKCS11) { | |
1143 if (hashAlg == SEC_OID_UNKNOWN) { | |
1144 MD5_HashBuf (hashes->u.s.md5, hashBuf, bufLen); | |
1145 SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen); | |
1146 hashes->len = MD5_LENGTH + SHA1_LENGTH; | |
1147 } else if (hashAlg == SEC_OID_SHA1) { | |
1148 SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen); | |
1149 hashes->len = SHA1_LENGTH; | |
1150 } else if (hashAlg == SEC_OID_SHA256) { | |
1151 SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen); | |
1152 hashes->len = SHA256_LENGTH; | |
1153 } else if (hashAlg == SEC_OID_SHA384) { | |
1154 SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen); | |
1155 hashes->len = SHA384_LENGTH; | |
1156 } else if (hashAlg == SEC_OID_SHA512) { | |
1157 SHA512_HashBuf(hashes->u.raw, hashBuf, bufLen); | |
1158 hashes->len = SHA512_LENGTH; | |
1159 } else { | |
1160 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); | |
1161 return SECFailure; | |
1162 } | |
1163 } else | |
1164 #endif | |
1165 { | |
1166 if (hashAlg == SEC_OID_UNKNOWN) { | |
1167 rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen); | |
1168 if (rv != SECSuccess) { | |
1169 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
1170 rv = SECFailure; | |
1171 goto done; | |
1172 } | |
1173 | |
1174 rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen); | |
1175 if (rv != SECSuccess) { | |
1176 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
1177 rv = SECFailure; | |
1178 } | |
1179 hashes->len = MD5_LENGTH + SHA1_LENGTH; | |
1180 } else { | |
1181 hashes->len = HASH_ResultLenByOidTag(hashAlg); | |
1182 if (hashes->len > sizeof(hashes->u.raw)) { | |
1183 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); | |
1184 rv = SECFailure; | |
1185 goto done; | |
1186 } | |
1187 rv = PK11_HashBuf(hashAlg, hashes->u.raw, hashBuf, bufLen); | |
1188 if (rv != SECSuccess) { | |
1189 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
1190 rv = SECFailure; | |
1191 } | |
1192 } | |
1193 } | |
1194 hashes->hashAlg = hashAlg; | |
1195 | |
1196 done: | |
1197 return rv; | |
1198 } | |
1199 | |
1200 /* Caller must set hiLevel error code. | |
1201 ** Called from ssl3_SendServerKeyExchange and | |
1202 ** ssl3_HandleServerKeyExchange. | |
1203 */ | |
1204 static SECStatus | |
1205 ssl3_ComputeExportRSAKeyHash(SECOidTag hashAlg, | |
1206 SECItem modulus, SECItem publicExponent, | |
1207 SSL3Random *client_rand, SSL3Random *server_rand, | |
1208 SSL3Hashes *hashes, PRBool bypassPKCS11) | |
1209 { | |
1210 PRUint8 * hashBuf; | |
1211 PRUint8 * pBuf; | |
1212 SECStatus rv = SECSuccess; | |
1213 unsigned int bufLen; | |
1214 PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8]; | |
1215 | |
1216 bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len; | |
1217 if (bufLen <= sizeof buf) { | |
1218 hashBuf = buf; | |
1219 } else { | |
1220 hashBuf = PORT_Alloc(bufLen); | |
1221 if (!hashBuf) { | |
1222 return SECFailure; | |
1223 } | |
1224 } | |
1225 | |
1226 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); | |
1227 pBuf = hashBuf + SSL3_RANDOM_LENGTH; | |
1228 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); | |
1229 pBuf += SSL3_RANDOM_LENGTH; | |
1230 pBuf[0] = (PRUint8)(modulus.len >> 8); | |
1231 pBuf[1] = (PRUint8)(modulus.len); | |
1232 pBuf += 2; | |
1233 memcpy(pBuf, modulus.data, modulus.len); | |
1234 pBuf += modulus.len; | |
1235 pBuf[0] = (PRUint8)(publicExponent.len >> 8); | |
1236 pBuf[1] = (PRUint8)(publicExponent.len); | |
1237 pBuf += 2; | |
1238 memcpy(pBuf, publicExponent.data, publicExponent.len); | |
1239 pBuf += publicExponent.len; | |
1240 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); | |
1241 | |
1242 rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, | |
1243 bypassPKCS11); | |
1244 | |
1245 PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen)); | |
1246 if (hashAlg == SEC_OID_UNKNOWN) { | |
1247 PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result", | |
1248 hashes->u.s.md5, MD5_LENGTH)); | |
1249 PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result", | |
1250 hashes->u.s.sha, SHA1_LENGTH)); | |
1251 } else { | |
1252 PRINT_BUF(95, (NULL, "RSAkey hash: result", | |
1253 hashes->u.raw, hashes->len)); | |
1254 } | |
1255 | |
1256 if (hashBuf != buf && hashBuf != NULL) | |
1257 PORT_Free(hashBuf); | |
1258 return rv; | |
1259 } | |
1260 | |
1261 /* Caller must set hiLevel error code. */ | |
1262 /* Called from ssl3_HandleServerKeyExchange. */ | |
1263 static SECStatus | |
1264 ssl3_ComputeDHKeyHash(SECOidTag hashAlg, | |
1265 SECItem dh_p, SECItem dh_g, SECItem dh_Ys, | |
1266 SSL3Random *client_rand, SSL3Random *server_rand, | |
1267 SSL3Hashes *hashes, PRBool bypassPKCS11) | |
1268 { | |
1269 PRUint8 * hashBuf; | |
1270 PRUint8 * pBuf; | |
1271 SECStatus rv = SECSuccess; | |
1272 unsigned int bufLen; | |
1273 PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8]; | |
1274 | |
1275 bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len; | |
1276 if (bufLen <= sizeof buf) { | |
1277 hashBuf = buf; | |
1278 } else { | |
1279 hashBuf = PORT_Alloc(bufLen); | |
1280 if (!hashBuf) { | |
1281 return SECFailure; | |
1282 } | |
1283 } | |
1284 | |
1285 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); | |
1286 pBuf = hashBuf + SSL3_RANDOM_LENGTH; | |
1287 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); | |
1288 pBuf += SSL3_RANDOM_LENGTH; | |
1289 pBuf[0] = (PRUint8)(dh_p.len >> 8); | |
1290 pBuf[1] = (PRUint8)(dh_p.len); | |
1291 pBuf += 2; | |
1292 memcpy(pBuf, dh_p.data, dh_p.len); | |
1293 pBuf += dh_p.len; | |
1294 pBuf[0] = (PRUint8)(dh_g.len >> 8); | |
1295 pBuf[1] = (PRUint8)(dh_g.len); | |
1296 pBuf += 2; | |
1297 memcpy(pBuf, dh_g.data, dh_g.len); | |
1298 pBuf += dh_g.len; | |
1299 pBuf[0] = (PRUint8)(dh_Ys.len >> 8); | |
1300 pBuf[1] = (PRUint8)(dh_Ys.len); | |
1301 pBuf += 2; | |
1302 memcpy(pBuf, dh_Ys.data, dh_Ys.len); | |
1303 pBuf += dh_Ys.len; | |
1304 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); | |
1305 | |
1306 rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, | |
1307 bypassPKCS11); | |
1308 | |
1309 PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen)); | |
1310 if (hashAlg == SEC_OID_UNKNOWN) { | |
1311 PRINT_BUF(95, (NULL, "DHkey hash: MD5 result", | |
1312 hashes->u.s.md5, MD5_LENGTH)); | |
1313 PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result", | |
1314 hashes->u.s.sha, SHA1_LENGTH)); | |
1315 } else { | |
1316 PRINT_BUF(95, (NULL, "DHkey hash: result", | |
1317 hashes->u.raw, hashes->len)); | |
1318 } | |
1319 | |
1320 if (hashBuf != buf && hashBuf != NULL) | |
1321 PORT_Free(hashBuf); | |
1322 return rv; | |
1323 } | |
1324 | |
1325 static void | |
1326 ssl3_BumpSequenceNumber(SSL3SequenceNumber *num) | |
1327 { | |
1328 num->low++; | |
1329 if (num->low == 0) | |
1330 num->high++; | |
1331 } | |
1332 | |
1333 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */ | |
1334 static void | |
1335 ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat) | |
1336 { | |
1337 if (mat->write_key != NULL) { | |
1338 PK11_FreeSymKey(mat->write_key); | |
1339 mat->write_key = NULL; | |
1340 } | |
1341 if (mat->write_mac_key != NULL) { | |
1342 PK11_FreeSymKey(mat->write_mac_key); | |
1343 mat->write_mac_key = NULL; | |
1344 } | |
1345 if (mat->write_mac_context != NULL) { | |
1346 PK11_DestroyContext(mat->write_mac_context, PR_TRUE); | |
1347 mat->write_mac_context = NULL; | |
1348 } | |
1349 } | |
1350 | |
1351 /* Called from ssl3_SendChangeCipherSpecs() and | |
1352 ** ssl3_HandleChangeCipherSpecs() | |
1353 ** ssl3_DestroySSL3Info | |
1354 ** Caller must hold SpecWriteLock. | |
1355 */ | |
1356 void | |
1357 ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName) | |
1358 { | |
1359 PRBool freeit = (PRBool)(!spec->bypassCiphers); | |
1360 /* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! *
/ | |
1361 if (spec->destroy) { | |
1362 spec->destroy(spec->encodeContext, freeit); | |
1363 spec->destroy(spec->decodeContext, freeit); | |
1364 spec->encodeContext = NULL; /* paranoia */ | |
1365 spec->decodeContext = NULL; | |
1366 } | |
1367 if (spec->destroyCompressContext && spec->compressContext) { | |
1368 spec->destroyCompressContext(spec->compressContext, 1); | |
1369 spec->compressContext = NULL; | |
1370 } | |
1371 if (spec->destroyDecompressContext && spec->decompressContext) { | |
1372 spec->destroyDecompressContext(spec->decompressContext, 1); | |
1373 spec->decompressContext = NULL; | |
1374 } | |
1375 if (freeSrvName && spec->srvVirtName.data) { | |
1376 SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE); | |
1377 } | |
1378 if (spec->master_secret != NULL) { | |
1379 PK11_FreeSymKey(spec->master_secret); | |
1380 spec->master_secret = NULL; | |
1381 } | |
1382 spec->msItem.data = NULL; | |
1383 spec->msItem.len = 0; | |
1384 ssl3_CleanupKeyMaterial(&spec->client); | |
1385 ssl3_CleanupKeyMaterial(&spec->server); | |
1386 spec->bypassCiphers = PR_FALSE; | |
1387 spec->destroy=NULL; | |
1388 spec->destroyCompressContext = NULL; | |
1389 spec->destroyDecompressContext = NULL; | |
1390 } | |
1391 | |
1392 /* Fill in the pending cipher spec with info from the selected ciphersuite. | |
1393 ** This is as much initialization as we can do without having key material. | |
1394 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello() | |
1395 ** Caller must hold the ssl3 handshake lock. | |
1396 ** Acquires & releases SpecWriteLock. | |
1397 */ | |
1398 static SECStatus | |
1399 ssl3_SetupPendingCipherSpec(sslSocket *ss) | |
1400 { | |
1401 ssl3CipherSpec * pwSpec; | |
1402 ssl3CipherSpec * cwSpec; | |
1403 ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite; | |
1404 SSL3MACAlgorithm mac; | |
1405 SSL3BulkCipher cipher; | |
1406 SSL3KeyExchangeAlgorithm kea; | |
1407 const ssl3CipherSuiteDef *suite_def; | |
1408 PRBool isTLS; | |
1409 | |
1410 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
1411 | |
1412 ssl_GetSpecWriteLock(ss); /*******************************/ | |
1413 | |
1414 pwSpec = ss->ssl3.pwSpec; | |
1415 PORT_Assert(pwSpec == ss->ssl3.prSpec); | |
1416 | |
1417 /* This hack provides maximal interoperability with SSL 3 servers. */ | |
1418 cwSpec = ss->ssl3.cwSpec; | |
1419 if (cwSpec->mac_def->mac == mac_null) { | |
1420 /* SSL records are not being MACed. */ | |
1421 cwSpec->version = ss->version; | |
1422 } | |
1423 | |
1424 pwSpec->version = ss->version; | |
1425 isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
1426 | |
1427 SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x", | |
1428 SSL_GETPID(), ss->fd, suite)); | |
1429 | |
1430 suite_def = ssl_LookupCipherSuiteDef(suite); | |
1431 if (suite_def == NULL) { | |
1432 ssl_ReleaseSpecWriteLock(ss); | |
1433 return SECFailure; /* error code set by ssl_LookupCipherSuiteDef */ | |
1434 } | |
1435 | |
1436 if (IS_DTLS(ss)) { | |
1437 /* Double-check that we did not pick an RC4 suite */ | |
1438 PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) && | |
1439 (suite_def->bulk_cipher_alg != cipher_rc4_40) && | |
1440 (suite_def->bulk_cipher_alg != cipher_rc4_56)); | |
1441 } | |
1442 | |
1443 cipher = suite_def->bulk_cipher_alg; | |
1444 kea = suite_def->key_exchange_alg; | |
1445 mac = suite_def->mac_alg; | |
1446 if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS) | |
1447 mac += 2; | |
1448 | |
1449 ss->ssl3.hs.suite_def = suite_def; | |
1450 ss->ssl3.hs.kea_def = &kea_defs[kea]; | |
1451 PORT_Assert(ss->ssl3.hs.kea_def->kea == kea); | |
1452 | |
1453 pwSpec->cipher_def = &bulk_cipher_defs[cipher]; | |
1454 PORT_Assert(pwSpec->cipher_def->cipher == cipher); | |
1455 | |
1456 pwSpec->mac_def = &mac_defs[mac]; | |
1457 PORT_Assert(pwSpec->mac_def->mac == mac); | |
1458 | |
1459 ss->sec.keyBits = pwSpec->cipher_def->key_size * BPB; | |
1460 ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB; | |
1461 ss->sec.cipherType = cipher; | |
1462 | |
1463 pwSpec->encodeContext = NULL; | |
1464 pwSpec->decodeContext = NULL; | |
1465 | |
1466 pwSpec->mac_size = pwSpec->mac_def->mac_size; | |
1467 | |
1468 pwSpec->compression_method = ss->ssl3.hs.compression; | |
1469 pwSpec->compressContext = NULL; | |
1470 pwSpec->decompressContext = NULL; | |
1471 | |
1472 ssl_ReleaseSpecWriteLock(ss); /*******************************/ | |
1473 return SECSuccess; | |
1474 } | |
1475 | |
1476 #ifdef NSS_ENABLE_ZLIB | |
1477 #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream) | |
1478 | |
1479 static SECStatus | |
1480 ssl3_MapZlibError(int zlib_error) | |
1481 { | |
1482 switch (zlib_error) { | |
1483 case Z_OK: | |
1484 return SECSuccess; | |
1485 default: | |
1486 return SECFailure; | |
1487 } | |
1488 } | |
1489 | |
1490 static SECStatus | |
1491 ssl3_DeflateInit(void *void_context) | |
1492 { | |
1493 z_stream *context = void_context; | |
1494 context->zalloc = NULL; | |
1495 context->zfree = NULL; | |
1496 context->opaque = NULL; | |
1497 | |
1498 return ssl3_MapZlibError(deflateInit(context, Z_DEFAULT_COMPRESSION)); | |
1499 } | |
1500 | |
1501 static SECStatus | |
1502 ssl3_InflateInit(void *void_context) | |
1503 { | |
1504 z_stream *context = void_context; | |
1505 context->zalloc = NULL; | |
1506 context->zfree = NULL; | |
1507 context->opaque = NULL; | |
1508 context->next_in = NULL; | |
1509 context->avail_in = 0; | |
1510 | |
1511 return ssl3_MapZlibError(inflateInit(context)); | |
1512 } | |
1513 | |
1514 static SECStatus | |
1515 ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len, | |
1516 int maxout, const unsigned char *in, int inlen) | |
1517 { | |
1518 z_stream *context = void_context; | |
1519 | |
1520 if (!inlen) { | |
1521 *out_len = 0; | |
1522 return SECSuccess; | |
1523 } | |
1524 | |
1525 context->next_in = (unsigned char*) in; | |
1526 context->avail_in = inlen; | |
1527 context->next_out = out; | |
1528 context->avail_out = maxout; | |
1529 if (deflate(context, Z_SYNC_FLUSH) != Z_OK) { | |
1530 return SECFailure; | |
1531 } | |
1532 if (context->avail_out == 0) { | |
1533 /* We ran out of space! */ | |
1534 SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing", | |
1535 SSL_GETPID())); | |
1536 return SECFailure; | |
1537 } | |
1538 | |
1539 *out_len = maxout - context->avail_out; | |
1540 return SECSuccess; | |
1541 } | |
1542 | |
1543 static SECStatus | |
1544 ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len, | |
1545 int maxout, const unsigned char *in, int inlen) | |
1546 { | |
1547 z_stream *context = void_context; | |
1548 | |
1549 if (!inlen) { | |
1550 *out_len = 0; | |
1551 return SECSuccess; | |
1552 } | |
1553 | |
1554 context->next_in = (unsigned char*) in; | |
1555 context->avail_in = inlen; | |
1556 context->next_out = out; | |
1557 context->avail_out = maxout; | |
1558 if (inflate(context, Z_SYNC_FLUSH) != Z_OK) { | |
1559 PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE); | |
1560 return SECFailure; | |
1561 } | |
1562 | |
1563 *out_len = maxout - context->avail_out; | |
1564 return SECSuccess; | |
1565 } | |
1566 | |
1567 static SECStatus | |
1568 ssl3_DestroyCompressContext(void *void_context, PRBool unused) | |
1569 { | |
1570 deflateEnd(void_context); | |
1571 PORT_Free(void_context); | |
1572 return SECSuccess; | |
1573 } | |
1574 | |
1575 static SECStatus | |
1576 ssl3_DestroyDecompressContext(void *void_context, PRBool unused) | |
1577 { | |
1578 inflateEnd(void_context); | |
1579 PORT_Free(void_context); | |
1580 return SECSuccess; | |
1581 } | |
1582 | |
1583 #endif /* NSS_ENABLE_ZLIB */ | |
1584 | |
1585 /* Initialize the compression functions and contexts for the given | |
1586 * CipherSpec. */ | |
1587 static SECStatus | |
1588 ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec) | |
1589 { | |
1590 /* Setup the compression functions */ | |
1591 switch (pwSpec->compression_method) { | |
1592 case ssl_compression_null: | |
1593 pwSpec->compressor = NULL; | |
1594 pwSpec->decompressor = NULL; | |
1595 pwSpec->compressContext = NULL; | |
1596 pwSpec->decompressContext = NULL; | |
1597 pwSpec->destroyCompressContext = NULL; | |
1598 pwSpec->destroyDecompressContext = NULL; | |
1599 break; | |
1600 #ifdef NSS_ENABLE_ZLIB | |
1601 case ssl_compression_deflate: | |
1602 pwSpec->compressor = ssl3_DeflateCompress; | |
1603 pwSpec->decompressor = ssl3_DeflateDecompress; | |
1604 pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); | |
1605 pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); | |
1606 pwSpec->destroyCompressContext = ssl3_DestroyCompressContext; | |
1607 pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext; | |
1608 ssl3_DeflateInit(pwSpec->compressContext); | |
1609 ssl3_InflateInit(pwSpec->decompressContext); | |
1610 break; | |
1611 #endif /* NSS_ENABLE_ZLIB */ | |
1612 default: | |
1613 PORT_Assert(0); | |
1614 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
1615 return SECFailure; | |
1616 } | |
1617 | |
1618 return SECSuccess; | |
1619 } | |
1620 | |
1621 #ifndef NO_PKCS11_BYPASS | |
1622 /* Initialize encryption contexts for pending spec. | |
1623 * MAC contexts are set up when computing the mac, not here. | |
1624 * Master Secret already is derived in spec->msItem | |
1625 * Caller holds Spec write lock. | |
1626 */ | |
1627 static SECStatus | |
1628 ssl3_InitPendingContextsBypass(sslSocket *ss) | |
1629 { | |
1630 ssl3CipherSpec * pwSpec; | |
1631 const ssl3BulkCipherDef *cipher_def; | |
1632 void * serverContext = NULL; | |
1633 void * clientContext = NULL; | |
1634 BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL; | |
1635 int mode = 0; | |
1636 unsigned int optArg1 = 0; | |
1637 unsigned int optArg2 = 0; | |
1638 PRBool server_encrypts = ss->sec.isServer; | |
1639 SSLCipherAlgorithm calg; | |
1640 SECStatus rv; | |
1641 | |
1642 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
1643 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); | |
1644 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
1645 | |
1646 pwSpec = ss->ssl3.pwSpec; | |
1647 cipher_def = pwSpec->cipher_def; | |
1648 | |
1649 calg = cipher_def->calg; | |
1650 | |
1651 if (calg == ssl_calg_aes_gcm) { | |
1652 pwSpec->encode = NULL; | |
1653 pwSpec->decode = NULL; | |
1654 pwSpec->destroy = NULL; | |
1655 pwSpec->encodeContext = NULL; | |
1656 pwSpec->decodeContext = NULL; | |
1657 pwSpec->aead = ssl3_AESGCMBypass; | |
1658 ssl3_InitCompressionContext(pwSpec); | |
1659 return SECSuccess; | |
1660 } | |
1661 | |
1662 serverContext = pwSpec->server.cipher_context; | |
1663 clientContext = pwSpec->client.cipher_context; | |
1664 | |
1665 switch (calg) { | |
1666 case ssl_calg_null: | |
1667 pwSpec->encode = Null_Cipher; | |
1668 pwSpec->decode = Null_Cipher; | |
1669 pwSpec->destroy = NULL; | |
1670 goto success; | |
1671 | |
1672 case ssl_calg_rc4: | |
1673 initFn = (BLapiInitContextFunc)RC4_InitContext; | |
1674 pwSpec->encode = (SSLCipher) RC4_Encrypt; | |
1675 pwSpec->decode = (SSLCipher) RC4_Decrypt; | |
1676 pwSpec->destroy = (SSLDestroy) RC4_DestroyContext; | |
1677 break; | |
1678 case ssl_calg_rc2: | |
1679 initFn = (BLapiInitContextFunc)RC2_InitContext; | |
1680 mode = NSS_RC2_CBC; | |
1681 optArg1 = cipher_def->key_size; | |
1682 pwSpec->encode = (SSLCipher) RC2_Encrypt; | |
1683 pwSpec->decode = (SSLCipher) RC2_Decrypt; | |
1684 pwSpec->destroy = (SSLDestroy) RC2_DestroyContext; | |
1685 break; | |
1686 case ssl_calg_des: | |
1687 initFn = (BLapiInitContextFunc)DES_InitContext; | |
1688 mode = NSS_DES_CBC; | |
1689 optArg1 = server_encrypts; | |
1690 pwSpec->encode = (SSLCipher) DES_Encrypt; | |
1691 pwSpec->decode = (SSLCipher) DES_Decrypt; | |
1692 pwSpec->destroy = (SSLDestroy) DES_DestroyContext; | |
1693 break; | |
1694 case ssl_calg_3des: | |
1695 initFn = (BLapiInitContextFunc)DES_InitContext; | |
1696 mode = NSS_DES_EDE3_CBC; | |
1697 optArg1 = server_encrypts; | |
1698 pwSpec->encode = (SSLCipher) DES_Encrypt; | |
1699 pwSpec->decode = (SSLCipher) DES_Decrypt; | |
1700 pwSpec->destroy = (SSLDestroy) DES_DestroyContext; | |
1701 break; | |
1702 case ssl_calg_aes: | |
1703 initFn = (BLapiInitContextFunc)AES_InitContext; | |
1704 mode = NSS_AES_CBC; | |
1705 optArg1 = server_encrypts; | |
1706 optArg2 = AES_BLOCK_SIZE; | |
1707 pwSpec->encode = (SSLCipher) AES_Encrypt; | |
1708 pwSpec->decode = (SSLCipher) AES_Decrypt; | |
1709 pwSpec->destroy = (SSLDestroy) AES_DestroyContext; | |
1710 break; | |
1711 | |
1712 case ssl_calg_camellia: | |
1713 initFn = (BLapiInitContextFunc)Camellia_InitContext; | |
1714 mode = NSS_CAMELLIA_CBC; | |
1715 optArg1 = server_encrypts; | |
1716 optArg2 = CAMELLIA_BLOCK_SIZE; | |
1717 pwSpec->encode = (SSLCipher) Camellia_Encrypt; | |
1718 pwSpec->decode = (SSLCipher) Camellia_Decrypt; | |
1719 pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext; | |
1720 break; | |
1721 | |
1722 case ssl_calg_seed: | |
1723 initFn = (BLapiInitContextFunc)SEED_InitContext; | |
1724 mode = NSS_SEED_CBC; | |
1725 optArg1 = server_encrypts; | |
1726 optArg2 = SEED_BLOCK_SIZE; | |
1727 pwSpec->encode = (SSLCipher) SEED_Encrypt; | |
1728 pwSpec->decode = (SSLCipher) SEED_Decrypt; | |
1729 pwSpec->destroy = (SSLDestroy) SEED_DestroyContext; | |
1730 break; | |
1731 | |
1732 case ssl_calg_idea: | |
1733 case ssl_calg_fortezza : | |
1734 default: | |
1735 PORT_Assert(0); | |
1736 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
1737 goto bail_out; | |
1738 } | |
1739 rv = (*initFn)(serverContext, | |
1740 pwSpec->server.write_key_item.data, | |
1741 pwSpec->server.write_key_item.len, | |
1742 pwSpec->server.write_iv_item.data, | |
1743 mode, optArg1, optArg2); | |
1744 if (rv != SECSuccess) { | |
1745 PORT_Assert(0); | |
1746 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
1747 goto bail_out; | |
1748 } | |
1749 | |
1750 switch (calg) { | |
1751 case ssl_calg_des: | |
1752 case ssl_calg_3des: | |
1753 case ssl_calg_aes: | |
1754 case ssl_calg_camellia: | |
1755 case ssl_calg_seed: | |
1756 /* For block ciphers, if the server is encrypting, then the client | |
1757 * is decrypting, and vice versa. | |
1758 */ | |
1759 optArg1 = !optArg1; | |
1760 break; | |
1761 /* kill warnings. */ | |
1762 case ssl_calg_null: | |
1763 case ssl_calg_rc4: | |
1764 case ssl_calg_rc2: | |
1765 case ssl_calg_idea: | |
1766 case ssl_calg_fortezza: | |
1767 case ssl_calg_aes_gcm: | |
1768 break; | |
1769 } | |
1770 | |
1771 rv = (*initFn)(clientContext, | |
1772 pwSpec->client.write_key_item.data, | |
1773 pwSpec->client.write_key_item.len, | |
1774 pwSpec->client.write_iv_item.data, | |
1775 mode, optArg1, optArg2); | |
1776 if (rv != SECSuccess) { | |
1777 PORT_Assert(0); | |
1778 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
1779 goto bail_out; | |
1780 } | |
1781 | |
1782 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; | |
1783 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext; | |
1784 | |
1785 ssl3_InitCompressionContext(pwSpec); | |
1786 | |
1787 success: | |
1788 return SECSuccess; | |
1789 | |
1790 bail_out: | |
1791 return SECFailure; | |
1792 } | |
1793 #endif | |
1794 | |
1795 /* This function should probably be moved to pk11wrap and be named | |
1796 * PK11_ParamFromIVAndEffectiveKeyBits | |
1797 */ | |
1798 static SECItem * | |
1799 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits) | |
1800 { | |
1801 SECItem * param = PK11_ParamFromIV(mtype, iv); | |
1802 if (param && param->data && param->len >= sizeof(CK_RC2_PARAMS)) { | |
1803 switch (mtype) { | |
1804 case CKM_RC2_KEY_GEN: | |
1805 case CKM_RC2_ECB: | |
1806 case CKM_RC2_CBC: | |
1807 case CKM_RC2_MAC: | |
1808 case CKM_RC2_MAC_GENERAL: | |
1809 case CKM_RC2_CBC_PAD: | |
1810 *(CK_RC2_PARAMS *)param->data = ulEffectiveBits; | |
1811 default: break; | |
1812 } | |
1813 } | |
1814 return param; | |
1815 } | |
1816 | |
1817 /* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data | |
1818 * which is included in the MAC or AEAD additional data) to |out| and returns | |
1819 * its length. See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the | |
1820 * definition of the AEAD additional data. | |
1821 * | |
1822 * TLS pseudo-header includes the record's version field, SSL's doesn't. Which | |
1823 * pseudo-header defintiion to use should be decided based on the version of | |
1824 * the protocol that was negotiated when the cipher spec became current, NOT | |
1825 * based on the version value in the record itself, and the decision is passed | |
1826 * to this function as the |includesVersion| argument. But, the |version| | |
1827 * argument should be the record's version value. | |
1828 */ | |
1829 static unsigned int | |
1830 ssl3_BuildRecordPseudoHeader(unsigned char *out, | |
1831 SSL3SequenceNumber seq_num, | |
1832 SSL3ContentType type, | |
1833 PRBool includesVersion, | |
1834 SSL3ProtocolVersion version, | |
1835 PRBool isDTLS, | |
1836 int length) | |
1837 { | |
1838 out[0] = (unsigned char)(seq_num.high >> 24); | |
1839 out[1] = (unsigned char)(seq_num.high >> 16); | |
1840 out[2] = (unsigned char)(seq_num.high >> 8); | |
1841 out[3] = (unsigned char)(seq_num.high >> 0); | |
1842 out[4] = (unsigned char)(seq_num.low >> 24); | |
1843 out[5] = (unsigned char)(seq_num.low >> 16); | |
1844 out[6] = (unsigned char)(seq_num.low >> 8); | |
1845 out[7] = (unsigned char)(seq_num.low >> 0); | |
1846 out[8] = type; | |
1847 | |
1848 /* SSL3 MAC doesn't include the record's version field. */ | |
1849 if (!includesVersion) { | |
1850 out[9] = MSB(length); | |
1851 out[10] = LSB(length); | |
1852 return 11; | |
1853 } | |
1854 | |
1855 /* TLS MAC and AEAD additional data include version. */ | |
1856 if (isDTLS) { | |
1857 SSL3ProtocolVersion dtls_version; | |
1858 | |
1859 dtls_version = dtls_TLSVersionToDTLSVersion(version); | |
1860 out[9] = MSB(dtls_version); | |
1861 out[10] = LSB(dtls_version); | |
1862 } else { | |
1863 out[9] = MSB(version); | |
1864 out[10] = LSB(version); | |
1865 } | |
1866 out[11] = MSB(length); | |
1867 out[12] = LSB(length); | |
1868 return 13; | |
1869 } | |
1870 | |
1871 typedef SECStatus (*PK11CryptFcn)( | |
1872 PK11SymKey *symKey, CK_MECHANISM_TYPE mechanism, SECItem *param, | |
1873 unsigned char *out, unsigned int *outLen, unsigned int maxLen, | |
1874 const unsigned char *in, unsigned int inLen); | |
1875 | |
1876 static PK11CryptFcn pk11_encrypt = NULL; | |
1877 static PK11CryptFcn pk11_decrypt = NULL; | |
1878 | |
1879 static PRCallOnceType resolvePK11CryptOnce; | |
1880 | |
1881 static PRStatus | |
1882 ssl3_ResolvePK11CryptFunctions(void) | |
1883 { | |
1884 #ifdef LINUX | |
1885 /* On Linux we use the system NSS libraries. Look up the PK11_Encrypt and | |
1886 * PK11_Decrypt functions at run time. */ | |
1887 void *handle = dlopen(NULL, RTLD_LAZY); | |
1888 if (!handle) { | |
1889 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
1890 return PR_FAILURE; | |
1891 } | |
1892 pk11_encrypt = (PK11CryptFcn)dlsym(handle, "PK11_Encrypt"); | |
1893 pk11_decrypt = (PK11CryptFcn)dlsym(handle, "PK11_Decrypt"); | |
1894 dlclose(handle); | |
1895 return PR_SUCCESS; | |
1896 #else | |
1897 /* On other platforms we use our own copy of NSS. PK11_Encrypt and | |
1898 * PK11_Decrypt are known to be available. */ | |
1899 pk11_encrypt = PK11_Encrypt; | |
1900 pk11_decrypt = PK11_Decrypt; | |
1901 return PR_SUCCESS; | |
1902 #endif | |
1903 } | |
1904 | |
1905 /* | |
1906 * In NSS 3.15, PK11_Encrypt and PK11_Decrypt were added to provide access | |
1907 * to the AES GCM implementation in the NSS softoken. So the presence of | |
1908 * these two functions implies the NSS version supports AES GCM. | |
1909 */ | |
1910 static PRBool | |
1911 ssl3_HasGCMSupport(void) | |
1912 { | |
1913 (void)PR_CallOnce(&resolvePK11CryptOnce, ssl3_ResolvePK11CryptFunctions); | |
1914 return pk11_encrypt != NULL; | |
1915 } | |
1916 | |
1917 /* On this socket, disable the GCM cipher suites */ | |
1918 SECStatus | |
1919 ssl3_DisableGCMSuites(sslSocket * ss) | |
1920 { | |
1921 unsigned int i; | |
1922 | |
1923 for (i = 0; i < PR_ARRAY_SIZE(cipher_suite_defs); i++) { | |
1924 const ssl3CipherSuiteDef *cipher_def = &cipher_suite_defs[i]; | |
1925 if (cipher_def->bulk_cipher_alg == cipher_aes_128_gcm) { | |
1926 SECStatus rv = ssl3_CipherPrefSet(ss, cipher_def->cipher_suite, | |
1927 PR_FALSE); | |
1928 PORT_Assert(rv == SECSuccess); /* else is coding error */ | |
1929 } | |
1930 } | |
1931 return SECSuccess; | |
1932 } | |
1933 | |
1934 static SECStatus | |
1935 ssl3_AESGCM(ssl3KeyMaterial *keys, | |
1936 PRBool doDecrypt, | |
1937 unsigned char *out, | |
1938 int *outlen, | |
1939 int maxout, | |
1940 const unsigned char *in, | |
1941 int inlen, | |
1942 const unsigned char *additionalData, | |
1943 int additionalDataLen) | |
1944 { | |
1945 SECItem param; | |
1946 SECStatus rv = SECFailure; | |
1947 unsigned char nonce[12]; | |
1948 unsigned int uOutLen; | |
1949 CK_GCM_PARAMS gcmParams; | |
1950 | |
1951 static const int tagSize = 16; | |
1952 static const int explicitNonceLen = 8; | |
1953 | |
1954 /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the | |
1955 * nonce is formed. */ | |
1956 memcpy(nonce, keys->write_iv, 4); | |
1957 if (doDecrypt) { | |
1958 memcpy(nonce + 4, in, explicitNonceLen); | |
1959 in += explicitNonceLen; | |
1960 inlen -= explicitNonceLen; | |
1961 *outlen = 0; | |
1962 } else { | |
1963 if (maxout < explicitNonceLen) { | |
1964 PORT_SetError(SEC_ERROR_INPUT_LEN); | |
1965 return SECFailure; | |
1966 } | |
1967 /* Use the 64-bit sequence number as the explicit nonce. */ | |
1968 memcpy(nonce + 4, additionalData, explicitNonceLen); | |
1969 memcpy(out, additionalData, explicitNonceLen); | |
1970 out += explicitNonceLen; | |
1971 maxout -= explicitNonceLen; | |
1972 *outlen = explicitNonceLen; | |
1973 } | |
1974 | |
1975 param.type = siBuffer; | |
1976 param.data = (unsigned char *) &gcmParams; | |
1977 param.len = sizeof(gcmParams); | |
1978 gcmParams.pIv = nonce; | |
1979 gcmParams.ulIvLen = sizeof(nonce); | |
1980 gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ | |
1981 gcmParams.ulAADLen = additionalDataLen; | |
1982 gcmParams.ulTagBits = tagSize * 8; | |
1983 | |
1984 if (doDecrypt) { | |
1985 rv = pk11_decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, | |
1986 maxout, in, inlen); | |
1987 } else { | |
1988 rv = pk11_encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, | |
1989 maxout, in, inlen); | |
1990 } | |
1991 *outlen += (int) uOutLen; | |
1992 | |
1993 return rv; | |
1994 } | |
1995 | |
1996 #ifndef NO_PKCS11_BYPASS | |
1997 static SECStatus | |
1998 ssl3_AESGCMBypass(ssl3KeyMaterial *keys, | |
1999 PRBool doDecrypt, | |
2000 unsigned char *out, | |
2001 int *outlen, | |
2002 int maxout, | |
2003 const unsigned char *in, | |
2004 int inlen, | |
2005 const unsigned char *additionalData, | |
2006 int additionalDataLen) | |
2007 { | |
2008 SECStatus rv = SECFailure; | |
2009 unsigned char nonce[12]; | |
2010 unsigned int uOutLen; | |
2011 AESContext *cx; | |
2012 CK_GCM_PARAMS gcmParams; | |
2013 | |
2014 static const int tagSize = 16; | |
2015 static const int explicitNonceLen = 8; | |
2016 | |
2017 /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the | |
2018 * nonce is formed. */ | |
2019 PORT_Assert(keys->write_iv_item.len == 4); | |
2020 if (keys->write_iv_item.len != 4) { | |
2021 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
2022 return SECFailure; | |
2023 } | |
2024 memcpy(nonce, keys->write_iv_item.data, 4); | |
2025 if (doDecrypt) { | |
2026 memcpy(nonce + 4, in, explicitNonceLen); | |
2027 in += explicitNonceLen; | |
2028 inlen -= explicitNonceLen; | |
2029 *outlen = 0; | |
2030 } else { | |
2031 if (maxout < explicitNonceLen) { | |
2032 PORT_SetError(SEC_ERROR_INPUT_LEN); | |
2033 return SECFailure; | |
2034 } | |
2035 /* Use the 64-bit sequence number as the explicit nonce. */ | |
2036 memcpy(nonce + 4, additionalData, explicitNonceLen); | |
2037 memcpy(out, additionalData, explicitNonceLen); | |
2038 out += explicitNonceLen; | |
2039 maxout -= explicitNonceLen; | |
2040 *outlen = explicitNonceLen; | |
2041 } | |
2042 | |
2043 gcmParams.pIv = nonce; | |
2044 gcmParams.ulIvLen = sizeof(nonce); | |
2045 gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ | |
2046 gcmParams.ulAADLen = additionalDataLen; | |
2047 gcmParams.ulTagBits = tagSize * 8; | |
2048 | |
2049 cx = (AESContext *)keys->cipher_context; | |
2050 rv = AES_InitContext(cx, keys->write_key_item.data, | |
2051 keys->write_key_item.len, | |
2052 (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt, | |
2053 AES_BLOCK_SIZE); | |
2054 if (rv != SECSuccess) { | |
2055 return rv; | |
2056 } | |
2057 if (doDecrypt) { | |
2058 rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen); | |
2059 } else { | |
2060 rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen); | |
2061 } | |
2062 AES_DestroyContext(cx, PR_FALSE); | |
2063 *outlen += (int) uOutLen; | |
2064 | |
2065 return rv; | |
2066 } | |
2067 #endif | |
2068 | |
2069 static SECStatus | |
2070 ssl3_ChaCha20Poly1305( | |
2071 ssl3KeyMaterial *keys, | |
2072 PRBool doDecrypt, | |
2073 unsigned char *out, | |
2074 int *outlen, | |
2075 int maxout, | |
2076 const unsigned char *in, | |
2077 int inlen, | |
2078 const unsigned char *additionalData, | |
2079 int additionalDataLen) | |
2080 { | |
2081 SECItem param; | |
2082 SECStatus rv = SECFailure; | |
2083 unsigned int uOutLen; | |
2084 CK_NSS_AEAD_PARAMS aeadParams; | |
2085 static const int tagSize = 16; | |
2086 | |
2087 param.type = siBuffer; | |
2088 param.len = sizeof(aeadParams); | |
2089 param.data = (unsigned char *) &aeadParams; | |
2090 memset(&aeadParams, 0, sizeof(aeadParams)); | |
2091 aeadParams.pIv = (unsigned char *) additionalData; | |
2092 aeadParams.ulIvLen = 8; | |
2093 aeadParams.pAAD = (unsigned char *) additionalData; | |
2094 aeadParams.ulAADLen = additionalDataLen; | |
2095 aeadParams.ulTagLen = tagSize; | |
2096 | |
2097 if (doDecrypt) { | |
2098 rv = pk11_decrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, ¶m, | |
2099 out, &uOutLen, maxout, in, inlen); | |
2100 } else { | |
2101 rv = pk11_encrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, ¶m, | |
2102 out, &uOutLen, maxout, in, inlen); | |
2103 } | |
2104 *outlen = (int) uOutLen; | |
2105 | |
2106 return rv; | |
2107 } | |
2108 | |
2109 /* Initialize encryption and MAC contexts for pending spec. | |
2110 * Master Secret already is derived. | |
2111 * Caller holds Spec write lock. | |
2112 */ | |
2113 static SECStatus | |
2114 ssl3_InitPendingContextsPKCS11(sslSocket *ss) | |
2115 { | |
2116 ssl3CipherSpec * pwSpec; | |
2117 const ssl3BulkCipherDef *cipher_def; | |
2118 PK11Context * serverContext = NULL; | |
2119 PK11Context * clientContext = NULL; | |
2120 SECItem * param; | |
2121 CK_MECHANISM_TYPE mechanism; | |
2122 CK_MECHANISM_TYPE mac_mech; | |
2123 CK_ULONG macLength; | |
2124 CK_ULONG effKeyBits; | |
2125 SECItem iv; | |
2126 SECItem mac_param; | |
2127 SSLCipherAlgorithm calg; | |
2128 | |
2129 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
2130 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); | |
2131 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
2132 | |
2133 pwSpec = ss->ssl3.pwSpec; | |
2134 cipher_def = pwSpec->cipher_def; | |
2135 macLength = pwSpec->mac_size; | |
2136 calg = cipher_def->calg; | |
2137 PORT_Assert(alg2Mech[calg].calg == calg); | |
2138 | |
2139 pwSpec->client.write_mac_context = NULL; | |
2140 pwSpec->server.write_mac_context = NULL; | |
2141 | |
2142 if (calg == calg_aes_gcm || calg == calg_chacha20) { | |
2143 pwSpec->encode = NULL; | |
2144 pwSpec->decode = NULL; | |
2145 pwSpec->destroy = NULL; | |
2146 pwSpec->encodeContext = NULL; | |
2147 pwSpec->decodeContext = NULL; | |
2148 if (calg == calg_aes_gcm) { | |
2149 pwSpec->aead = ssl3_AESGCM; | |
2150 } else { | |
2151 pwSpec->aead = ssl3_ChaCha20Poly1305; | |
2152 } | |
2153 return SECSuccess; | |
2154 } | |
2155 | |
2156 /* | |
2157 ** Now setup the MAC contexts, | |
2158 ** crypto contexts are setup below. | |
2159 */ | |
2160 | |
2161 mac_mech = pwSpec->mac_def->mmech; | |
2162 mac_param.data = (unsigned char *)&macLength; | |
2163 mac_param.len = sizeof(macLength); | |
2164 mac_param.type = 0; | |
2165 | |
2166 pwSpec->client.write_mac_context = PK11_CreateContextBySymKey( | |
2167 mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param); | |
2168 if (pwSpec->client.write_mac_context == NULL) { | |
2169 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); | |
2170 goto fail; | |
2171 } | |
2172 pwSpec->server.write_mac_context = PK11_CreateContextBySymKey( | |
2173 mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param); | |
2174 if (pwSpec->server.write_mac_context == NULL) { | |
2175 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); | |
2176 goto fail; | |
2177 } | |
2178 | |
2179 /* | |
2180 ** Now setup the crypto contexts. | |
2181 */ | |
2182 | |
2183 if (calg == calg_null) { | |
2184 pwSpec->encode = Null_Cipher; | |
2185 pwSpec->decode = Null_Cipher; | |
2186 pwSpec->destroy = NULL; | |
2187 return SECSuccess; | |
2188 } | |
2189 mechanism = alg2Mech[calg].cmech; | |
2190 effKeyBits = cipher_def->key_size * BPB; | |
2191 | |
2192 /* | |
2193 * build the server context | |
2194 */ | |
2195 iv.data = pwSpec->server.write_iv; | |
2196 iv.len = cipher_def->iv_size; | |
2197 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); | |
2198 if (param == NULL) { | |
2199 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); | |
2200 goto fail; | |
2201 } | |
2202 serverContext = PK11_CreateContextBySymKey(mechanism, | |
2203 (ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT), | |
2204 pwSpec->server.write_key, param); | |
2205 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); | |
2206 if (iv.data) | |
2207 PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len); | |
2208 SECITEM_FreeItem(param, PR_TRUE); | |
2209 if (serverContext == NULL) { | |
2210 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); | |
2211 goto fail; | |
2212 } | |
2213 | |
2214 /* | |
2215 * build the client context | |
2216 */ | |
2217 iv.data = pwSpec->client.write_iv; | |
2218 iv.len = cipher_def->iv_size; | |
2219 | |
2220 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); | |
2221 if (param == NULL) { | |
2222 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); | |
2223 goto fail; | |
2224 } | |
2225 clientContext = PK11_CreateContextBySymKey(mechanism, | |
2226 (ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT), | |
2227 pwSpec->client.write_key, param); | |
2228 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); | |
2229 if (iv.data) | |
2230 PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len); | |
2231 SECITEM_FreeItem(param,PR_TRUE); | |
2232 if (clientContext == NULL) { | |
2233 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); | |
2234 goto fail; | |
2235 } | |
2236 pwSpec->encode = (SSLCipher) PK11_CipherOp; | |
2237 pwSpec->decode = (SSLCipher) PK11_CipherOp; | |
2238 pwSpec->destroy = (SSLDestroy) PK11_DestroyContext; | |
2239 | |
2240 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; | |
2241 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext; | |
2242 | |
2243 serverContext = NULL; | |
2244 clientContext = NULL; | |
2245 | |
2246 ssl3_InitCompressionContext(pwSpec); | |
2247 | |
2248 return SECSuccess; | |
2249 | |
2250 fail: | |
2251 if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE); | |
2252 if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE); | |
2253 if (pwSpec->client.write_mac_context != NULL) { | |
2254 PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE); | |
2255 pwSpec->client.write_mac_context = NULL; | |
2256 } | |
2257 if (pwSpec->server.write_mac_context != NULL) { | |
2258 PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE); | |
2259 pwSpec->server.write_mac_context = NULL; | |
2260 } | |
2261 | |
2262 return SECFailure; | |
2263 } | |
2264 | |
2265 /* Complete the initialization of all keys, ciphers, MACs and their contexts | |
2266 * for the pending Cipher Spec. | |
2267 * Called from: ssl3_SendClientKeyExchange (for Full handshake) | |
2268 * ssl3_HandleRSAClientKeyExchange (for Full handshake) | |
2269 * ssl3_HandleServerHello (for session restart) | |
2270 * ssl3_HandleClientHello (for session restart) | |
2271 * Sets error code, but caller probably should override to disambiguate. | |
2272 * NULL pms means re-use old master_secret. | |
2273 * | |
2274 * This code is common to the bypass and PKCS11 execution paths. | |
2275 * For the bypass case, pms is NULL. | |
2276 */ | |
2277 SECStatus | |
2278 ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms) | |
2279 { | |
2280 ssl3CipherSpec * pwSpec; | |
2281 ssl3CipherSpec * cwSpec; | |
2282 SECStatus rv; | |
2283 | |
2284 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
2285 | |
2286 ssl_GetSpecWriteLock(ss); /**************************************/ | |
2287 | |
2288 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
2289 | |
2290 pwSpec = ss->ssl3.pwSpec; | |
2291 cwSpec = ss->ssl3.cwSpec; | |
2292 | |
2293 if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) { | |
2294 rv = ssl3_DeriveMasterSecret(ss, pms); | |
2295 if (rv != SECSuccess) { | |
2296 goto done; /* err code set by ssl3_DeriveMasterSecret */ | |
2297 } | |
2298 } | |
2299 #ifndef NO_PKCS11_BYPASS | |
2300 if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) { | |
2301 /* Double Bypass succeeded in extracting the master_secret */ | |
2302 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; | |
2303 PRBool isTLS = (PRBool)(kea_def->tls_keygen || | |
2304 (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); | |
2305 pwSpec->bypassCiphers = PR_TRUE; | |
2306 rv = ssl3_KeyAndMacDeriveBypass( pwSpec, | |
2307 (const unsigned char *)&ss->ssl3.hs.client_random, | |
2308 (const unsigned char *)&ss->ssl3.hs.server_random, | |
2309 isTLS, | |
2310 (PRBool)(kea_def->is_limited)); | |
2311 if (rv == SECSuccess) { | |
2312 rv = ssl3_InitPendingContextsBypass(ss); | |
2313 } | |
2314 } else | |
2315 #endif | |
2316 if (pwSpec->master_secret) { | |
2317 rv = ssl3_DeriveConnectionKeysPKCS11(ss); | |
2318 if (rv == SECSuccess) { | |
2319 rv = ssl3_InitPendingContextsPKCS11(ss); | |
2320 } | |
2321 } else { | |
2322 PORT_Assert(pwSpec->master_secret); | |
2323 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
2324 rv = SECFailure; | |
2325 } | |
2326 if (rv != SECSuccess) { | |
2327 goto done; | |
2328 } | |
2329 | |
2330 /* Generic behaviors -- common to all crypto methods */ | |
2331 if (!IS_DTLS(ss)) { | |
2332 pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0; | |
2333 } else { | |
2334 if (cwSpec->epoch == PR_UINT16_MAX) { | |
2335 /* The problem here is that we have rehandshaked too many | |
2336 * times (you are not allowed to wrap the epoch). The | |
2337 * spec says you should be discarding the connection | |
2338 * and start over, so not much we can do here. */ | |
2339 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
2340 rv = SECFailure; | |
2341 goto done; | |
2342 } | |
2343 /* The sequence number has the high 16 bits as the epoch. */ | |
2344 pwSpec->epoch = cwSpec->epoch + 1; | |
2345 pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = | |
2346 pwSpec->epoch << 16; | |
2347 | |
2348 dtls_InitRecvdRecords(&pwSpec->recvdRecords); | |
2349 } | |
2350 pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0; | |
2351 | |
2352 done: | |
2353 ssl_ReleaseSpecWriteLock(ss); /******************************/ | |
2354 if (rv != SECSuccess) | |
2355 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); | |
2356 return rv; | |
2357 } | |
2358 | |
2359 /* | |
2360 * 60 bytes is 3 times the maximum length MAC size that is supported. | |
2361 */ | |
2362 static const unsigned char mac_pad_1 [60] = { | |
2363 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2364 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2365 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2366 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2367 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2368 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2369 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2370 0x36, 0x36, 0x36, 0x36 | |
2371 }; | |
2372 static const unsigned char mac_pad_2 [60] = { | |
2373 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2374 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2375 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2376 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2377 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2378 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2379 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2380 0x5c, 0x5c, 0x5c, 0x5c | |
2381 }; | |
2382 | |
2383 /* Called from: ssl3_SendRecord() | |
2384 ** Caller must already hold the SpecReadLock. (wish we could assert that!) | |
2385 */ | |
2386 static SECStatus | |
2387 ssl3_ComputeRecordMAC( | |
2388 ssl3CipherSpec * spec, | |
2389 PRBool useServerMacKey, | |
2390 const unsigned char *header, | |
2391 unsigned int headerLen, | |
2392 const SSL3Opaque * input, | |
2393 int inputLength, | |
2394 unsigned char * outbuf, | |
2395 unsigned int * outLength) | |
2396 { | |
2397 const ssl3MACDef * mac_def; | |
2398 SECStatus rv; | |
2399 | |
2400 PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen)); | |
2401 PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength)); | |
2402 | |
2403 mac_def = spec->mac_def; | |
2404 if (mac_def->mac == mac_null) { | |
2405 *outLength = 0; | |
2406 return SECSuccess; | |
2407 } | |
2408 #ifndef NO_PKCS11_BYPASS | |
2409 if (spec->bypassCiphers) { | |
2410 /* bypass version */ | |
2411 const SECHashObject *hashObj = NULL; | |
2412 unsigned int pad_bytes = 0; | |
2413 PRUint64 write_mac_context[MAX_MAC_CONTEXT_LLONGS]; | |
2414 | |
2415 switch (mac_def->mac) { | |
2416 case ssl_mac_null: | |
2417 *outLength = 0; | |
2418 return SECSuccess; | |
2419 case ssl_mac_md5: | |
2420 pad_bytes = 48; | |
2421 hashObj = HASH_GetRawHashObject(HASH_AlgMD5); | |
2422 break; | |
2423 case ssl_mac_sha: | |
2424 pad_bytes = 40; | |
2425 hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); | |
2426 break; | |
2427 case ssl_hmac_md5: /* used with TLS */ | |
2428 hashObj = HASH_GetRawHashObject(HASH_AlgMD5); | |
2429 break; | |
2430 case ssl_hmac_sha: /* used with TLS */ | |
2431 hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); | |
2432 break; | |
2433 case ssl_hmac_sha256: /* used with TLS */ | |
2434 hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); | |
2435 break; | |
2436 default: | |
2437 break; | |
2438 } | |
2439 if (!hashObj) { | |
2440 PORT_Assert(0); | |
2441 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
2442 return SECFailure; | |
2443 } | |
2444 | |
2445 if (spec->version <= SSL_LIBRARY_VERSION_3_0) { | |
2446 unsigned int tempLen; | |
2447 unsigned char temp[MAX_MAC_LENGTH]; | |
2448 | |
2449 /* compute "inner" part of SSL3 MAC */ | |
2450 hashObj->begin(write_mac_context); | |
2451 if (useServerMacKey) | |
2452 hashObj->update(write_mac_context, | |
2453 spec->server.write_mac_key_item.data, | |
2454 spec->server.write_mac_key_item.len); | |
2455 else | |
2456 hashObj->update(write_mac_context, | |
2457 spec->client.write_mac_key_item.data, | |
2458 spec->client.write_mac_key_item.len); | |
2459 hashObj->update(write_mac_context, mac_pad_1, pad_bytes); | |
2460 hashObj->update(write_mac_context, header, headerLen); | |
2461 hashObj->update(write_mac_context, input, inputLength); | |
2462 hashObj->end(write_mac_context, temp, &tempLen, sizeof temp); | |
2463 | |
2464 /* compute "outer" part of SSL3 MAC */ | |
2465 hashObj->begin(write_mac_context); | |
2466 if (useServerMacKey) | |
2467 hashObj->update(write_mac_context, | |
2468 spec->server.write_mac_key_item.data, | |
2469 spec->server.write_mac_key_item.len); | |
2470 else | |
2471 hashObj->update(write_mac_context, | |
2472 spec->client.write_mac_key_item.data, | |
2473 spec->client.write_mac_key_item.len); | |
2474 hashObj->update(write_mac_context, mac_pad_2, pad_bytes); | |
2475 hashObj->update(write_mac_context, temp, tempLen); | |
2476 hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size); | |
2477 rv = SECSuccess; | |
2478 } else { /* is TLS */ | |
2479 #define cx ((HMACContext *)write_mac_context) | |
2480 if (useServerMacKey) { | |
2481 rv = HMAC_Init(cx, hashObj, | |
2482 spec->server.write_mac_key_item.data, | |
2483 spec->server.write_mac_key_item.len, PR_FALSE); | |
2484 } else { | |
2485 rv = HMAC_Init(cx, hashObj, | |
2486 spec->client.write_mac_key_item.data, | |
2487 spec->client.write_mac_key_item.len, PR_FALSE); | |
2488 } | |
2489 if (rv == SECSuccess) { | |
2490 HMAC_Begin(cx); | |
2491 HMAC_Update(cx, header, headerLen); | |
2492 HMAC_Update(cx, input, inputLength); | |
2493 rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size); | |
2494 HMAC_Destroy(cx, PR_FALSE); | |
2495 } | |
2496 #undef cx | |
2497 } | |
2498 } else | |
2499 #endif | |
2500 { | |
2501 PK11Context *mac_context = | |
2502 (useServerMacKey ? spec->server.write_mac_context | |
2503 : spec->client.write_mac_context); | |
2504 rv = PK11_DigestBegin(mac_context); | |
2505 rv |= PK11_DigestOp(mac_context, header, headerLen); | |
2506 rv |= PK11_DigestOp(mac_context, input, inputLength); | |
2507 rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size); | |
2508 } | |
2509 | |
2510 PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size); | |
2511 | |
2512 PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength)); | |
2513 | |
2514 if (rv != SECSuccess) { | |
2515 rv = SECFailure; | |
2516 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); | |
2517 } | |
2518 return rv; | |
2519 } | |
2520 | |
2521 /* Called from: ssl3_HandleRecord() | |
2522 * Caller must already hold the SpecReadLock. (wish we could assert that!) | |
2523 * | |
2524 * On entry: | |
2525 * originalLen >= inputLen >= MAC size | |
2526 */ | |
2527 static SECStatus | |
2528 ssl3_ComputeRecordMACConstantTime( | |
2529 ssl3CipherSpec * spec, | |
2530 PRBool useServerMacKey, | |
2531 const unsigned char *header, | |
2532 unsigned int headerLen, | |
2533 const SSL3Opaque * input, | |
2534 int inputLen, | |
2535 int originalLen, | |
2536 unsigned char * outbuf, | |
2537 unsigned int * outLen) | |
2538 { | |
2539 CK_MECHANISM_TYPE macType; | |
2540 CK_NSS_MAC_CONSTANT_TIME_PARAMS params; | |
2541 SECItem param, inputItem, outputItem; | |
2542 SECStatus rv; | |
2543 PK11SymKey * key; | |
2544 | |
2545 PORT_Assert(inputLen >= spec->mac_size); | |
2546 PORT_Assert(originalLen >= inputLen); | |
2547 | |
2548 if (spec->bypassCiphers) { | |
2549 /* This function doesn't support PKCS#11 bypass. We fallback on the | |
2550 * non-constant time version. */ | |
2551 goto fallback; | |
2552 } | |
2553 | |
2554 if (spec->mac_def->mac == mac_null) { | |
2555 *outLen = 0; | |
2556 return SECSuccess; | |
2557 } | |
2558 | |
2559 macType = CKM_NSS_HMAC_CONSTANT_TIME; | |
2560 if (spec->version <= SSL_LIBRARY_VERSION_3_0) { | |
2561 macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME; | |
2562 } | |
2563 | |
2564 params.macAlg = spec->mac_def->mmech; | |
2565 params.ulBodyTotalLen = originalLen; | |
2566 params.pHeader = (unsigned char *) header; /* const cast */ | |
2567 params.ulHeaderLen = headerLen; | |
2568 | |
2569 param.data = (unsigned char*) ¶ms; | |
2570 param.len = sizeof(params); | |
2571 param.type = 0; | |
2572 | |
2573 inputItem.data = (unsigned char *) input; | |
2574 inputItem.len = inputLen; | |
2575 inputItem.type = 0; | |
2576 | |
2577 outputItem.data = outbuf; | |
2578 outputItem.len = *outLen; | |
2579 outputItem.type = 0; | |
2580 | |
2581 key = spec->server.write_mac_key; | |
2582 if (!useServerMacKey) { | |
2583 key = spec->client.write_mac_key; | |
2584 } | |
2585 | |
2586 rv = PK11_SignWithSymKey(key, macType, ¶m, &outputItem, &inputItem); | |
2587 if (rv != SECSuccess) { | |
2588 if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) { | |
2589 goto fallback; | |
2590 } | |
2591 | |
2592 *outLen = 0; | |
2593 rv = SECFailure; | |
2594 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); | |
2595 return rv; | |
2596 } | |
2597 | |
2598 PORT_Assert(outputItem.len == (unsigned)spec->mac_size); | |
2599 *outLen = outputItem.len; | |
2600 | |
2601 return rv; | |
2602 | |
2603 fallback: | |
2604 /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the | |
2605 * length already. */ | |
2606 inputLen -= spec->mac_size; | |
2607 return ssl3_ComputeRecordMAC(spec, useServerMacKey, header, headerLen, | |
2608 input, inputLen, outbuf, outLen); | |
2609 } | |
2610 | |
2611 static PRBool | |
2612 ssl3_ClientAuthTokenPresent(sslSessionID *sid) { | |
2613 PK11SlotInfo *slot = NULL; | |
2614 PRBool isPresent = PR_TRUE; | |
2615 | |
2616 /* we only care if we are doing client auth */ | |
2617 /* If NSS_PLATFORM_CLIENT_AUTH is defined and a platformClientKey is being | |
2618 * used, u.ssl3.clAuthValid will be false and this function will always | |
2619 * return PR_TRUE. */ | |
2620 if (!sid || !sid->u.ssl3.clAuthValid) { | |
2621 return PR_TRUE; | |
2622 } | |
2623 | |
2624 /* get the slot */ | |
2625 slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID, | |
2626 sid->u.ssl3.clAuthSlotID); | |
2627 if (slot == NULL || | |
2628 !PK11_IsPresent(slot) || | |
2629 sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) || | |
2630 sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) || | |
2631 sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) || | |
2632 (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) { | |
2633 isPresent = PR_FALSE; | |
2634 } | |
2635 if (slot) { | |
2636 PK11_FreeSlot(slot); | |
2637 } | |
2638 return isPresent; | |
2639 } | |
2640 | |
2641 /* Caller must hold the spec read lock. */ | |
2642 SECStatus | |
2643 ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec, | |
2644 PRBool isServer, | |
2645 PRBool isDTLS, | |
2646 PRBool capRecordVersion, | |
2647 SSL3ContentType type, | |
2648 const SSL3Opaque * pIn, | |
2649 PRUint32 contentLen, | |
2650 sslBuffer * wrBuf) | |
2651 { | |
2652 const ssl3BulkCipherDef * cipher_def; | |
2653 SECStatus rv; | |
2654 PRUint32 macLen = 0; | |
2655 PRUint32 fragLen; | |
2656 PRUint32 p1Len, p2Len, oddLen = 0; | |
2657 PRUint16 headerLen; | |
2658 int ivLen = 0; | |
2659 int cipherBytes = 0; | |
2660 unsigned char pseudoHeader[13]; | |
2661 unsigned int pseudoHeaderLen; | |
2662 | |
2663 cipher_def = cwSpec->cipher_def; | |
2664 headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH; | |
2665 | |
2666 if (cipher_def->type == type_block && | |
2667 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { | |
2668 /* Prepend the per-record explicit IV using technique 2b from | |
2669 * RFC 4346 section 6.2.3.2: The IV is a cryptographically | |
2670 * strong random number XORed with the CBC residue from the previous | |
2671 * record. | |
2672 */ | |
2673 ivLen = cipher_def->iv_size; | |
2674 if (ivLen > wrBuf->space - headerLen) { | |
2675 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
2676 return SECFailure; | |
2677 } | |
2678 rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen); | |
2679 if (rv != SECSuccess) { | |
2680 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); | |
2681 return rv; | |
2682 } | |
2683 rv = cwSpec->encode( cwSpec->encodeContext, | |
2684 wrBuf->buf + headerLen, | |
2685 &cipherBytes, /* output and actual outLen */ | |
2686 ivLen, /* max outlen */ | |
2687 wrBuf->buf + headerLen, | |
2688 ivLen); /* input and inputLen*/ | |
2689 if (rv != SECSuccess || cipherBytes != ivLen) { | |
2690 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); | |
2691 return SECFailure; | |
2692 } | |
2693 } | |
2694 | |
2695 if (cwSpec->compressor) { | |
2696 int outlen; | |
2697 rv = cwSpec->compressor( | |
2698 cwSpec->compressContext, | |
2699 wrBuf->buf + headerLen + ivLen, &outlen, | |
2700 wrBuf->space - headerLen - ivLen, pIn, contentLen); | |
2701 if (rv != SECSuccess) | |
2702 return rv; | |
2703 pIn = wrBuf->buf + headerLen + ivLen; | |
2704 contentLen = outlen; | |
2705 } | |
2706 | |
2707 pseudoHeaderLen = ssl3_BuildRecordPseudoHeader( | |
2708 pseudoHeader, cwSpec->write_seq_num, type, | |
2709 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version, | |
2710 isDTLS, contentLen); | |
2711 PORT_Assert(pseudoHeaderLen <= sizeof(pseudoHeader)); | |
2712 if (cipher_def->type == type_aead) { | |
2713 const int nonceLen = cipher_def->explicit_nonce_size; | |
2714 const int tagLen = cipher_def->tag_size; | |
2715 | |
2716 if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) { | |
2717 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
2718 return SECFailure; | |
2719 } | |
2720 | |
2721 cipherBytes = contentLen; | |
2722 rv = cwSpec->aead( | |
2723 isServer ? &cwSpec->server : &cwSpec->client, | |
2724 PR_FALSE, /* do encrypt */ | |
2725 wrBuf->buf + headerLen, /* output */ | |
2726 &cipherBytes, /* out len */ | |
2727 wrBuf->space - headerLen, /* max out */ | |
2728 pIn, contentLen, /* input */ | |
2729 pseudoHeader, pseudoHeaderLen); | |
2730 if (rv != SECSuccess) { | |
2731 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); | |
2732 return SECFailure; | |
2733 } | |
2734 } else { | |
2735 /* | |
2736 * Add the MAC | |
2737 */ | |
2738 rv = ssl3_ComputeRecordMAC(cwSpec, isServer, | |
2739 pseudoHeader, pseudoHeaderLen, pIn, contentLen, | |
2740 wrBuf->buf + headerLen + ivLen + contentLen, &macLen); | |
2741 if (rv != SECSuccess) { | |
2742 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); | |
2743 return SECFailure; | |
2744 } | |
2745 p1Len = contentLen; | |
2746 p2Len = macLen; | |
2747 fragLen = contentLen + macLen; /* needs to be encrypted */ | |
2748 PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024); | |
2749 | |
2750 /* | |
2751 * Pad the text (if we're doing a block cipher) | |
2752 * then Encrypt it | |
2753 */ | |
2754 if (cipher_def->type == type_block) { | |
2755 unsigned char * pBuf; | |
2756 int padding_length; | |
2757 int i; | |
2758 | |
2759 oddLen = contentLen % cipher_def->block_size; | |
2760 /* Assume blockSize is a power of two */ | |
2761 padding_length = cipher_def->block_size - 1 - | |
2762 ((fragLen) & (cipher_def->block_size - 1)); | |
2763 fragLen += padding_length + 1; | |
2764 PORT_Assert((fragLen % cipher_def->block_size) == 0); | |
2765 | |
2766 /* Pad according to TLS rules (also acceptable to SSL3). */ | |
2767 pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1]; | |
2768 for (i = padding_length + 1; i > 0; --i) { | |
2769 *pBuf-- = padding_length; | |
2770 } | |
2771 /* now, if contentLen is not a multiple of block size, fix it */ | |
2772 p2Len = fragLen - p1Len; | |
2773 } | |
2774 if (p1Len < 256) { | |
2775 oddLen = p1Len; | |
2776 p1Len = 0; | |
2777 } else { | |
2778 p1Len -= oddLen; | |
2779 } | |
2780 if (oddLen) { | |
2781 p2Len += oddLen; | |
2782 PORT_Assert( (cipher_def->block_size < 2) || \ | |
2783 (p2Len % cipher_def->block_size) == 0); | |
2784 memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, | |
2785 oddLen); | |
2786 } | |
2787 if (p1Len > 0) { | |
2788 int cipherBytesPart1 = -1; | |
2789 rv = cwSpec->encode( cwSpec->encodeContext, | |
2790 wrBuf->buf + headerLen + ivLen, /* output */ | |
2791 &cipherBytesPart1, /* actual outlen */ | |
2792 p1Len, /* max outlen */ | |
2793 pIn, p1Len); /* input, and inputlen */ | |
2794 PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len); | |
2795 if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) { | |
2796 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); | |
2797 return SECFailure; | |
2798 } | |
2799 cipherBytes += cipherBytesPart1; | |
2800 } | |
2801 if (p2Len > 0) { | |
2802 int cipherBytesPart2 = -1; | |
2803 rv = cwSpec->encode( cwSpec->encodeContext, | |
2804 wrBuf->buf + headerLen + ivLen + p1Len, | |
2805 &cipherBytesPart2, /* output and actual outLen */ | |
2806 p2Len, /* max outlen */ | |
2807 wrBuf->buf + headerLen + ivLen + p1Len, | |
2808 p2Len); /* input and inputLen*/ | |
2809 PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len); | |
2810 if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) { | |
2811 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); | |
2812 return SECFailure; | |
2813 } | |
2814 cipherBytes += cipherBytesPart2; | |
2815 } | |
2816 } | |
2817 | |
2818 PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024); | |
2819 | |
2820 wrBuf->len = cipherBytes + headerLen; | |
2821 wrBuf->buf[0] = type; | |
2822 if (isDTLS) { | |
2823 SSL3ProtocolVersion version; | |
2824 | |
2825 version = dtls_TLSVersionToDTLSVersion(cwSpec->version); | |
2826 wrBuf->buf[1] = MSB(version); | |
2827 wrBuf->buf[2] = LSB(version); | |
2828 wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24); | |
2829 wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16); | |
2830 wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >> 8); | |
2831 wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >> 0); | |
2832 wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low >> 24); | |
2833 wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low >> 16); | |
2834 wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low >> 8); | |
2835 wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >> 0); | |
2836 wrBuf->buf[11] = MSB(cipherBytes); | |
2837 wrBuf->buf[12] = LSB(cipherBytes); | |
2838 } else { | |
2839 SSL3ProtocolVersion version = cwSpec->version; | |
2840 | |
2841 if (capRecordVersion) { | |
2842 version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version); | |
2843 } | |
2844 wrBuf->buf[1] = MSB(version); | |
2845 wrBuf->buf[2] = LSB(version); | |
2846 wrBuf->buf[3] = MSB(cipherBytes); | |
2847 wrBuf->buf[4] = LSB(cipherBytes); | |
2848 } | |
2849 | |
2850 ssl3_BumpSequenceNumber(&cwSpec->write_seq_num); | |
2851 | |
2852 return SECSuccess; | |
2853 } | |
2854 | |
2855 /* Process the plain text before sending it. | |
2856 * Returns the number of bytes of plaintext that were successfully sent | |
2857 * plus the number of bytes of plaintext that were copied into the | |
2858 * output (write) buffer. | |
2859 * Returns SECFailure on a hard IO error, memory error, or crypto error. | |
2860 * Does NOT return SECWouldBlock. | |
2861 * | |
2862 * Notes on the use of the private ssl flags: | |
2863 * (no private SSL flags) | |
2864 * Attempt to make and send SSL records for all plaintext | |
2865 * If non-blocking and a send gets WOULD_BLOCK, | |
2866 * or if the pending (ciphertext) buffer is not empty, | |
2867 * then buffer remaining bytes of ciphertext into pending buf, | |
2868 * and continue to do that for all succssive records until all | |
2869 * bytes are used. | |
2870 * ssl_SEND_FLAG_FORCE_INTO_BUFFER | |
2871 * As above, except this suppresses all write attempts, and forces | |
2872 * all ciphertext into the pending ciphertext buffer. | |
2873 * ssl_SEND_FLAG_USE_EPOCH (for DTLS) | |
2874 * Forces the use of the provided epoch | |
2875 * ssl_SEND_FLAG_CAP_RECORD_VERSION | |
2876 * Caps the record layer version number of TLS ClientHello to { 3, 1 } | |
2877 * (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore | |
2878 * ClientHello.client_version and use the record layer version number | |
2879 * (TLSPlaintext.version) instead when negotiating protocol versions. In | |
2880 * addition, if the record layer version number of ClientHello is { 3, 2 } | |
2881 * (TLS 1.1) or higher, these servers reset the TCP connections. Lastly, | |
2882 * some F5 BIG-IP servers hang if a record containing a ClientHello has a | |
2883 * version greater than { 3, 1 } and a length greater than 255. Set this | |
2884 * flag to work around such servers. | |
2885 */ | |
2886 PRInt32 | |
2887 ssl3_SendRecord( sslSocket * ss, | |
2888 DTLSEpoch epoch, /* DTLS only */ | |
2889 SSL3ContentType type, | |
2890 const SSL3Opaque * pIn, /* input buffer */ | |
2891 PRInt32 nIn, /* bytes of input */ | |
2892 PRInt32 flags) | |
2893 { | |
2894 sslBuffer * wrBuf = &ss->sec.writeBuf; | |
2895 SECStatus rv; | |
2896 PRInt32 totalSent = 0; | |
2897 PRBool capRecordVersion; | |
2898 | |
2899 SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d", | |
2900 SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type), | |
2901 nIn)); | |
2902 PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn)); | |
2903 | |
2904 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); | |
2905 | |
2906 capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0); | |
2907 | |
2908 if (capRecordVersion) { | |
2909 /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the | |
2910 * TLS initial ClientHello. */ | |
2911 PORT_Assert(!IS_DTLS(ss)); | |
2912 PORT_Assert(!ss->firstHsDone); | |
2913 PORT_Assert(type == content_handshake); | |
2914 PORT_Assert(ss->ssl3.hs.ws == wait_server_hello); | |
2915 } | |
2916 | |
2917 if (ss->ssl3.initialized == PR_FALSE) { | |
2918 /* This can happen on a server if the very first incoming record | |
2919 ** looks like a defective ssl3 record (e.g. too long), and we're | |
2920 ** trying to send an alert. | |
2921 */ | |
2922 PR_ASSERT(type == content_alert); | |
2923 rv = ssl3_InitState(ss); | |
2924 if (rv != SECSuccess) { | |
2925 return SECFailure; /* ssl3_InitState has set the error code. */ | |
2926 } | |
2927 } | |
2928 | |
2929 /* check for Token Presence */ | |
2930 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { | |
2931 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); | |
2932 return SECFailure; | |
2933 } | |
2934 | |
2935 while (nIn > 0) { | |
2936 PRUint32 contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH); | |
2937 unsigned int spaceNeeded; | |
2938 unsigned int numRecords; | |
2939 | |
2940 ssl_GetSpecReadLock(ss); /********************************/ | |
2941 | |
2942 if (nIn > 1 && ss->opt.cbcRandomIV && | |
2943 ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 && | |
2944 type == content_application_data && | |
2945 ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) { | |
2946 /* We will split the first byte of the record into its own record, | |
2947 * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h | |
2948 */ | |
2949 numRecords = 2; | |
2950 } else { | |
2951 numRecords = 1; | |
2952 } | |
2953 | |
2954 spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE); | |
2955 if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 && | |
2956 ss->ssl3.cwSpec->cipher_def->type == type_block) { | |
2957 spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size; | |
2958 } | |
2959 if (spaceNeeded > wrBuf->space) { | |
2960 rv = sslBuffer_Grow(wrBuf, spaceNeeded); | |
2961 if (rv != SECSuccess) { | |
2962 SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes", | |
2963 SSL_GETPID(), ss->fd, spaceNeeded)); | |
2964 goto spec_locked_loser; /* sslBuffer_Grow set error code. */ | |
2965 } | |
2966 } | |
2967 | |
2968 if (numRecords == 2) { | |
2969 sslBuffer secondRecord; | |
2970 | |
2971 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, | |
2972 ss->sec.isServer, IS_DTLS(ss), | |
2973 capRecordVersion, type, pIn, | |
2974 1, wrBuf); | |
2975 if (rv != SECSuccess) | |
2976 goto spec_locked_loser; | |
2977 | |
2978 PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:", | |
2979 wrBuf->buf, wrBuf->len)); | |
2980 | |
2981 secondRecord.buf = wrBuf->buf + wrBuf->len; | |
2982 secondRecord.len = 0; | |
2983 secondRecord.space = wrBuf->space - wrBuf->len; | |
2984 | |
2985 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, | |
2986 ss->sec.isServer, IS_DTLS(ss), | |
2987 capRecordVersion, type, | |
2988 pIn + 1, contentLen - 1, | |
2989 &secondRecord); | |
2990 if (rv == SECSuccess) { | |
2991 PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:", | |
2992 secondRecord.buf, secondRecord.len)); | |
2993 wrBuf->len += secondRecord.len; | |
2994 } | |
2995 } else { | |
2996 if (!IS_DTLS(ss)) { | |
2997 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, | |
2998 ss->sec.isServer, | |
2999 IS_DTLS(ss), | |
3000 capRecordVersion, | |
3001 type, pIn, | |
3002 contentLen, wrBuf); | |
3003 } else { | |
3004 rv = dtls_CompressMACEncryptRecord(ss, epoch, | |
3005 !!(flags & ssl_SEND_FLAG_USE_
EPOCH), | |
3006 type, pIn, | |
3007 contentLen, wrBuf); | |
3008 } | |
3009 | |
3010 if (rv == SECSuccess) { | |
3011 PRINT_BUF(50, (ss, "send (encrypted) record data:", | |
3012 wrBuf->buf, wrBuf->len)); | |
3013 } | |
3014 } | |
3015 | |
3016 spec_locked_loser: | |
3017 ssl_ReleaseSpecReadLock(ss); /************************************/ | |
3018 | |
3019 if (rv != SECSuccess) | |
3020 return SECFailure; | |
3021 | |
3022 pIn += contentLen; | |
3023 nIn -= contentLen; | |
3024 PORT_Assert( nIn >= 0 ); | |
3025 | |
3026 /* If there's still some previously saved ciphertext, | |
3027 * or the caller doesn't want us to send the data yet, | |
3028 * then add all our new ciphertext to the amount previously saved. | |
3029 */ | |
3030 if ((ss->pendingBuf.len > 0) || | |
3031 (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { | |
3032 | |
3033 rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len); | |
3034 if (rv != SECSuccess) { | |
3035 /* presumably a memory error, SEC_ERROR_NO_MEMORY */ | |
3036 return SECFailure; | |
3037 } | |
3038 wrBuf->len = 0; /* All cipher text is saved away. */ | |
3039 | |
3040 if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { | |
3041 PRInt32 sent; | |
3042 ss->handshakeBegun = 1; | |
3043 sent = ssl_SendSavedWriteData(ss); | |
3044 if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) { | |
3045 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); | |
3046 return SECFailure; | |
3047 } | |
3048 if (ss->pendingBuf.len) { | |
3049 flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER; | |
3050 } | |
3051 } | |
3052 } else if (wrBuf->len > 0) { | |
3053 PRInt32 sent; | |
3054 ss->handshakeBegun = 1; | |
3055 sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len, | |
3056 flags & ~ssl_SEND_FLAG_MASK); | |
3057 if (sent < 0) { | |
3058 if (PR_GetError() != PR_WOULD_BLOCK_ERROR) { | |
3059 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); | |
3060 return SECFailure; | |
3061 } | |
3062 /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */ | |
3063 sent = 0; | |
3064 } | |
3065 wrBuf->len -= sent; | |
3066 if (wrBuf->len) { | |
3067 if (IS_DTLS(ss)) { | |
3068 /* DTLS just says no in this case. No buffering */ | |
3069 PR_SetError(PR_WOULD_BLOCK_ERROR, 0); | |
3070 return SECFailure; | |
3071 } | |
3072 /* now take all the remaining unsent new ciphertext and | |
3073 * append it to the buffer of previously unsent ciphertext. | |
3074 */ | |
3075 rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len); | |
3076 if (rv != SECSuccess) { | |
3077 /* presumably a memory error, SEC_ERROR_NO_MEMORY */ | |
3078 return SECFailure; | |
3079 } | |
3080 } | |
3081 } | |
3082 totalSent += contentLen; | |
3083 } | |
3084 return totalSent; | |
3085 } | |
3086 | |
3087 #define SSL3_PENDING_HIGH_WATER 1024 | |
3088 | |
3089 /* Attempt to send the content of "in" in an SSL application_data record. | |
3090 * Returns "len" or SECFailure, never SECWouldBlock, nor SECSuccess. | |
3091 */ | |
3092 int | |
3093 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in, | |
3094 PRInt32 len, PRInt32 flags) | |
3095 { | |
3096 PRInt32 totalSent = 0; | |
3097 PRInt32 discarded = 0; | |
3098 | |
3099 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); | |
3100 /* These flags for internal use only */ | |
3101 PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH | | |
3102 ssl_SEND_FLAG_NO_RETRANSMIT))); | |
3103 if (len < 0 || !in) { | |
3104 PORT_SetError(PR_INVALID_ARGUMENT_ERROR); | |
3105 return SECFailure; | |
3106 } | |
3107 | |
3108 if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER && | |
3109 !ssl_SocketIsBlocking(ss)) { | |
3110 PORT_Assert(!ssl_SocketIsBlocking(ss)); | |
3111 PORT_SetError(PR_WOULD_BLOCK_ERROR); | |
3112 return SECFailure; | |
3113 } | |
3114 | |
3115 if (ss->appDataBuffered && len) { | |
3116 PORT_Assert (in[0] == (unsigned char)(ss->appDataBuffered)); | |
3117 if (in[0] != (unsigned char)(ss->appDataBuffered)) { | |
3118 PORT_SetError(PR_INVALID_ARGUMENT_ERROR); | |
3119 return SECFailure; | |
3120 } | |
3121 in++; | |
3122 len--; | |
3123 discarded = 1; | |
3124 } | |
3125 while (len > totalSent) { | |
3126 PRInt32 sent, toSend; | |
3127 | |
3128 if (totalSent > 0) { | |
3129 /* | |
3130 * The thread yield is intended to give the reader thread a | |
3131 * chance to get some cycles while the writer thread is in | |
3132 * the middle of a large application data write. (See | |
3133 * Bugzilla bug 127740, comment #1.) | |
3134 */ | |
3135 ssl_ReleaseXmitBufLock(ss); | |
3136 PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */ | |
3137 ssl_GetXmitBufLock(ss); | |
3138 } | |
3139 toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH); | |
3140 /* | |
3141 * Note that the 0 epoch is OK because flags will never require | |
3142 * its use, as guaranteed by the PORT_Assert above. | |
3143 */ | |
3144 sent = ssl3_SendRecord(ss, 0, content_application_data, | |
3145 in + totalSent, toSend, flags); | |
3146 if (sent < 0) { | |
3147 if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) { | |
3148 PORT_Assert(ss->lastWriteBlocked); | |
3149 break; | |
3150 } | |
3151 return SECFailure; /* error code set by ssl3_SendRecord */ | |
3152 } | |
3153 totalSent += sent; | |
3154 if (ss->pendingBuf.len) { | |
3155 /* must be a non-blocking socket */ | |
3156 PORT_Assert(!ssl_SocketIsBlocking(ss)); | |
3157 PORT_Assert(ss->lastWriteBlocked); | |
3158 break; | |
3159 } | |
3160 } | |
3161 if (ss->pendingBuf.len) { | |
3162 /* Must be non-blocking. */ | |
3163 PORT_Assert(!ssl_SocketIsBlocking(ss)); | |
3164 if (totalSent > 0) { | |
3165 ss->appDataBuffered = 0x100 | in[totalSent - 1]; | |
3166 } | |
3167 | |
3168 totalSent = totalSent + discarded - 1; | |
3169 if (totalSent <= 0) { | |
3170 PORT_SetError(PR_WOULD_BLOCK_ERROR); | |
3171 totalSent = SECFailure; | |
3172 } | |
3173 return totalSent; | |
3174 } | |
3175 ss->appDataBuffered = 0; | |
3176 return totalSent + discarded; | |
3177 } | |
3178 | |
3179 /* Attempt to send buffered handshake messages. | |
3180 * This function returns SECSuccess or SECFailure, never SECWouldBlock. | |
3181 * Always set sendBuf.len to 0, even when returning SECFailure. | |
3182 * | |
3183 * Depending on whether we are doing DTLS or not, this either calls | |
3184 * | |
3185 * - ssl3_FlushHandshakeMessages if non-DTLS | |
3186 * - dtls_FlushHandshakeMessages if DTLS | |
3187 * | |
3188 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(), | |
3189 * ssl3_AppendHandshake(), ssl3_SendClientHello(), | |
3190 * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(), | |
3191 * ssl3_SendFinished(), | |
3192 */ | |
3193 static SECStatus | |
3194 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags) | |
3195 { | |
3196 if (IS_DTLS(ss)) { | |
3197 return dtls_FlushHandshakeMessages(ss, flags); | |
3198 } else { | |
3199 return ssl3_FlushHandshakeMessages(ss, flags); | |
3200 } | |
3201 } | |
3202 | |
3203 /* Attempt to send the content of sendBuf buffer in an SSL handshake record. | |
3204 * This function returns SECSuccess or SECFailure, never SECWouldBlock. | |
3205 * Always set sendBuf.len to 0, even when returning SECFailure. | |
3206 * | |
3207 * Called from ssl3_FlushHandshake | |
3208 */ | |
3209 static SECStatus | |
3210 ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags) | |
3211 { | |
3212 static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER | | |
3213 ssl_SEND_FLAG_CAP_RECORD_VERSION; | |
3214 PRInt32 rv = SECSuccess; | |
3215 | |
3216 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
3217 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); | |
3218 | |
3219 if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len) | |
3220 return rv; | |
3221 | |
3222 /* only these flags are allowed */ | |
3223 PORT_Assert(!(flags & ~allowedFlags)); | |
3224 if ((flags & ~allowedFlags) != 0) { | |
3225 PORT_SetError(SEC_ERROR_INVALID_ARGS); | |
3226 rv = SECFailure; | |
3227 } else { | |
3228 rv = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf, | |
3229 ss->sec.ci.sendBuf.len, flags); | |
3230 } | |
3231 if (rv < 0) { | |
3232 int err = PORT_GetError(); | |
3233 PORT_Assert(err != PR_WOULD_BLOCK_ERROR); | |
3234 if (err == PR_WOULD_BLOCK_ERROR) { | |
3235 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
3236 } | |
3237 } else if (rv < ss->sec.ci.sendBuf.len) { | |
3238 /* short write should never happen */ | |
3239 PORT_Assert(rv >= ss->sec.ci.sendBuf.len); | |
3240 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
3241 rv = SECFailure; | |
3242 } else { | |
3243 rv = SECSuccess; | |
3244 } | |
3245 | |
3246 /* Whether we succeeded or failed, toss the old handshake data. */ | |
3247 ss->sec.ci.sendBuf.len = 0; | |
3248 return rv; | |
3249 } | |
3250 | |
3251 /* | |
3252 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when | |
3253 * the remote client sends a negative response to our certificate request. | |
3254 * Returns SECFailure if the application has required client auth. | |
3255 * SECSuccess otherwise. | |
3256 */ | |
3257 static SECStatus | |
3258 ssl3_HandleNoCertificate(sslSocket *ss) | |
3259 { | |
3260 if (ss->sec.peerCert != NULL) { | |
3261 if (ss->sec.peerKey != NULL) { | |
3262 SECKEY_DestroyPublicKey(ss->sec.peerKey); | |
3263 ss->sec.peerKey = NULL; | |
3264 } | |
3265 CERT_DestroyCertificate(ss->sec.peerCert); | |
3266 ss->sec.peerCert = NULL; | |
3267 } | |
3268 ssl3_CleanupPeerCerts(ss); | |
3269 | |
3270 /* If the server has required client-auth blindly but doesn't | |
3271 * actually look at the certificate it won't know that no | |
3272 * certificate was presented so we shutdown the socket to ensure | |
3273 * an error. We only do this if we haven't already completed the | |
3274 * first handshake because if we're redoing the handshake we | |
3275 * know the server is paying attention to the certificate. | |
3276 */ | |
3277 if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || | |
3278 (!ss->firstHsDone && | |
3279 (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) { | |
3280 PRFileDesc * lower; | |
3281 | |
3282 if (ss->sec.uncache) | |
3283 ss->sec.uncache(ss->sec.ci.sid); | |
3284 SSL3_SendAlert(ss, alert_fatal, bad_certificate); | |
3285 | |
3286 lower = ss->fd->lower; | |
3287 #ifdef _WIN32 | |
3288 lower->methods->shutdown(lower, PR_SHUTDOWN_SEND); | |
3289 #else | |
3290 lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH); | |
3291 #endif | |
3292 PORT_SetError(SSL_ERROR_NO_CERTIFICATE); | |
3293 return SECFailure; | |
3294 } | |
3295 return SECSuccess; | |
3296 } | |
3297 | |
3298 /************************************************************************ | |
3299 * Alerts | |
3300 */ | |
3301 | |
3302 /* | |
3303 ** Acquires both handshake and XmitBuf locks. | |
3304 ** Called from: ssl3_IllegalParameter <- | |
3305 ** ssl3_HandshakeFailure <- | |
3306 ** ssl3_HandleAlert <- ssl3_HandleRecord. | |
3307 ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord | |
3308 ** ssl3_ConsumeHandshakeVariable <- | |
3309 ** ssl3_HandleHelloRequest <- | |
3310 ** ssl3_HandleServerHello <- | |
3311 ** ssl3_HandleServerKeyExchange <- | |
3312 ** ssl3_HandleCertificateRequest <- | |
3313 ** ssl3_HandleServerHelloDone <- | |
3314 ** ssl3_HandleClientHello <- | |
3315 ** ssl3_HandleV2ClientHello <- | |
3316 ** ssl3_HandleCertificateVerify <- | |
3317 ** ssl3_HandleClientKeyExchange <- | |
3318 ** ssl3_HandleCertificate <- | |
3319 ** ssl3_HandleFinished <- | |
3320 ** ssl3_HandleHandshakeMessage <- | |
3321 ** ssl3_HandleRecord <- | |
3322 ** | |
3323 */ | |
3324 SECStatus | |
3325 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc) | |
3326 { | |
3327 PRUint8 bytes[2]; | |
3328 SECStatus rv; | |
3329 | |
3330 SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d", | |
3331 SSL_GETPID(), ss->fd, level, desc)); | |
3332 | |
3333 bytes[0] = level; | |
3334 bytes[1] = desc; | |
3335 | |
3336 ssl_GetSSL3HandshakeLock(ss); | |
3337 if (level == alert_fatal) { | |
3338 if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) { | |
3339 ss->sec.uncache(ss->sec.ci.sid); | |
3340 } | |
3341 } | |
3342 ssl_GetXmitBufLock(ss); | |
3343 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); | |
3344 if (rv == SECSuccess) { | |
3345 PRInt32 sent; | |
3346 sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2, | |
3347 desc == no_certificate | |
3348 ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0); | |
3349 rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; | |
3350 } | |
3351 ssl_ReleaseXmitBufLock(ss); | |
3352 ssl_ReleaseSSL3HandshakeLock(ss); | |
3353 return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */ | |
3354 } | |
3355 | |
3356 /* | |
3357 * Send illegal_parameter alert. Set generic error number. | |
3358 */ | |
3359 static SECStatus | |
3360 ssl3_IllegalParameter(sslSocket *ss) | |
3361 { | |
3362 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); | |
3363 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT | |
3364 : SSL_ERROR_BAD_SERVER ); | |
3365 return SECFailure; | |
3366 } | |
3367 | |
3368 /* | |
3369 * Send handshake_Failure alert. Set generic error number. | |
3370 */ | |
3371 static SECStatus | |
3372 ssl3_HandshakeFailure(sslSocket *ss) | |
3373 { | |
3374 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure); | |
3375 PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT | |
3376 : SSL_ERROR_BAD_SERVER ); | |
3377 return SECFailure; | |
3378 } | |
3379 | |
3380 static void | |
3381 ssl3_SendAlertForCertError(sslSocket * ss, PRErrorCode errCode) | |
3382 { | |
3383 SSL3AlertDescription desc = bad_certificate; | |
3384 PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS; | |
3385 | |
3386 switch (errCode) { | |
3387 case SEC_ERROR_LIBRARY_FAILURE: desc = unsupported_certificate; break; | |
3388 case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired; break; | |
3389 case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked; break; | |
3390 case SEC_ERROR_INADEQUATE_KEY_USAGE: | |
3391 case SEC_ERROR_INADEQUATE_CERT_TYPE: | |
3392 desc = certificate_unknown; break; | |
3393 case SEC_ERROR_UNTRUSTED_CERT: | |
3394 desc = isTLS ? access_denied : certificate_unknown; break; | |
3395 case SEC_ERROR_UNKNOWN_ISSUER: | |
3396 case SEC_ERROR_UNTRUSTED_ISSUER: | |
3397 desc = isTLS ? unknown_ca : certificate_unknown; break; | |
3398 case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE: | |
3399 desc = isTLS ? unknown_ca : certificate_expired; break; | |
3400 | |
3401 case SEC_ERROR_CERT_NOT_IN_NAME_SPACE: | |
3402 case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID: | |
3403 case SEC_ERROR_CA_CERT_INVALID: | |
3404 case SEC_ERROR_BAD_SIGNATURE: | |
3405 default: desc = bad_certificate; break; | |
3406 } | |
3407 SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d", | |
3408 SSL_GETPID(), ss->fd, errCode)); | |
3409 | |
3410 (void) SSL3_SendAlert(ss, alert_fatal, desc); | |
3411 } | |
3412 | |
3413 | |
3414 /* | |
3415 * Send decode_error alert. Set generic error number. | |
3416 */ | |
3417 SECStatus | |
3418 ssl3_DecodeError(sslSocket *ss) | |
3419 { | |
3420 (void)SSL3_SendAlert(ss, alert_fatal, | |
3421 ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error | |
3422 : illegal_parameter); | |
3423 PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT | |
3424 : SSL_ERROR_BAD_SERVER ); | |
3425 return SECFailure; | |
3426 } | |
3427 | |
3428 /* Called from ssl3_HandleRecord. | |
3429 ** Caller must hold both RecvBuf and Handshake locks. | |
3430 */ | |
3431 static SECStatus | |
3432 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf) | |
3433 { | |
3434 SSL3AlertLevel level; | |
3435 SSL3AlertDescription desc; | |
3436 int error; | |
3437 | |
3438 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
3439 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
3440 | |
3441 SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd)); | |
3442 | |
3443 if (buf->len != 2) { | |
3444 (void)ssl3_DecodeError(ss); | |
3445 PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT); | |
3446 return SECFailure; | |
3447 } | |
3448 level = (SSL3AlertLevel)buf->buf[0]; | |
3449 desc = (SSL3AlertDescription)buf->buf[1]; | |
3450 buf->len = 0; | |
3451 SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d", | |
3452 SSL_GETPID(), ss->fd, level, desc)); | |
3453 | |
3454 switch (desc) { | |
3455 case close_notify: ss->recvdCloseNotify = 1; | |
3456 error = SSL_ERROR_CLOSE_NOTIFY_ALERT; break; | |
3457 case unexpected_message: error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT; | |
3458 break; | |
3459 case bad_record_mac: error = SSL_ERROR_BAD_MAC_ALERT; break; | |
3460 case decryption_failed_RESERVED: | |
3461 error = SSL_ERROR_DECRYPTION_FAILED_ALERT; | |
3462 break; | |
3463 case record_overflow: error = SSL_ERROR_RECORD_OVERFLOW_ALERT; break; | |
3464 case decompression_failure: error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT; | |
3465 break; | |
3466 case handshake_failure: error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT; | |
3467 break; | |
3468 case no_certificate: error = SSL_ERROR_NO_CERTIFICATE; break; | |
3469 case bad_certificate: error = SSL_ERROR_BAD_CERT_ALERT; break; | |
3470 case unsupported_certificate:error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;break; | |
3471 case certificate_revoked: error = SSL_ERROR_REVOKED_CERT_ALERT; break; | |
3472 case certificate_expired: error = SSL_ERROR_EXPIRED_CERT_ALERT; break; | |
3473 case certificate_unknown: error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT; | |
3474 break; | |
3475 case illegal_parameter: error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;break; | |
3476 case inappropriate_fallback: | |
3477 error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; | |
3478 break; | |
3479 | |
3480 /* All alerts below are TLS only. */ | |
3481 case unknown_ca: error = SSL_ERROR_UNKNOWN_CA_ALERT; break; | |
3482 case access_denied: error = SSL_ERROR_ACCESS_DENIED_ALERT; break; | |
3483 case decode_error: error = SSL_ERROR_DECODE_ERROR_ALERT; break; | |
3484 case decrypt_error: error = SSL_ERROR_DECRYPT_ERROR_ALERT; break; | |
3485 case export_restriction: error = SSL_ERROR_EXPORT_RESTRICTION_ALERT; | |
3486 break; | |
3487 case protocol_version: error = SSL_ERROR_PROTOCOL_VERSION_ALERT; break; | |
3488 case insufficient_security: error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT; | |
3489 break; | |
3490 case internal_error: error = SSL_ERROR_INTERNAL_ERROR_ALERT; break; | |
3491 case user_canceled: error = SSL_ERROR_USER_CANCELED_ALERT; break; | |
3492 case no_renegotiation: error = SSL_ERROR_NO_RENEGOTIATION_ALERT; break; | |
3493 | |
3494 /* Alerts for TLS client hello extensions */ | |
3495 case unsupported_extension: | |
3496 error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT; break; | |
3497 case certificate_unobtainable: | |
3498 error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; break; | |
3499 case unrecognized_name: | |
3500 error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; break; | |
3501 case bad_certificate_status_response: | |
3502 error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; break; | |
3503 case bad_certificate_hash_value: | |
3504 error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT; break; | |
3505 default: error = SSL_ERROR_RX_UNKNOWN_ALERT; break; | |
3506 } | |
3507 if (level == alert_fatal) { | |
3508 if (!ss->opt.noCache) { | |
3509 if (ss->sec.uncache) | |
3510 ss->sec.uncache(ss->sec.ci.sid); | |
3511 } | |
3512 if ((ss->ssl3.hs.ws == wait_server_hello) && | |
3513 (desc == handshake_failure)) { | |
3514 /* XXX This is a hack. We're assuming that any handshake failure | |
3515 * XXX on the client hello is a failure to match ciphers. | |
3516 */ | |
3517 error = SSL_ERROR_NO_CYPHER_OVERLAP; | |
3518 } | |
3519 PORT_SetError(error); | |
3520 return SECFailure; | |
3521 } | |
3522 if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) { | |
3523 /* I'm a server. I've requested a client cert. He hasn't got one. */ | |
3524 SECStatus rv; | |
3525 | |
3526 PORT_Assert(ss->sec.isServer); | |
3527 ss->ssl3.hs.ws = wait_client_key; | |
3528 rv = ssl3_HandleNoCertificate(ss); | |
3529 return rv; | |
3530 } | |
3531 return SECSuccess; | |
3532 } | |
3533 | |
3534 /* | |
3535 * Change Cipher Specs | |
3536 * Called from ssl3_HandleServerHelloDone, | |
3537 * ssl3_HandleClientHello, | |
3538 * and ssl3_HandleFinished | |
3539 * | |
3540 * Acquires and releases spec write lock, to protect switching the current | |
3541 * and pending write spec pointers. | |
3542 */ | |
3543 | |
3544 static SECStatus | |
3545 ssl3_SendChangeCipherSpecs(sslSocket *ss) | |
3546 { | |
3547 PRUint8 change = change_cipher_spec_choice; | |
3548 ssl3CipherSpec * pwSpec; | |
3549 SECStatus rv; | |
3550 PRInt32 sent; | |
3551 | |
3552 SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record", | |
3553 SSL_GETPID(), ss->fd)); | |
3554 | |
3555 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); | |
3556 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
3557 | |
3558 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); | |
3559 if (rv != SECSuccess) { | |
3560 return rv; /* error code set by ssl3_FlushHandshake */ | |
3561 } | |
3562 if (!IS_DTLS(ss)) { | |
3563 sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1, | |
3564 ssl_SEND_FLAG_FORCE_INTO_BUFFER); | |
3565 if (sent < 0) { | |
3566 return (SECStatus)sent; /* error code set by ssl3_SendRecord */ | |
3567 } | |
3568 } else { | |
3569 rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1); | |
3570 if (rv != SECSuccess) { | |
3571 return rv; | |
3572 } | |
3573 } | |
3574 | |
3575 /* swap the pending and current write specs. */ | |
3576 ssl_GetSpecWriteLock(ss); /**************************************/ | |
3577 pwSpec = ss->ssl3.pwSpec; | |
3578 | |
3579 ss->ssl3.pwSpec = ss->ssl3.cwSpec; | |
3580 ss->ssl3.cwSpec = pwSpec; | |
3581 | |
3582 SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending", | |
3583 SSL_GETPID(), ss->fd )); | |
3584 | |
3585 /* We need to free up the contexts, keys and certs ! */ | |
3586 /* If we are really through with the old cipher spec | |
3587 * (Both the read and write sides have changed) destroy it. | |
3588 */ | |
3589 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { | |
3590 if (!IS_DTLS(ss)) { | |
3591 ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE/*freeSrvName*/); | |
3592 } else { | |
3593 /* With DTLS, we need to set a holddown timer in case the final | |
3594 * message got lost */ | |
3595 ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS; | |
3596 dtls_StartTimer(ss, dtls_FinishedTimerCb); | |
3597 } | |
3598 } | |
3599 ssl_ReleaseSpecWriteLock(ss); /**************************************/ | |
3600 | |
3601 return SECSuccess; | |
3602 } | |
3603 | |
3604 /* Called from ssl3_HandleRecord. | |
3605 ** Caller must hold both RecvBuf and Handshake locks. | |
3606 * | |
3607 * Acquires and releases spec write lock, to protect switching the current | |
3608 * and pending write spec pointers. | |
3609 */ | |
3610 static SECStatus | |
3611 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf) | |
3612 { | |
3613 ssl3CipherSpec * prSpec; | |
3614 SSL3WaitState ws = ss->ssl3.hs.ws; | |
3615 SSL3ChangeCipherSpecChoice change; | |
3616 | |
3617 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
3618 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
3619 | |
3620 SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record", | |
3621 SSL_GETPID(), ss->fd)); | |
3622 | |
3623 if (ws != wait_change_cipher) { | |
3624 if (IS_DTLS(ss)) { | |
3625 /* Ignore this because it's out of order. */ | |
3626 SSL_TRC(3, ("%d: SSL3[%d]: discard out of order " | |
3627 "DTLS change_cipher_spec", | |
3628 SSL_GETPID(), ss->fd)); | |
3629 buf->len = 0; | |
3630 return SECSuccess; | |
3631 } | |
3632 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
3633 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER); | |
3634 return SECFailure; | |
3635 } | |
3636 | |
3637 if(buf->len != 1) { | |
3638 (void)ssl3_DecodeError(ss); | |
3639 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); | |
3640 return SECFailure; | |
3641 } | |
3642 change = (SSL3ChangeCipherSpecChoice)buf->buf[0]; | |
3643 if (change != change_cipher_spec_choice) { | |
3644 /* illegal_parameter is correct here for both SSL3 and TLS. */ | |
3645 (void)ssl3_IllegalParameter(ss); | |
3646 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); | |
3647 return SECFailure; | |
3648 } | |
3649 buf->len = 0; | |
3650 | |
3651 /* Swap the pending and current read specs. */ | |
3652 ssl_GetSpecWriteLock(ss); /*************************************/ | |
3653 prSpec = ss->ssl3.prSpec; | |
3654 | |
3655 ss->ssl3.prSpec = ss->ssl3.crSpec; | |
3656 ss->ssl3.crSpec = prSpec; | |
3657 ss->ssl3.hs.ws = wait_finished; | |
3658 | |
3659 SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending", | |
3660 SSL_GETPID(), ss->fd )); | |
3661 | |
3662 /* If we are really through with the old cipher prSpec | |
3663 * (Both the read and write sides have changed) destroy it. | |
3664 */ | |
3665 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { | |
3666 ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/); | |
3667 } | |
3668 ssl_ReleaseSpecWriteLock(ss); /*************************************/ | |
3669 return SECSuccess; | |
3670 } | |
3671 | |
3672 /* This method uses PKCS11 to derive the MS from the PMS, where PMS | |
3673 ** is a PKCS11 symkey. This is used in all cases except the | |
3674 ** "triple bypass" with RSA key exchange. | |
3675 ** Called from ssl3_InitPendingCipherSpec. prSpec is pwSpec. | |
3676 */ | |
3677 static SECStatus | |
3678 ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms) | |
3679 { | |
3680 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; | |
3681 const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def; | |
3682 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; | |
3683 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; | |
3684 PRBool isTLS = (PRBool)(kea_def->tls_keygen || | |
3685 (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); | |
3686 PRBool isTLS12= | |
3687 (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
3688 /* | |
3689 * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH | |
3690 * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size | |
3691 * data into a 48-byte value. | |
3692 */ | |
3693 PRBool isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) || | |
3694 (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh)); | |
3695 SECStatus rv = SECFailure; | |
3696 CK_MECHANISM_TYPE master_derive; | |
3697 CK_MECHANISM_TYPE key_derive; | |
3698 SECItem params; | |
3699 CK_FLAGS keyFlags; | |
3700 CK_VERSION pms_version; | |
3701 CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params; | |
3702 | |
3703 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
3704 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); | |
3705 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
3706 if (isTLS12) { | |
3707 if(isDH) master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256; | |
3708 else master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256; | |
3709 key_derive = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256; | |
3710 keyFlags = CKF_SIGN | CKF_VERIFY; | |
3711 } else if (isTLS) { | |
3712 if(isDH) master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH; | |
3713 else master_derive = CKM_TLS_MASTER_KEY_DERIVE; | |
3714 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; | |
3715 keyFlags = CKF_SIGN | CKF_VERIFY; | |
3716 } else { | |
3717 if (isDH) master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH; | |
3718 else master_derive = CKM_SSL3_MASTER_KEY_DERIVE; | |
3719 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; | |
3720 keyFlags = 0; | |
3721 } | |
3722 | |
3723 if (pms || !pwSpec->master_secret) { | |
3724 if (isDH) { | |
3725 master_params.pVersion = NULL; | |
3726 } else { | |
3727 master_params.pVersion = &pms_version; | |
3728 } | |
3729 master_params.RandomInfo.pClientRandom = cr; | |
3730 master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; | |
3731 master_params.RandomInfo.pServerRandom = sr; | |
3732 master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; | |
3733 | |
3734 params.data = (unsigned char *) &master_params; | |
3735 params.len = sizeof master_params; | |
3736 } | |
3737 | |
3738 if (pms != NULL) { | |
3739 #if defined(TRACE) | |
3740 if (ssl_trace >= 100) { | |
3741 SECStatus extractRV = PK11_ExtractKeyValue(pms); | |
3742 if (extractRV == SECSuccess) { | |
3743 SECItem * keyData = PK11_GetKeyData(pms); | |
3744 if (keyData && keyData->data && keyData->len) { | |
3745 ssl_PrintBuf(ss, "Pre-Master Secret", | |
3746 keyData->data, keyData->len); | |
3747 } | |
3748 } | |
3749 } | |
3750 #endif | |
3751 pwSpec->master_secret = PK11_DeriveWithFlags(pms, master_derive, | |
3752 ¶ms, key_derive, CKA_DERIVE, 0, keyFlags); | |
3753 if (!isDH && pwSpec->master_secret && ss->opt.detectRollBack) { | |
3754 SSL3ProtocolVersion client_version; | |
3755 client_version = pms_version.major << 8 | pms_version.minor; | |
3756 | |
3757 if (IS_DTLS(ss)) { | |
3758 client_version = dtls_DTLSVersionToTLSVersion(client_version); | |
3759 } | |
3760 | |
3761 if (client_version != ss->clientHelloVersion) { | |
3762 /* Destroy it. Version roll-back detected. */ | |
3763 PK11_FreeSymKey(pwSpec->master_secret); | |
3764 pwSpec->master_secret = NULL; | |
3765 } | |
3766 } | |
3767 if (pwSpec->master_secret == NULL) { | |
3768 /* Generate a faux master secret in the same slot as the old one. */ | |
3769 PK11SlotInfo * slot = PK11_GetSlotFromKey((PK11SymKey *)pms); | |
3770 PK11SymKey * fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot); | |
3771 | |
3772 PK11_FreeSlot(slot); | |
3773 if (fpms != NULL) { | |
3774 pwSpec->master_secret = PK11_DeriveWithFlags(fpms, | |
3775 master_derive, ¶ms, key_derive, | |
3776 CKA_DERIVE, 0, keyFlags); | |
3777 PK11_FreeSymKey(fpms); | |
3778 } | |
3779 } | |
3780 } | |
3781 if (pwSpec->master_secret == NULL) { | |
3782 /* Generate a faux master secret from the internal slot. */ | |
3783 PK11SlotInfo * slot = PK11_GetInternalSlot(); | |
3784 PK11SymKey * fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot); | |
3785 | |
3786 PK11_FreeSlot(slot); | |
3787 if (fpms != NULL) { | |
3788 pwSpec->master_secret = PK11_DeriveWithFlags(fpms, | |
3789 master_derive, ¶ms, key_derive, | |
3790 CKA_DERIVE, 0, keyFlags); | |
3791 if (pwSpec->master_secret == NULL) { | |
3792 pwSpec->master_secret = fpms; /* use the fpms as the master. */ | |
3793 fpms = NULL; | |
3794 } | |
3795 } | |
3796 if (fpms) { | |
3797 PK11_FreeSymKey(fpms); | |
3798 } | |
3799 } | |
3800 if (pwSpec->master_secret == NULL) { | |
3801 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); | |
3802 return rv; | |
3803 } | |
3804 #ifndef NO_PKCS11_BYPASS | |
3805 if (ss->opt.bypassPKCS11) { | |
3806 SECItem * keydata; | |
3807 /* In hope of doing a "double bypass", | |
3808 * need to extract the master secret's value from the key object | |
3809 * and store it raw in the sslSocket struct. | |
3810 */ | |
3811 rv = PK11_ExtractKeyValue(pwSpec->master_secret); | |
3812 if (rv != SECSuccess) { | |
3813 return rv; | |
3814 } | |
3815 /* This returns the address of the secItem inside the key struct, | |
3816 * not a copy or a reference. So, there's no need to free it. | |
3817 */ | |
3818 keydata = PK11_GetKeyData(pwSpec->master_secret); | |
3819 if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) { | |
3820 memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len); | |
3821 pwSpec->msItem.data = pwSpec->raw_master_secret; | |
3822 pwSpec->msItem.len = keydata->len; | |
3823 } else { | |
3824 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
3825 return SECFailure; | |
3826 } | |
3827 } | |
3828 #endif | |
3829 return SECSuccess; | |
3830 } | |
3831 | |
3832 | |
3833 /* | |
3834 * Derive encryption and MAC Keys (and IVs) from master secret | |
3835 * Sets a useful error code when returning SECFailure. | |
3836 * | |
3837 * Called only from ssl3_InitPendingCipherSpec(), | |
3838 * which in turn is called from | |
3839 * sendRSAClientKeyExchange (for Full handshake) | |
3840 * sendDHClientKeyExchange (for Full handshake) | |
3841 * ssl3_HandleClientKeyExchange (for Full handshake) | |
3842 * ssl3_HandleServerHello (for session restart) | |
3843 * ssl3_HandleClientHello (for session restart) | |
3844 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock. | |
3845 * ssl3_InitPendingCipherSpec does that. | |
3846 * | |
3847 */ | |
3848 static SECStatus | |
3849 ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss) | |
3850 { | |
3851 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; | |
3852 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; | |
3853 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; | |
3854 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; | |
3855 PRBool isTLS = (PRBool)(kea_def->tls_keygen || | |
3856 (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); | |
3857 PRBool isTLS12= | |
3858 (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
3859 /* following variables used in PKCS11 path */ | |
3860 const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def; | |
3861 PK11SlotInfo * slot = NULL; | |
3862 PK11SymKey * symKey = NULL; | |
3863 void * pwArg = ss->pkcs11PinArg; | |
3864 int keySize; | |
3865 CK_SSL3_KEY_MAT_PARAMS key_material_params; | |
3866 CK_SSL3_KEY_MAT_OUT returnedKeys; | |
3867 CK_MECHANISM_TYPE key_derive; | |
3868 CK_MECHANISM_TYPE bulk_mechanism; | |
3869 SSLCipherAlgorithm calg; | |
3870 SECItem params; | |
3871 PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null); | |
3872 | |
3873 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
3874 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); | |
3875 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
3876 | |
3877 if (!pwSpec->master_secret) { | |
3878 PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); | |
3879 return SECFailure; | |
3880 } | |
3881 /* | |
3882 * generate the key material | |
3883 */ | |
3884 key_material_params.ulMacSizeInBits = pwSpec->mac_size * BPB; | |
3885 key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB; | |
3886 key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB; | |
3887 if (cipher_def->type == type_block && | |
3888 pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { | |
3889 /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */ | |
3890 key_material_params.ulIVSizeInBits = 0; | |
3891 memset(pwSpec->client.write_iv, 0, cipher_def->iv_size); | |
3892 memset(pwSpec->server.write_iv, 0, cipher_def->iv_size); | |
3893 } | |
3894 | |
3895 key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited); | |
3896 | |
3897 key_material_params.RandomInfo.pClientRandom = cr; | |
3898 key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; | |
3899 key_material_params.RandomInfo.pServerRandom = sr; | |
3900 key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; | |
3901 key_material_params.pReturnedKeyMaterial = &returnedKeys; | |
3902 | |
3903 returnedKeys.pIVClient = pwSpec->client.write_iv; | |
3904 returnedKeys.pIVServer = pwSpec->server.write_iv; | |
3905 keySize = cipher_def->key_size; | |
3906 | |
3907 if (skipKeysAndIVs) { | |
3908 keySize = 0; | |
3909 key_material_params.ulKeySizeInBits = 0; | |
3910 key_material_params.ulIVSizeInBits = 0; | |
3911 returnedKeys.pIVClient = NULL; | |
3912 returnedKeys.pIVServer = NULL; | |
3913 } | |
3914 | |
3915 calg = cipher_def->calg; | |
3916 PORT_Assert( alg2Mech[calg].calg == calg); | |
3917 bulk_mechanism = alg2Mech[calg].cmech; | |
3918 | |
3919 params.data = (unsigned char *)&key_material_params; | |
3920 params.len = sizeof(key_material_params); | |
3921 | |
3922 if (isTLS12) { | |
3923 key_derive = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256; | |
3924 } else if (isTLS) { | |
3925 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; | |
3926 } else { | |
3927 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; | |
3928 } | |
3929 | |
3930 /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and | |
3931 * DERIVE by DEFAULT */ | |
3932 symKey = PK11_Derive(pwSpec->master_secret, key_derive, ¶ms, | |
3933 bulk_mechanism, CKA_ENCRYPT, keySize); | |
3934 if (!symKey) { | |
3935 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); | |
3936 return SECFailure; | |
3937 } | |
3938 /* we really should use the actual mac'ing mechanism here, but we | |
3939 * don't because these types are used to map keytype anyway and both | |
3940 * mac's map to the same keytype. | |
3941 */ | |
3942 slot = PK11_GetSlotFromKey(symKey); | |
3943 | |
3944 PK11_FreeSlot(slot); /* slot is held until the key is freed */ | |
3945 pwSpec->client.write_mac_key = | |
3946 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, | |
3947 CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg); | |
3948 if (pwSpec->client.write_mac_key == NULL ) { | |
3949 goto loser; /* loser sets err */ | |
3950 } | |
3951 pwSpec->server.write_mac_key = | |
3952 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, | |
3953 CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg); | |
3954 if (pwSpec->server.write_mac_key == NULL ) { | |
3955 goto loser; /* loser sets err */ | |
3956 } | |
3957 if (!skipKeysAndIVs) { | |
3958 pwSpec->client.write_key = | |
3959 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, | |
3960 bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg); | |
3961 if (pwSpec->client.write_key == NULL ) { | |
3962 goto loser; /* loser sets err */ | |
3963 } | |
3964 pwSpec->server.write_key = | |
3965 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, | |
3966 bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg); | |
3967 if (pwSpec->server.write_key == NULL ) { | |
3968 goto loser; /* loser sets err */ | |
3969 } | |
3970 } | |
3971 PK11_FreeSymKey(symKey); | |
3972 return SECSuccess; | |
3973 | |
3974 | |
3975 loser: | |
3976 if (symKey) PK11_FreeSymKey(symKey); | |
3977 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); | |
3978 return SECFailure; | |
3979 } | |
3980 | |
3981 /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in | |
3982 * buffered messages in ss->ssl3.hs.messages. */ | |
3983 static SECStatus | |
3984 ssl3_InitHandshakeHashes(sslSocket *ss) | |
3985 { | |
3986 SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd)); | |
3987 | |
3988 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown); | |
3989 #ifndef NO_PKCS11_BYPASS | |
3990 if (ss->opt.bypassPKCS11) { | |
3991 PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone); | |
3992 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
3993 /* If we ever support ciphersuites where the PRF hash isn't SHA-256 | |
3994 * then this will need to be updated. */ | |
3995 ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256); | |
3996 if (!ss->ssl3.hs.sha_obj) { | |
3997 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
3998 return SECFailure; | |
3999 } | |
4000 ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone; | |
4001 ss->ssl3.hs.hashType = handshake_hash_single; | |
4002 ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx); | |
4003 } else { | |
4004 ss->ssl3.hs.hashType = handshake_hash_combo; | |
4005 MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx); | |
4006 SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx); | |
4007 } | |
4008 } else | |
4009 #endif | |
4010 { | |
4011 PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha); | |
4012 /* | |
4013 * note: We should probably lookup an SSL3 slot for these | |
4014 * handshake hashes in hopes that we wind up with the same slots | |
4015 * that the master secret will wind up in ... | |
4016 */ | |
4017 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
4018 /* If we ever support ciphersuites where the PRF hash isn't SHA-256 | |
4019 * then this will need to be updated. */ | |
4020 ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256); | |
4021 if (ss->ssl3.hs.sha == NULL) { | |
4022 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4023 return SECFailure; | |
4024 } | |
4025 ss->ssl3.hs.hashType = handshake_hash_single; | |
4026 | |
4027 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { | |
4028 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
4029 return SECFailure; | |
4030 } | |
4031 | |
4032 /* Create a backup SHA-1 hash for a potential client auth | |
4033 * signature. | |
4034 * | |
4035 * In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the | |
4036 * handshake hash function (SHA-256). If the server or the client | |
4037 * does not support SHA-256 as a signature hash, we can either | |
4038 * maintain a backup SHA-1 handshake hash or buffer all handshake | |
4039 * messages. | |
4040 */ | |
4041 if (!ss->sec.isServer) { | |
4042 ss->ssl3.hs.backupHash = PK11_CreateDigestContext(SEC_OID_SHA1); | |
4043 if (ss->ssl3.hs.backupHash == NULL) { | |
4044 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4045 return SECFailure; | |
4046 } | |
4047 | |
4048 if (PK11_DigestBegin(ss->ssl3.hs.backupHash) != SECSuccess) { | |
4049 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4050 return SECFailure; | |
4051 } | |
4052 } | |
4053 } else { | |
4054 /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or | |
4055 * created successfully. */ | |
4056 ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5); | |
4057 if (ss->ssl3.hs.md5 == NULL) { | |
4058 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
4059 return SECFailure; | |
4060 } | |
4061 ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1); | |
4062 if (ss->ssl3.hs.sha == NULL) { | |
4063 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); | |
4064 ss->ssl3.hs.md5 = NULL; | |
4065 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4066 return SECFailure; | |
4067 } | |
4068 ss->ssl3.hs.hashType = handshake_hash_combo; | |
4069 | |
4070 if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) { | |
4071 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
4072 return SECFailure; | |
4073 } | |
4074 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { | |
4075 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4076 return SECFailure; | |
4077 } | |
4078 } | |
4079 } | |
4080 | |
4081 if (ss->ssl3.hs.messages.len > 0) { | |
4082 if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf, | |
4083 ss->ssl3.hs.messages.len) != | |
4084 SECSuccess) { | |
4085 return SECFailure; | |
4086 } | |
4087 PORT_Free(ss->ssl3.hs.messages.buf); | |
4088 ss->ssl3.hs.messages.buf = NULL; | |
4089 ss->ssl3.hs.messages.len = 0; | |
4090 ss->ssl3.hs.messages.space = 0; | |
4091 } | |
4092 | |
4093 return SECSuccess; | |
4094 } | |
4095 | |
4096 static SECStatus | |
4097 ssl3_RestartHandshakeHashes(sslSocket *ss) | |
4098 { | |
4099 SECStatus rv = SECSuccess; | |
4100 | |
4101 SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes", | |
4102 SSL_GETPID(), ss->fd )); | |
4103 ss->ssl3.hs.hashType = handshake_hash_unknown; | |
4104 ss->ssl3.hs.messages.len = 0; | |
4105 #ifndef NO_PKCS11_BYPASS | |
4106 ss->ssl3.hs.sha_obj = NULL; | |
4107 ss->ssl3.hs.sha_clone = NULL; | |
4108 #endif | |
4109 if (ss->ssl3.hs.md5) { | |
4110 PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE); | |
4111 ss->ssl3.hs.md5 = NULL; | |
4112 } | |
4113 if (ss->ssl3.hs.sha) { | |
4114 PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE); | |
4115 ss->ssl3.hs.sha = NULL; | |
4116 } | |
4117 return rv; | |
4118 } | |
4119 | |
4120 /* | |
4121 * Handshake messages | |
4122 */ | |
4123 /* Called from ssl3_InitHandshakeHashes() | |
4124 ** ssl3_AppendHandshake() | |
4125 ** ssl3_StartHandshakeHash() | |
4126 ** ssl3_HandleV2ClientHello() | |
4127 ** ssl3_HandleHandshakeMessage() | |
4128 ** Caller must hold the ssl3Handshake lock. | |
4129 */ | |
4130 static SECStatus | |
4131 ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, | |
4132 unsigned int l) | |
4133 { | |
4134 SECStatus rv = SECSuccess; | |
4135 | |
4136 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
4137 | |
4138 /* We need to buffer the handshake messages until we have established | |
4139 * which handshake hash function to use. */ | |
4140 if (ss->ssl3.hs.hashType == handshake_hash_unknown) { | |
4141 return sslBuffer_Append(&ss->ssl3.hs.messages, b, l); | |
4142 } | |
4143 | |
4144 PRINT_BUF(90, (NULL, "handshake hash input:", b, l)); | |
4145 | |
4146 #ifndef NO_PKCS11_BYPASS | |
4147 if (ss->opt.bypassPKCS11) { | |
4148 if (ss->ssl3.hs.hashType == handshake_hash_single) { | |
4149 ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l); | |
4150 } else { | |
4151 MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l); | |
4152 SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l); | |
4153 } | |
4154 return rv; | |
4155 } | |
4156 #endif | |
4157 if (ss->ssl3.hs.hashType == handshake_hash_single) { | |
4158 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); | |
4159 if (rv != SECSuccess) { | |
4160 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
4161 return rv; | |
4162 } | |
4163 if (ss->ssl3.hs.backupHash) { | |
4164 rv = PK11_DigestOp(ss->ssl3.hs.backupHash, b, l); | |
4165 if (rv != SECSuccess) { | |
4166 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4167 return rv; | |
4168 } | |
4169 } | |
4170 } else { | |
4171 rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l); | |
4172 if (rv != SECSuccess) { | |
4173 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
4174 return rv; | |
4175 } | |
4176 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); | |
4177 if (rv != SECSuccess) { | |
4178 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4179 return rv; | |
4180 } | |
4181 } | |
4182 return rv; | |
4183 } | |
4184 | |
4185 /************************************************************************** | |
4186 * Append Handshake functions. | |
4187 * All these functions set appropriate error codes. | |
4188 * Most rely on ssl3_AppendHandshake to set the error code. | |
4189 **************************************************************************/ | |
4190 SECStatus | |
4191 ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes) | |
4192 { | |
4193 unsigned char * src = (unsigned char *)void_src; | |
4194 int room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; | |
4195 SECStatus rv; | |
4196 | |
4197 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); /* protects
sendBuf. */ | |
4198 | |
4199 if (!bytes) | |
4200 return SECSuccess; | |
4201 if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) { | |
4202 rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH, | |
4203 PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes))); | |
4204 if (rv != SECSuccess) | |
4205 return rv; /* sslBuffer_Grow has set a memory error code. */ | |
4206 room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; | |
4207 } | |
4208 | |
4209 PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char*)void_src, bytes)); | |
4210 rv = ssl3_UpdateHandshakeHashes(ss, src, bytes); | |
4211 if (rv != SECSuccess) | |
4212 return rv; /* error code set by ssl3_UpdateHandshakeHashes */ | |
4213 | |
4214 while (bytes > room) { | |
4215 if (room > 0) | |
4216 PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, | |
4217 room); | |
4218 ss->sec.ci.sendBuf.len += room; | |
4219 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); | |
4220 if (rv != SECSuccess) { | |
4221 return rv; /* error code set by ssl3_FlushHandshake */ | |
4222 } | |
4223 bytes -= room; | |
4224 src += room; | |
4225 room = ss->sec.ci.sendBuf.space; | |
4226 PORT_Assert(ss->sec.ci.sendBuf.len == 0); | |
4227 } | |
4228 PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes); | |
4229 ss->sec.ci.sendBuf.len += bytes; | |
4230 return SECSuccess; | |
4231 } | |
4232 | |
4233 SECStatus | |
4234 ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize) | |
4235 { | |
4236 SECStatus rv; | |
4237 PRUint8 b[4]; | |
4238 PRUint8 * p = b; | |
4239 | |
4240 switch (lenSize) { | |
4241 case 4: | |
4242 *p++ = (num >> 24) & 0xff; | |
4243 case 3: | |
4244 *p++ = (num >> 16) & 0xff; | |
4245 case 2: | |
4246 *p++ = (num >> 8) & 0xff; | |
4247 case 1: | |
4248 *p = num & 0xff; | |
4249 } | |
4250 SSL_TRC(60, ("%d: number:", SSL_GETPID())); | |
4251 rv = ssl3_AppendHandshake(ss, &b[0], lenSize); | |
4252 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4253 } | |
4254 | |
4255 SECStatus | |
4256 ssl3_AppendHandshakeVariable( | |
4257 sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize) | |
4258 { | |
4259 SECStatus rv; | |
4260 | |
4261 PORT_Assert((bytes < (1<<8) && lenSize == 1) || | |
4262 (bytes < (1L<<16) && lenSize == 2) || | |
4263 (bytes < (1L<<24) && lenSize == 3)); | |
4264 | |
4265 SSL_TRC(60,("%d: append variable:", SSL_GETPID())); | |
4266 rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize); | |
4267 if (rv != SECSuccess) { | |
4268 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4269 } | |
4270 SSL_TRC(60, ("data:")); | |
4271 rv = ssl3_AppendHandshake(ss, src, bytes); | |
4272 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4273 } | |
4274 | |
4275 SECStatus | |
4276 ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length) | |
4277 { | |
4278 SECStatus rv; | |
4279 | |
4280 /* If we already have a message in place, we need to enqueue it. | |
4281 * This empties the buffer. This is a convenient place to call | |
4282 * dtls_StageHandshakeMessage to mark the message boundary. | |
4283 */ | |
4284 if (IS_DTLS(ss)) { | |
4285 rv = dtls_StageHandshakeMessage(ss); | |
4286 if (rv != SECSuccess) { | |
4287 return rv; | |
4288 } | |
4289 } | |
4290 | |
4291 SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s", | |
4292 SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t))); | |
4293 | |
4294 rv = ssl3_AppendHandshakeNumber(ss, t, 1); | |
4295 if (rv != SECSuccess) { | |
4296 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4297 } | |
4298 rv = ssl3_AppendHandshakeNumber(ss, length, 3); | |
4299 if (rv != SECSuccess) { | |
4300 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4301 } | |
4302 | |
4303 if (IS_DTLS(ss)) { | |
4304 /* Note that we make an unfragmented message here. We fragment in the | |
4305 * transmission code, if necessary */ | |
4306 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2); | |
4307 if (rv != SECSuccess) { | |
4308 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4309 } | |
4310 ss->ssl3.hs.sendMessageSeq++; | |
4311 | |
4312 /* 0 is the fragment offset, because it's not fragmented yet */ | |
4313 rv = ssl3_AppendHandshakeNumber(ss, 0, 3); | |
4314 if (rv != SECSuccess) { | |
4315 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4316 } | |
4317 | |
4318 /* Fragment length -- set to the packet length because not fragmented */ | |
4319 rv = ssl3_AppendHandshakeNumber(ss, length, 3); | |
4320 if (rv != SECSuccess) { | |
4321 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4322 } | |
4323 } | |
4324 | |
4325 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4326 } | |
4327 | |
4328 /* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of | |
4329 * |sigAndHash| to the current handshake message. */ | |
4330 SECStatus | |
4331 ssl3_AppendSignatureAndHashAlgorithm( | |
4332 sslSocket *ss, const SSL3SignatureAndHashAlgorithm* sigAndHash) | |
4333 { | |
4334 unsigned char serialized[2]; | |
4335 | |
4336 serialized[0] = ssl3_OIDToTLSHashAlgorithm(sigAndHash->hashAlg); | |
4337 if (serialized[0] == 0) { | |
4338 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); | |
4339 return SECFailure; | |
4340 } | |
4341 | |
4342 serialized[1] = sigAndHash->sigAlg; | |
4343 | |
4344 return ssl3_AppendHandshake(ss, serialized, sizeof(serialized)); | |
4345 } | |
4346 | |
4347 /************************************************************************** | |
4348 * Consume Handshake functions. | |
4349 * | |
4350 * All data used in these functions is protected by two locks, | |
4351 * the RecvBufLock and the SSL3HandshakeLock | |
4352 **************************************************************************/ | |
4353 | |
4354 /* Read up the next "bytes" number of bytes from the (decrypted) input | |
4355 * stream "b" (which is *length bytes long). Copy them into buffer "v". | |
4356 * Reduces *length by bytes. Advances *b by bytes. | |
4357 * | |
4358 * If this function returns SECFailure, it has already sent an alert, | |
4359 * and has set a generic error code. The caller should probably | |
4360 * override the generic error code by setting another. | |
4361 */ | |
4362 SECStatus | |
4363 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b, | |
4364 PRUint32 *length) | |
4365 { | |
4366 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
4367 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
4368 | |
4369 if ((PRUint32)bytes > *length) { | |
4370 return ssl3_DecodeError(ss); | |
4371 } | |
4372 PORT_Memcpy(v, *b, bytes); | |
4373 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); | |
4374 *b += bytes; | |
4375 *length -= bytes; | |
4376 return SECSuccess; | |
4377 } | |
4378 | |
4379 /* Read up the next "bytes" number of bytes from the (decrypted) input | |
4380 * stream "b" (which is *length bytes long), and interpret them as an | |
4381 * integer in network byte order. Returns the received value. | |
4382 * Reduces *length by bytes. Advances *b by bytes. | |
4383 * | |
4384 * Returns SECFailure (-1) on failure. | |
4385 * This value is indistinguishable from the equivalent received value. | |
4386 * Only positive numbers are to be received this way. | |
4387 * Thus, the largest value that may be sent this way is 0x7fffffff. | |
4388 * On error, an alert has been sent, and a generic error code has been set. | |
4389 */ | |
4390 PRInt32 | |
4391 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b, | |
4392 PRUint32 *length) | |
4393 { | |
4394 PRUint8 *buf = *b; | |
4395 int i; | |
4396 PRInt32 num = 0; | |
4397 | |
4398 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
4399 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
4400 PORT_Assert( bytes <= sizeof num); | |
4401 | |
4402 if ((PRUint32)bytes > *length) { | |
4403 return ssl3_DecodeError(ss); | |
4404 } | |
4405 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); | |
4406 | |
4407 for (i = 0; i < bytes; i++) | |
4408 num = (num << 8) + buf[i]; | |
4409 *b += bytes; | |
4410 *length -= bytes; | |
4411 return num; | |
4412 } | |
4413 | |
4414 /* Read in two values from the incoming decrypted byte stream "b", which is | |
4415 * *length bytes long. The first value is a number whose size is "bytes" | |
4416 * bytes long. The second value is a byte-string whose size is the value | |
4417 * of the first number received. The latter byte-string, and its length, | |
4418 * is returned in the SECItem i. | |
4419 * | |
4420 * Returns SECFailure (-1) on failure. | |
4421 * On error, an alert has been sent, and a generic error code has been set. | |
4422 * | |
4423 * RADICAL CHANGE for NSS 3.11. All callers of this function make copies | |
4424 * of the data returned in the SECItem *i, so making a copy of it here | |
4425 * is simply wasteful. So, This function now just sets SECItem *i to | |
4426 * point to the values in the buffer **b. | |
4427 */ | |
4428 SECStatus | |
4429 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes, | |
4430 SSL3Opaque **b, PRUint32 *length) | |
4431 { | |
4432 PRInt32 count; | |
4433 | |
4434 PORT_Assert(bytes <= 3); | |
4435 i->len = 0; | |
4436 i->data = NULL; | |
4437 count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length); | |
4438 if (count < 0) { /* Can't test for SECSuccess here. */ | |
4439 return SECFailure; | |
4440 } | |
4441 if (count > 0) { | |
4442 if ((PRUint32)count > *length) { | |
4443 return ssl3_DecodeError(ss); | |
4444 } | |
4445 i->data = *b; | |
4446 i->len = count; | |
4447 *b += count; | |
4448 *length -= count; | |
4449 } | |
4450 return SECSuccess; | |
4451 } | |
4452 | |
4453 /* tlsHashOIDMap contains the mapping between TLS hash identifiers and the | |
4454 * SECOidTag used internally by NSS. */ | |
4455 static const struct { | |
4456 int tlsHash; | |
4457 SECOidTag oid; | |
4458 } tlsHashOIDMap[] = { | |
4459 { tls_hash_md5, SEC_OID_MD5 }, | |
4460 { tls_hash_sha1, SEC_OID_SHA1 }, | |
4461 { tls_hash_sha224, SEC_OID_SHA224 }, | |
4462 { tls_hash_sha256, SEC_OID_SHA256 }, | |
4463 { tls_hash_sha384, SEC_OID_SHA384 }, | |
4464 { tls_hash_sha512, SEC_OID_SHA512 } | |
4465 }; | |
4466 | |
4467 /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value. | |
4468 * If the hash is not recognised, SEC_OID_UNKNOWN is returned. | |
4469 * | |
4470 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ | |
4471 SECOidTag | |
4472 ssl3_TLSHashAlgorithmToOID(int hashFunc) | |
4473 { | |
4474 unsigned int i; | |
4475 | |
4476 for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) { | |
4477 if (hashFunc == tlsHashOIDMap[i].tlsHash) { | |
4478 return tlsHashOIDMap[i].oid; | |
4479 } | |
4480 } | |
4481 return SEC_OID_UNKNOWN; | |
4482 } | |
4483 | |
4484 /* ssl3_OIDToTLSHashAlgorithm converts an OID to a TLS hash algorithm | |
4485 * identifier. If the hash is not recognised, zero is returned. | |
4486 * | |
4487 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ | |
4488 static int | |
4489 ssl3_OIDToTLSHashAlgorithm(SECOidTag oid) | |
4490 { | |
4491 unsigned int i; | |
4492 | |
4493 for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) { | |
4494 if (oid == tlsHashOIDMap[i].oid) { | |
4495 return tlsHashOIDMap[i].tlsHash; | |
4496 } | |
4497 } | |
4498 return 0; | |
4499 } | |
4500 | |
4501 /* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm | |
4502 * identifier for a given KeyType. */ | |
4503 static SECStatus | |
4504 ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType, | |
4505 TLSSignatureAlgorithm *out) | |
4506 { | |
4507 switch (keyType) { | |
4508 case rsaKey: | |
4509 *out = tls_sig_rsa; | |
4510 return SECSuccess; | |
4511 case dsaKey: | |
4512 *out = tls_sig_dsa; | |
4513 return SECSuccess; | |
4514 case ecKey: | |
4515 *out = tls_sig_ecdsa; | |
4516 return SECSuccess; | |
4517 default: | |
4518 PORT_SetError(SEC_ERROR_INVALID_KEY); | |
4519 return SECFailure; | |
4520 } | |
4521 } | |
4522 | |
4523 /* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature | |
4524 * algorithm identifier for the given certificate. */ | |
4525 static SECStatus | |
4526 ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert, | |
4527 TLSSignatureAlgorithm *out) | |
4528 { | |
4529 SECKEYPublicKey *key; | |
4530 KeyType keyType; | |
4531 | |
4532 key = CERT_ExtractPublicKey(cert); | |
4533 if (key == NULL) { | |
4534 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); | |
4535 return SECFailure; | |
4536 } | |
4537 | |
4538 keyType = key->keyType; | |
4539 SECKEY_DestroyPublicKey(key); | |
4540 return ssl3_TLSSignatureAlgorithmForKeyType(keyType, out); | |
4541 } | |
4542 | |
4543 /* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature | |
4544 * algorithm identifier in |sigAndHash| is consistent with the public key in | |
4545 * |cert|. If so, SECSuccess is returned. Otherwise, PORT_SetError is called | |
4546 * and SECFailure is returned. */ | |
4547 SECStatus | |
4548 ssl3_CheckSignatureAndHashAlgorithmConsistency( | |
4549 const SSL3SignatureAndHashAlgorithm *sigAndHash, CERTCertificate* cert) | |
4550 { | |
4551 SECStatus rv; | |
4552 TLSSignatureAlgorithm sigAlg; | |
4553 | |
4554 rv = ssl3_TLSSignatureAlgorithmForCertificate(cert, &sigAlg); | |
4555 if (rv != SECSuccess) { | |
4556 return rv; | |
4557 } | |
4558 if (sigAlg != sigAndHash->sigAlg) { | |
4559 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM); | |
4560 return SECFailure; | |
4561 } | |
4562 return SECSuccess; | |
4563 } | |
4564 | |
4565 /* ssl3_ConsumeSignatureAndHashAlgorithm reads a SignatureAndHashAlgorithm | |
4566 * structure from |b| and puts the resulting value into |out|. |b| and |length| | |
4567 * are updated accordingly. | |
4568 * | |
4569 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ | |
4570 SECStatus | |
4571 ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss, | |
4572 SSL3Opaque **b, | |
4573 PRUint32 *length, | |
4574 SSL3SignatureAndHashAlgorithm *out) | |
4575 { | |
4576 unsigned char bytes[2]; | |
4577 SECStatus rv; | |
4578 | |
4579 rv = ssl3_ConsumeHandshake(ss, bytes, sizeof(bytes), b, length); | |
4580 if (rv != SECSuccess) { | |
4581 return rv; | |
4582 } | |
4583 | |
4584 out->hashAlg = ssl3_TLSHashAlgorithmToOID(bytes[0]); | |
4585 if (out->hashAlg == SEC_OID_UNKNOWN) { | |
4586 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); | |
4587 return SECFailure; | |
4588 } | |
4589 | |
4590 out->sigAlg = bytes[1]; | |
4591 return SECSuccess; | |
4592 } | |
4593 | |
4594 /************************************************************************** | |
4595 * end of Consume Handshake functions. | |
4596 **************************************************************************/ | |
4597 | |
4598 /* Extract the hashes of handshake messages to this point. | |
4599 * Called from ssl3_SendCertificateVerify | |
4600 * ssl3_SendFinished | |
4601 * ssl3_HandleHandshakeMessage | |
4602 * | |
4603 * Caller must hold the SSL3HandshakeLock. | |
4604 * Caller must hold a read or write lock on the Spec R/W lock. | |
4605 * (There is presently no way to assert on a Read lock.) | |
4606 */ | |
4607 static SECStatus | |
4608 ssl3_ComputeHandshakeHashes(sslSocket * ss, | |
4609 ssl3CipherSpec *spec, /* uses ->master_secret */ | |
4610 SSL3Hashes * hashes, /* output goes here. */ | |
4611 PRUint32 sender) | |
4612 { | |
4613 SECStatus rv = SECSuccess; | |
4614 PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0); | |
4615 unsigned int outLength; | |
4616 SSL3Opaque md5_inner[MAX_MAC_LENGTH]; | |
4617 SSL3Opaque sha_inner[MAX_MAC_LENGTH]; | |
4618 | |
4619 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
4620 hashes->hashAlg = SEC_OID_UNKNOWN; | |
4621 | |
4622 #ifndef NO_PKCS11_BYPASS | |
4623 if (ss->opt.bypassPKCS11 && | |
4624 ss->ssl3.hs.hashType == handshake_hash_single) { | |
4625 /* compute them without PKCS11 */ | |
4626 PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; | |
4627 | |
4628 if (!spec->msItem.data) { | |
4629 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); | |
4630 return SECFailure; | |
4631 } | |
4632 | |
4633 ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx); | |
4634 ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len, | |
4635 sizeof(hashes->u.raw)); | |
4636 | |
4637 PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len)); | |
4638 | |
4639 /* If we ever support ciphersuites where the PRF hash isn't SHA-256 | |
4640 * then this will need to be updated. */ | |
4641 hashes->hashAlg = SEC_OID_SHA256; | |
4642 rv = SECSuccess; | |
4643 } else if (ss->opt.bypassPKCS11) { | |
4644 /* compute them without PKCS11 */ | |
4645 PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS]; | |
4646 PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; | |
4647 | |
4648 #define md5cx ((MD5Context *)md5_cx) | |
4649 #define shacx ((SHA1Context *)sha_cx) | |
4650 | |
4651 if (!spec->msItem.data) { | |
4652 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); | |
4653 return SECFailure; | |
4654 } | |
4655 | |
4656 MD5_Clone (md5cx, (MD5Context *)ss->ssl3.hs.md5_cx); | |
4657 SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx); | |
4658 | |
4659 if (!isTLS) { | |
4660 /* compute hashes for SSL3. */ | |
4661 unsigned char s[4]; | |
4662 | |
4663 s[0] = (unsigned char)(sender >> 24); | |
4664 s[1] = (unsigned char)(sender >> 16); | |
4665 s[2] = (unsigned char)(sender >> 8); | |
4666 s[3] = (unsigned char)sender; | |
4667 | |
4668 if (sender != 0) { | |
4669 MD5_Update(md5cx, s, 4); | |
4670 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); | |
4671 } | |
4672 | |
4673 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, | |
4674 mac_defs[mac_md5].pad_size)); | |
4675 | |
4676 MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); | |
4677 MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size); | |
4678 MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH); | |
4679 | |
4680 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); | |
4681 | |
4682 if (sender != 0) { | |
4683 SHA1_Update(shacx, s, 4); | |
4684 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); | |
4685 } | |
4686 | |
4687 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, | |
4688 mac_defs[mac_sha].pad_size)); | |
4689 | |
4690 SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); | |
4691 SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size); | |
4692 SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH); | |
4693 | |
4694 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); | |
4695 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, | |
4696 mac_defs[mac_md5].pad_size)); | |
4697 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH))
; | |
4698 | |
4699 MD5_Begin(md5cx); | |
4700 MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); | |
4701 MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size); | |
4702 MD5_Update(md5cx, md5_inner, MD5_LENGTH); | |
4703 } | |
4704 MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH); | |
4705 | |
4706 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); | |
4707 | |
4708 if (!isTLS) { | |
4709 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, | |
4710 mac_defs[mac_sha].pad_size)); | |
4711 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)
); | |
4712 | |
4713 SHA1_Begin(shacx); | |
4714 SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); | |
4715 SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size); | |
4716 SHA1_Update(shacx, sha_inner, SHA1_LENGTH); | |
4717 } | |
4718 SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH); | |
4719 | |
4720 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH))
; | |
4721 | |
4722 hashes->len = MD5_LENGTH + SHA1_LENGTH; | |
4723 rv = SECSuccess; | |
4724 #undef md5cx | |
4725 #undef shacx | |
4726 } else | |
4727 #endif | |
4728 if (ss->ssl3.hs.hashType == handshake_hash_single) { | |
4729 /* compute hashes with PKCS11 */ | |
4730 PK11Context *h; | |
4731 unsigned int stateLen; | |
4732 unsigned char stackBuf[1024]; | |
4733 unsigned char *stateBuf = NULL; | |
4734 | |
4735 if (!spec->master_secret) { | |
4736 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); | |
4737 return SECFailure; | |
4738 } | |
4739 | |
4740 h = ss->ssl3.hs.sha; | |
4741 stateBuf = PK11_SaveContextAlloc(h, stackBuf, | |
4742 sizeof(stackBuf), &stateLen); | |
4743 if (stateBuf == NULL) { | |
4744 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
4745 goto tls12_loser; | |
4746 } | |
4747 rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len, | |
4748 sizeof(hashes->u.raw)); | |
4749 if (rv != SECSuccess) { | |
4750 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
4751 rv = SECFailure; | |
4752 goto tls12_loser; | |
4753 } | |
4754 /* If we ever support ciphersuites where the PRF hash isn't SHA-256 | |
4755 * then this will need to be updated. */ | |
4756 hashes->hashAlg = SEC_OID_SHA256; | |
4757 rv = SECSuccess; | |
4758 | |
4759 tls12_loser: | |
4760 if (stateBuf) { | |
4761 if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) { | |
4762 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
4763 rv = SECFailure; | |
4764 } | |
4765 if (stateBuf != stackBuf) { | |
4766 PORT_ZFree(stateBuf, stateLen); | |
4767 } | |
4768 } | |
4769 } else { | |
4770 /* compute hashes with PKCS11 */ | |
4771 PK11Context * md5; | |
4772 PK11Context * sha = NULL; | |
4773 unsigned char *md5StateBuf = NULL; | |
4774 unsigned char *shaStateBuf = NULL; | |
4775 unsigned int md5StateLen, shaStateLen; | |
4776 unsigned char md5StackBuf[256]; | |
4777 unsigned char shaStackBuf[512]; | |
4778 | |
4779 if (!spec->master_secret) { | |
4780 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); | |
4781 return SECFailure; | |
4782 } | |
4783 | |
4784 md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf, | |
4785 sizeof md5StackBuf, &md5StateLen); | |
4786 if (md5StateBuf == NULL) { | |
4787 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
4788 goto loser; | |
4789 } | |
4790 md5 = ss->ssl3.hs.md5; | |
4791 | |
4792 shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf, | |
4793 sizeof shaStackBuf, &shaStateLen); | |
4794 if (shaStateBuf == NULL) { | |
4795 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4796 goto loser; | |
4797 } | |
4798 sha = ss->ssl3.hs.sha; | |
4799 | |
4800 if (!isTLS) { | |
4801 /* compute hashes for SSL3. */ | |
4802 unsigned char s[4]; | |
4803 | |
4804 s[0] = (unsigned char)(sender >> 24); | |
4805 s[1] = (unsigned char)(sender >> 16); | |
4806 s[2] = (unsigned char)(sender >> 8); | |
4807 s[3] = (unsigned char)sender; | |
4808 | |
4809 if (sender != 0) { | |
4810 rv |= PK11_DigestOp(md5, s, 4); | |
4811 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); | |
4812 } | |
4813 | |
4814 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, | |
4815 mac_defs[mac_md5].pad_size)); | |
4816 | |
4817 rv |= PK11_DigestKey(md5,spec->master_secret); | |
4818 rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size); | |
4819 rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH); | |
4820 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); | |
4821 if (rv != SECSuccess) { | |
4822 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
4823 rv = SECFailure; | |
4824 goto loser; | |
4825 } | |
4826 | |
4827 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); | |
4828 | |
4829 if (sender != 0) { | |
4830 rv |= PK11_DigestOp(sha, s, 4); | |
4831 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); | |
4832 } | |
4833 | |
4834 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, | |
4835 mac_defs[mac_sha].pad_size)); | |
4836 | |
4837 rv |= PK11_DigestKey(sha, spec->master_secret); | |
4838 rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size); | |
4839 rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH); | |
4840 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); | |
4841 if (rv != SECSuccess) { | |
4842 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4843 rv = SECFailure; | |
4844 goto loser; | |
4845 } | |
4846 | |
4847 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); | |
4848 | |
4849 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, | |
4850 mac_defs[mac_md5].pad_size)); | |
4851 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH))
; | |
4852 | |
4853 rv |= PK11_DigestBegin(md5); | |
4854 rv |= PK11_DigestKey(md5, spec->master_secret); | |
4855 rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size); | |
4856 rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH); | |
4857 } | |
4858 rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH); | |
4859 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); | |
4860 if (rv != SECSuccess) { | |
4861 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
4862 rv = SECFailure; | |
4863 goto loser; | |
4864 } | |
4865 | |
4866 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); | |
4867 | |
4868 if (!isTLS) { | |
4869 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, | |
4870 mac_defs[mac_sha].pad_size)); | |
4871 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)
); | |
4872 | |
4873 rv |= PK11_DigestBegin(sha); | |
4874 rv |= PK11_DigestKey(sha,spec->master_secret); | |
4875 rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size); | |
4876 rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH); | |
4877 } | |
4878 rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH); | |
4879 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); | |
4880 if (rv != SECSuccess) { | |
4881 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4882 rv = SECFailure; | |
4883 goto loser; | |
4884 } | |
4885 | |
4886 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH))
; | |
4887 | |
4888 hashes->len = MD5_LENGTH + SHA1_LENGTH; | |
4889 rv = SECSuccess; | |
4890 | |
4891 loser: | |
4892 if (md5StateBuf) { | |
4893 if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) | |
4894 != SECSuccess) | |
4895 { | |
4896 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
4897 rv = SECFailure; | |
4898 } | |
4899 if (md5StateBuf != md5StackBuf) { | |
4900 PORT_ZFree(md5StateBuf, md5StateLen); | |
4901 } | |
4902 } | |
4903 if (shaStateBuf) { | |
4904 if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) | |
4905 != SECSuccess) | |
4906 { | |
4907 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4908 rv = SECFailure; | |
4909 } | |
4910 if (shaStateBuf != shaStackBuf) { | |
4911 PORT_ZFree(shaStateBuf, shaStateLen); | |
4912 } | |
4913 } | |
4914 } | |
4915 return rv; | |
4916 } | |
4917 | |
4918 static SECStatus | |
4919 ssl3_ComputeBackupHandshakeHashes(sslSocket * ss, | |
4920 SSL3Hashes * hashes) /* output goes here. */ | |
4921 { | |
4922 SECStatus rv = SECSuccess; | |
4923 | |
4924 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
4925 PORT_Assert( !ss->sec.isServer ); | |
4926 PORT_Assert( ss->ssl3.hs.hashType == handshake_hash_single ); | |
4927 | |
4928 rv = PK11_DigestFinal(ss->ssl3.hs.backupHash, hashes->u.raw, &hashes->len, | |
4929 sizeof(hashes->u.raw)); | |
4930 if (rv != SECSuccess) { | |
4931 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4932 rv = SECFailure; | |
4933 goto loser; | |
4934 } | |
4935 hashes->hashAlg = SEC_OID_SHA1; | |
4936 | |
4937 loser: | |
4938 PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); | |
4939 ss->ssl3.hs.backupHash = NULL; | |
4940 return rv; | |
4941 } | |
4942 | |
4943 /* | |
4944 * SSL 2 based implementations pass in the initial outbound buffer | |
4945 * so that the handshake hash can contain the included information. | |
4946 * | |
4947 * Called from ssl2_BeginClientHandshake() in sslcon.c | |
4948 */ | |
4949 SECStatus | |
4950 ssl3_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length) | |
4951 { | |
4952 SECStatus rv; | |
4953 | |
4954 ssl_GetSSL3HandshakeLock(ss); /**************************************/ | |
4955 | |
4956 rv = ssl3_InitState(ss); | |
4957 if (rv != SECSuccess) { | |
4958 goto done; /* ssl3_InitState has set the error code. */ | |
4959 } | |
4960 rv = ssl3_RestartHandshakeHashes(ss); | |
4961 if (rv != SECSuccess) { | |
4962 goto done; | |
4963 } | |
4964 | |
4965 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); | |
4966 PORT_Memcpy( | |
4967 &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES
], | |
4968 &ss->sec.ci.clientChallenge, | |
4969 SSL_CHALLENGE_BYTES); | |
4970 | |
4971 rv = ssl3_UpdateHandshakeHashes(ss, buf, length); | |
4972 /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */ | |
4973 | |
4974 done: | |
4975 ssl_ReleaseSSL3HandshakeLock(ss); /**************************************/ | |
4976 return rv; | |
4977 } | |
4978 | |
4979 /************************************************************************** | |
4980 * end of Handshake Hash functions. | |
4981 * Begin Send and Handle functions for handshakes. | |
4982 **************************************************************************/ | |
4983 | |
4984 /* Called from ssl3_HandleHelloRequest(), | |
4985 * ssl3_RedoHandshake() | |
4986 * ssl2_BeginClientHandshake (when resuming ssl3 session) | |
4987 * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE) | |
4988 */ | |
4989 SECStatus | |
4990 ssl3_SendClientHello(sslSocket *ss, PRBool resending) | |
4991 { | |
4992 sslSessionID * sid; | |
4993 ssl3CipherSpec * cwSpec; | |
4994 SECStatus rv; | |
4995 int i; | |
4996 int length; | |
4997 int num_suites; | |
4998 int actual_count = 0; | |
4999 PRBool isTLS = PR_FALSE; | |
5000 PRBool requestingResume = PR_FALSE, fallbackSCSV = PR_FALSE; | |
5001 PRInt32 total_exten_len = 0; | |
5002 unsigned paddingExtensionLen; | |
5003 unsigned numCompressionMethods; | |
5004 PRInt32 flags; | |
5005 | |
5006 SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(), | |
5007 ss->fd)); | |
5008 | |
5009 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
5010 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); | |
5011 | |
5012 rv = ssl3_InitState(ss); | |
5013 if (rv != SECSuccess) { | |
5014 return rv; /* ssl3_InitState has set the error code. */ | |
5015 } | |
5016 ss->ssl3.hs.sendingSCSV = PR_FALSE; /* Must be reset every handshake */ | |
5017 PORT_Assert(IS_DTLS(ss) || !resending); | |
5018 | |
5019 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); | |
5020 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; | |
5021 | |
5022 /* We might be starting a session renegotiation in which case we should | |
5023 * clear previous state. | |
5024 */ | |
5025 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); | |
5026 | |
5027 rv = ssl3_RestartHandshakeHashes(ss); | |
5028 if (rv != SECSuccess) { | |
5029 return rv; | |
5030 } | |
5031 | |
5032 /* | |
5033 * During a renegotiation, ss->clientHelloVersion will be used again to | |
5034 * work around a Windows SChannel bug. Ensure that it is still enabled. | |
5035 */ | |
5036 if (ss->firstHsDone) { | |
5037 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { | |
5038 PORT_SetError(SSL_ERROR_SSL_DISABLED); | |
5039 return SECFailure; | |
5040 } | |
5041 | |
5042 if (ss->clientHelloVersion < ss->vrange.min || | |
5043 ss->clientHelloVersion > ss->vrange.max) { | |
5044 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); | |
5045 return SECFailure; | |
5046 } | |
5047 } | |
5048 | |
5049 /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup | |
5050 * handles expired entries and other details. | |
5051 * XXX If we've been called from ssl2_BeginClientHandshake, then | |
5052 * this lookup is duplicative and wasteful. | |
5053 */ | |
5054 sid = (ss->opt.noCache) ? NULL | |
5055 : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->u
rl); | |
5056 | |
5057 /* We can't resume based on a different token. If the sid exists, | |
5058 * make sure the token that holds the master secret still exists ... | |
5059 * If we previously did client-auth, make sure that the token that holds | |
5060 * the private key still exists, is logged in, hasn't been removed, etc. | |
5061 */ | |
5062 if (sid) { | |
5063 PRBool sidOK = PR_TRUE; | |
5064 if (sid->u.ssl3.keys.msIsWrapped) { | |
5065 /* Session key was wrapped, which means it was using PKCS11, */ | |
5066 PK11SlotInfo *slot = NULL; | |
5067 if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) { | |
5068 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, | |
5069 sid->u.ssl3.masterSlotID); | |
5070 } | |
5071 if (slot == NULL) { | |
5072 sidOK = PR_FALSE; | |
5073 } else { | |
5074 PK11SymKey *wrapKey = NULL; | |
5075 if (!PK11_IsPresent(slot) || | |
5076 ((wrapKey = PK11_GetWrapKey(slot, | |
5077 sid->u.ssl3.masterWrapIndex, | |
5078 sid->u.ssl3.masterWrapMech, | |
5079 sid->u.ssl3.masterWrapSeries, | |
5080 ss->pkcs11PinArg)) == NULL) ) { | |
5081 sidOK = PR_FALSE; | |
5082 } | |
5083 if (wrapKey) PK11_FreeSymKey(wrapKey); | |
5084 PK11_FreeSlot(slot); | |
5085 slot = NULL; | |
5086 } | |
5087 } | |
5088 /* If we previously did client-auth, make sure that the token that | |
5089 ** holds the private key still exists, is logged in, hasn't been | |
5090 ** removed, etc. | |
5091 */ | |
5092 if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) { | |
5093 sidOK = PR_FALSE; | |
5094 } | |
5095 | |
5096 /* TLS 1.0 (RFC 2246) Appendix E says: | |
5097 * Whenever a client already knows the highest protocol known to | |
5098 * a server (for example, when resuming a session), it should | |
5099 * initiate the connection in that native protocol. | |
5100 * So we pass sid->version to ssl3_NegotiateVersion() here, except | |
5101 * when renegotiating. | |
5102 * | |
5103 * Windows SChannel compares the client_version inside the RSA | |
5104 * EncryptedPreMasterSecret of a renegotiation with the | |
5105 * client_version of the initial ClientHello rather than the | |
5106 * ClientHello in the renegotiation. To work around this bug, we | |
5107 * continue to use the client_version used in the initial | |
5108 * ClientHello when renegotiating. | |
5109 */ | |
5110 if (sidOK) { | |
5111 if (ss->firstHsDone) { | |
5112 /* | |
5113 * The client_version of the initial ClientHello is still | |
5114 * available in ss->clientHelloVersion. Ensure that | |
5115 * sid->version is bounded within | |
5116 * [ss->vrange.min, ss->clientHelloVersion], otherwise we | |
5117 * can't use sid. | |
5118 */ | |
5119 if (sid->version >= ss->vrange.min && | |
5120 sid->version <= ss->clientHelloVersion) { | |
5121 ss->version = ss->clientHelloVersion; | |
5122 } else { | |
5123 sidOK = PR_FALSE; | |
5124 } | |
5125 } else { | |
5126 if (ssl3_NegotiateVersion(ss, sid->version, | |
5127 PR_FALSE) != SECSuccess) { | |
5128 sidOK = PR_FALSE; | |
5129 } | |
5130 } | |
5131 } | |
5132 | |
5133 if (!sidOK) { | |
5134 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok ); | |
5135 if (ss->sec.uncache) | |
5136 (*ss->sec.uncache)(sid); | |
5137 ssl_FreeSID(sid); | |
5138 sid = NULL; | |
5139 } | |
5140 } | |
5141 | |
5142 if (sid) { | |
5143 requestingResume = PR_TRUE; | |
5144 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits ); | |
5145 | |
5146 PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID, | |
5147 sid->u.ssl3.sessionIDLength)); | |
5148 | |
5149 ss->ssl3.policy = sid->u.ssl3.policy; | |
5150 } else { | |
5151 SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_misses ); | |
5152 | |
5153 /* | |
5154 * Windows SChannel compares the client_version inside the RSA | |
5155 * EncryptedPreMasterSecret of a renegotiation with the | |
5156 * client_version of the initial ClientHello rather than the | |
5157 * ClientHello in the renegotiation. To work around this bug, we | |
5158 * continue to use the client_version used in the initial | |
5159 * ClientHello when renegotiating. | |
5160 */ | |
5161 if (ss->firstHsDone) { | |
5162 ss->version = ss->clientHelloVersion; | |
5163 } else { | |
5164 rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED, | |
5165 PR_TRUE); | |
5166 if (rv != SECSuccess) | |
5167 return rv; /* error code was set */ | |
5168 } | |
5169 | |
5170 sid = ssl3_NewSessionID(ss, PR_FALSE); | |
5171 if (!sid) { | |
5172 return SECFailure; /* memory error is set */ | |
5173 } | |
5174 } | |
5175 | |
5176 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0); | |
5177 ssl_GetSpecWriteLock(ss); | |
5178 cwSpec = ss->ssl3.cwSpec; | |
5179 if (cwSpec->mac_def->mac == mac_null) { | |
5180 /* SSL records are not being MACed. */ | |
5181 cwSpec->version = ss->version; | |
5182 } | |
5183 ssl_ReleaseSpecWriteLock(ss); | |
5184 | |
5185 if (ss->sec.ci.sid != NULL) { | |
5186 ssl_FreeSID(ss->sec.ci.sid); /* decrement ref count, free if zero */ | |
5187 } | |
5188 ss->sec.ci.sid = sid; | |
5189 | |
5190 ss->sec.send = ssl3_SendApplicationData; | |
5191 | |
5192 /* shouldn't get here if SSL3 is disabled, but ... */ | |
5193 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { | |
5194 PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled"); | |
5195 PORT_SetError(SSL_ERROR_SSL_DISABLED); | |
5196 return SECFailure; | |
5197 } | |
5198 | |
5199 /* how many suites does our PKCS11 support (regardless of policy)? */ | |
5200 num_suites = ssl3_config_match_init(ss); | |
5201 if (!num_suites) | |
5202 return SECFailure; /* ssl3_config_match_init has set error code. */ | |
5203 | |
5204 /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV, | |
5205 * only if TLS is disabled. | |
5206 */ | |
5207 if (!ss->firstHsDone && !isTLS) { | |
5208 /* Must set this before calling Hello Extension Senders, | |
5209 * to suppress sending of empty RI extension. | |
5210 */ | |
5211 ss->ssl3.hs.sendingSCSV = PR_TRUE; | |
5212 } | |
5213 | |
5214 /* When we attempt session resumption (only), we must lock the sid to | |
5215 * prevent races with other resumption connections that receive a | |
5216 * NewSessionTicket that will cause the ticket in the sid to be replaced. | |
5217 * Once we've copied the session ticket into our ClientHello message, it | |
5218 * is OK for the ticket to change, so we just need to make sure we hold | |
5219 * the lock across the calls to ssl3_CallHelloExtensionSenders. | |
5220 */ | |
5221 if (sid->u.ssl3.lock) { | |
5222 NSSRWLock_LockRead(sid->u.ssl3.lock); | |
5223 } | |
5224 | |
5225 if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) { | |
5226 PRUint32 maxBytes = 65535; /* 2^16 - 1 */ | |
5227 PRInt32 extLen; | |
5228 | |
5229 extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL); | |
5230 if (extLen < 0) { | |
5231 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5232 return SECFailure; | |
5233 } | |
5234 maxBytes -= extLen; | |
5235 total_exten_len += extLen; | |
5236 | |
5237 if (total_exten_len > 0) | |
5238 total_exten_len += 2; | |
5239 } | |
5240 | |
5241 #if defined(NSS_ENABLE_ECC) | |
5242 if (!total_exten_len || !isTLS) { | |
5243 /* not sending the elliptic_curves and ec_point_formats extensions */ | |
5244 ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */ | |
5245 } | |
5246 #endif | |
5247 | |
5248 if (IS_DTLS(ss)) { | |
5249 ssl3_DisableNonDTLSSuites(ss); | |
5250 } | |
5251 | |
5252 if (!ssl3_HasGCMSupport()) { | |
5253 ssl3_DisableGCMSuites(ss); | |
5254 } | |
5255 | |
5256 /* how many suites are permitted by policy and user preference? */ | |
5257 num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE); | |
5258 if (!num_suites) { | |
5259 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5260 return SECFailure; /* count_cipher_suites has set error code. */ | |
5261 } | |
5262 | |
5263 fallbackSCSV = ss->opt.enableFallbackSCSV && (!requestingResume || | |
5264 ss->version < sid->version); | |
5265 /* make room for SCSV */ | |
5266 if (ss->ssl3.hs.sendingSCSV) { | |
5267 ++num_suites; | |
5268 } | |
5269 if (fallbackSCSV) { | |
5270 ++num_suites; | |
5271 } | |
5272 | |
5273 /* count compression methods */ | |
5274 numCompressionMethods = 0; | |
5275 for (i = 0; i < compressionMethodsCount; i++) { | |
5276 if (compressionEnabled(ss, compressions[i])) | |
5277 numCompressionMethods++; | |
5278 } | |
5279 | |
5280 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + | |
5281 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) + | |
5282 2 + num_suites*sizeof(ssl3CipherSuite) + | |
5283 1 + numCompressionMethods + total_exten_len; | |
5284 if (IS_DTLS(ss)) { | |
5285 length += 1 + ss->ssl3.hs.cookieLen; | |
5286 } | |
5287 | |
5288 /* A padding extension may be included to ensure that the record containing | |
5289 * the ClientHello doesn't have a length between 256 and 511 bytes | |
5290 * (inclusive). Initial, ClientHello records with such lengths trigger bugs | |
5291 * in F5 devices. | |
5292 * | |
5293 * This is not done for DTLS nor for renegotiation. */ | |
5294 if (!IS_DTLS(ss) && isTLS && !ss->firstHsDone) { | |
5295 paddingExtensionLen = ssl3_CalculatePaddingExtensionLength(length); | |
5296 total_exten_len += paddingExtensionLen; | |
5297 length += paddingExtensionLen; | |
5298 } else { | |
5299 paddingExtensionLen = 0; | |
5300 } | |
5301 | |
5302 rv = ssl3_AppendHandshakeHeader(ss, client_hello, length); | |
5303 if (rv != SECSuccess) { | |
5304 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5305 return rv; /* err set by ssl3_AppendHandshake* */ | |
5306 } | |
5307 | |
5308 if (ss->firstHsDone) { | |
5309 /* The client hello version must stay unchanged to work around | |
5310 * the Windows SChannel bug described above. */ | |
5311 PORT_Assert(ss->version == ss->clientHelloVersion); | |
5312 } | |
5313 ss->clientHelloVersion = ss->version; | |
5314 if (IS_DTLS(ss)) { | |
5315 PRUint16 version; | |
5316 | |
5317 version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); | |
5318 rv = ssl3_AppendHandshakeNumber(ss, version, 2); | |
5319 } else { | |
5320 rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2); | |
5321 } | |
5322 if (rv != SECSuccess) { | |
5323 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5324 return rv; /* err set by ssl3_AppendHandshake* */ | |
5325 } | |
5326 | |
5327 if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */ | |
5328 rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random); | |
5329 if (rv != SECSuccess) { | |
5330 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5331 return rv; /* err set by GetNewRandom. */ | |
5332 } | |
5333 } | |
5334 rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random, | |
5335 SSL3_RANDOM_LENGTH); | |
5336 if (rv != SECSuccess) { | |
5337 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5338 return rv; /* err set by ssl3_AppendHandshake* */ | |
5339 } | |
5340 | |
5341 if (sid) | |
5342 rv = ssl3_AppendHandshakeVariable( | |
5343 ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); | |
5344 else | |
5345 rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1); | |
5346 if (rv != SECSuccess) { | |
5347 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5348 return rv; /* err set by ssl3_AppendHandshake* */ | |
5349 } | |
5350 | |
5351 if (IS_DTLS(ss)) { | |
5352 rv = ssl3_AppendHandshakeVariable( | |
5353 ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1); | |
5354 if (rv != SECSuccess) { | |
5355 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5356 return rv; /* err set by ssl3_AppendHandshake* */ | |
5357 } | |
5358 } | |
5359 | |
5360 rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2); | |
5361 if (rv != SECSuccess) { | |
5362 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5363 return rv; /* err set by ssl3_AppendHandshake* */ | |
5364 } | |
5365 | |
5366 if (ss->ssl3.hs.sendingSCSV) { | |
5367 /* Add the actual SCSV */ | |
5368 rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, | |
5369 sizeof(ssl3CipherSuite)); | |
5370 if (rv != SECSuccess) { | |
5371 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5372 return rv; /* err set by ssl3_AppendHandshake* */ | |
5373 } | |
5374 actual_count++; | |
5375 } | |
5376 | |
5377 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { | |
5378 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; | |
5379 if (config_match(suite, ss->ssl3.policy, PR_TRUE, &ss->vrange)) { | |
5380 actual_count++; | |
5381 if (actual_count > num_suites) { | |
5382 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock);
} | |
5383 /* set error card removal/insertion error */ | |
5384 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); | |
5385 return SECFailure; | |
5386 } | |
5387 rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite, | |
5388 sizeof(ssl3CipherSuite)); | |
5389 if (rv != SECSuccess) { | |
5390 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock);
} | |
5391 return rv; /* err set by ssl3_AppendHandshake* */ | |
5392 } | |
5393 } | |
5394 } | |
5395 | |
5396 if (fallbackSCSV) { | |
5397 rv = ssl3_AppendHandshakeNumber(ss, TLS_FALLBACK_SCSV, | |
5398 sizeof(ssl3CipherSuite)); | |
5399 if (rv != SECSuccess) { | |
5400 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5401 return rv; /* err set by ssl3_AppendHandshake* */ | |
5402 } | |
5403 actual_count++; | |
5404 } | |
5405 | |
5406 /* if cards were removed or inserted between count_cipher_suites and | |
5407 * generating our list, detect the error here rather than send it off to | |
5408 * the server.. */ | |
5409 if (actual_count != num_suites) { | |
5410 /* Card removal/insertion error */ | |
5411 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5412 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); | |
5413 return SECFailure; | |
5414 } | |
5415 | |
5416 rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1); | |
5417 if (rv != SECSuccess) { | |
5418 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5419 return rv; /* err set by ssl3_AppendHandshake* */ | |
5420 } | |
5421 for (i = 0; i < compressionMethodsCount; i++) { | |
5422 if (!compressionEnabled(ss, compressions[i])) | |
5423 continue; | |
5424 rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1); | |
5425 if (rv != SECSuccess) { | |
5426 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5427 return rv; /* err set by ssl3_AppendHandshake* */ | |
5428 } | |
5429 } | |
5430 | |
5431 if (total_exten_len) { | |
5432 PRUint32 maxBytes = total_exten_len - 2; | |
5433 PRInt32 extLen; | |
5434 | |
5435 rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2); | |
5436 if (rv != SECSuccess) { | |
5437 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5438 return rv; /* err set by AppendHandshake. */ | |
5439 } | |
5440 | |
5441 extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL); | |
5442 if (extLen < 0) { | |
5443 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5444 return SECFailure; | |
5445 } | |
5446 maxBytes -= extLen; | |
5447 | |
5448 extLen = ssl3_AppendPaddingExtension(ss, paddingExtensionLen, maxBytes); | |
5449 if (extLen < 0) { | |
5450 if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } | |
5451 return SECFailure; | |
5452 } | |
5453 maxBytes -= extLen; | |
5454 | |
5455 PORT_Assert(!maxBytes); | |
5456 } | |
5457 | |
5458 if (sid->u.ssl3.lock) { | |
5459 NSSRWLock_UnlockRead(sid->u.ssl3.lock); | |
5460 } | |
5461 | |
5462 if (ss->xtnData.sentSessionTicketInClientHello) { | |
5463 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes); | |
5464 } | |
5465 | |
5466 if (ss->ssl3.hs.sendingSCSV) { | |
5467 /* Since we sent the SCSV, pretend we sent empty RI extension. */ | |
5468 TLSExtensionData *xtnData = &ss->xtnData; | |
5469 xtnData->advertised[xtnData->numAdvertised++] = | |
5470 ssl_renegotiation_info_xtn; | |
5471 } | |
5472 | |
5473 flags = 0; | |
5474 if (!ss->firstHsDone && !IS_DTLS(ss)) { | |
5475 flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION; | |
5476 } | |
5477 rv = ssl3_FlushHandshake(ss, flags); | |
5478 if (rv != SECSuccess) { | |
5479 return rv; /* error code set by ssl3_FlushHandshake */ | |
5480 } | |
5481 | |
5482 ss->ssl3.hs.ws = wait_server_hello; | |
5483 return rv; | |
5484 } | |
5485 | |
5486 | |
5487 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete | |
5488 * ssl3 Hello Request. | |
5489 * Caller must hold Handshake and RecvBuf locks. | |
5490 */ | |
5491 static SECStatus | |
5492 ssl3_HandleHelloRequest(sslSocket *ss) | |
5493 { | |
5494 sslSessionID *sid = ss->sec.ci.sid; | |
5495 SECStatus rv; | |
5496 | |
5497 SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake", | |
5498 SSL_GETPID(), ss->fd)); | |
5499 | |
5500 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
5501 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
5502 | |
5503 if (ss->ssl3.hs.ws == wait_server_hello) | |
5504 return SECSuccess; | |
5505 if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) { | |
5506 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
5507 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); | |
5508 return SECFailure; | |
5509 } | |
5510 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { | |
5511 ssl_GetXmitBufLock(ss); | |
5512 rv = SSL3_SendAlert(ss, alert_warning, no_renegotiation); | |
5513 ssl_ReleaseXmitBufLock(ss); | |
5514 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); | |
5515 return SECFailure; | |
5516 } | |
5517 | |
5518 if (sid) { | |
5519 if (ss->sec.uncache) | |
5520 ss->sec.uncache(sid); | |
5521 ssl_FreeSID(sid); | |
5522 ss->sec.ci.sid = NULL; | |
5523 } | |
5524 | |
5525 if (IS_DTLS(ss)) { | |
5526 dtls_RehandshakeCleanup(ss); | |
5527 } | |
5528 | |
5529 ssl_GetXmitBufLock(ss); | |
5530 rv = ssl3_SendClientHello(ss, PR_FALSE); | |
5531 ssl_ReleaseXmitBufLock(ss); | |
5532 | |
5533 return rv; | |
5534 } | |
5535 | |
5536 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff | |
5537 | |
5538 static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = { | |
5539 CKM_DES3_ECB, | |
5540 CKM_CAST5_ECB, | |
5541 CKM_DES_ECB, | |
5542 CKM_KEY_WRAP_LYNKS, | |
5543 CKM_IDEA_ECB, | |
5544 CKM_CAST3_ECB, | |
5545 CKM_CAST_ECB, | |
5546 CKM_RC5_ECB, | |
5547 CKM_RC2_ECB, | |
5548 CKM_CDMF_ECB, | |
5549 CKM_SKIPJACK_WRAP, | |
5550 CKM_SKIPJACK_CBC64, | |
5551 CKM_AES_ECB, | |
5552 CKM_CAMELLIA_ECB, | |
5553 CKM_SEED_ECB, | |
5554 UNKNOWN_WRAP_MECHANISM | |
5555 }; | |
5556 | |
5557 static int | |
5558 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech) | |
5559 { | |
5560 const CK_MECHANISM_TYPE *pMech = wrapMechanismList; | |
5561 | |
5562 while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) { | |
5563 ++pMech; | |
5564 } | |
5565 return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1 | |
5566 : (pMech - wrapMechanismList); | |
5567 } | |
5568 | |
5569 static PK11SymKey * | |
5570 ssl_UnwrapSymWrappingKey( | |
5571 SSLWrappedSymWrappingKey *pWswk, | |
5572 SECKEYPrivateKey * svrPrivKey, | |
5573 SSL3KEAType exchKeyType, | |
5574 CK_MECHANISM_TYPE masterWrapMech, | |
5575 void * pwArg) | |
5576 { | |
5577 PK11SymKey * unwrappedWrappingKey = NULL; | |
5578 SECItem wrappedKey; | |
5579 #ifdef NSS_ENABLE_ECC | |
5580 PK11SymKey * Ks; | |
5581 SECKEYPublicKey pubWrapKey; | |
5582 ECCWrappedKeyInfo *ecWrapped; | |
5583 #endif /* NSS_ENABLE_ECC */ | |
5584 | |
5585 /* found the wrapping key on disk. */ | |
5586 PORT_Assert(pWswk->symWrapMechanism == masterWrapMech); | |
5587 PORT_Assert(pWswk->exchKeyType == exchKeyType); | |
5588 if (pWswk->symWrapMechanism != masterWrapMech || | |
5589 pWswk->exchKeyType != exchKeyType) { | |
5590 goto loser; | |
5591 } | |
5592 wrappedKey.type = siBuffer; | |
5593 wrappedKey.data = pWswk->wrappedSymmetricWrappingkey; | |
5594 wrappedKey.len = pWswk->wrappedSymKeyLen; | |
5595 PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey); | |
5596 | |
5597 switch (exchKeyType) { | |
5598 | |
5599 case kt_rsa: | |
5600 unwrappedWrappingKey = | |
5601 PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey, | |
5602 masterWrapMech, CKA_UNWRAP, 0); | |
5603 break; | |
5604 | |
5605 #ifdef NSS_ENABLE_ECC | |
5606 case kt_ecdh: | |
5607 /* | |
5608 * For kt_ecdh, we first create an EC public key based on | |
5609 * data stored with the wrappedSymmetricWrappingkey. Next, | |
5610 * we do an ECDH computation involving this public key and | |
5611 * the SSL server's (long-term) EC private key. The resulting | |
5612 * shared secret is treated the same way as Fortezza's Ks, i.e., | |
5613 * it is used to recover the symmetric wrapping key. | |
5614 * | |
5615 * The data in wrappedSymmetricWrappingkey is laid out as defined | |
5616 * in the ECCWrappedKeyInfo structure. | |
5617 */ | |
5618 ecWrapped = (ECCWrappedKeyInfo *) pWswk->wrappedSymmetricWrappingkey; | |
5619 | |
5620 PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen + | |
5621 ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN); | |
5622 | |
5623 if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen + | |
5624 ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) { | |
5625 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
5626 goto loser; | |
5627 } | |
5628 | |
5629 pubWrapKey.keyType = ecKey; | |
5630 pubWrapKey.u.ec.size = ecWrapped->size; | |
5631 pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen; | |
5632 pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var; | |
5633 pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen; | |
5634 pubWrapKey.u.ec.publicValue.data = ecWrapped->var + | |
5635 ecWrapped->encodedParamLen; | |
5636 | |
5637 wrappedKey.len = ecWrapped->wrappedKeyLen; | |
5638 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + | |
5639 ecWrapped->pubValueLen; | |
5640 | |
5641 /* Derive Ks using ECDH */ | |
5642 Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL, | |
5643 NULL, CKM_ECDH1_DERIVE, masterWrapMech, | |
5644 CKA_DERIVE, 0, CKD_NULL, NULL, NULL); | |
5645 if (Ks == NULL) { | |
5646 goto loser; | |
5647 } | |
5648 | |
5649 /* Use Ks to unwrap the wrapping key */ | |
5650 unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL, | |
5651 &wrappedKey, masterWrapMech, | |
5652 CKA_UNWRAP, 0); | |
5653 PK11_FreeSymKey(Ks); | |
5654 | |
5655 break; | |
5656 #endif | |
5657 | |
5658 default: | |
5659 /* Assert? */ | |
5660 SET_ERROR_CODE | |
5661 goto loser; | |
5662 } | |
5663 loser: | |
5664 return unwrappedWrappingKey; | |
5665 } | |
5666 | |
5667 /* Each process sharing the server session ID cache has its own array of | |
5668 * SymKey pointers for the symmetric wrapping keys that are used to wrap | |
5669 * the master secrets. There is one key for each KEA type. These Symkeys | |
5670 * correspond to the wrapped SymKeys kept in the server session cache. | |
5671 */ | |
5672 | |
5673 typedef struct { | |
5674 PK11SymKey * symWrapKey[kt_kea_size]; | |
5675 } ssl3SymWrapKey; | |
5676 | |
5677 static PZLock * symWrapKeysLock = NULL; | |
5678 static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS]; | |
5679 | |
5680 SECStatus ssl_FreeSymWrapKeysLock(void) | |
5681 { | |
5682 if (symWrapKeysLock) { | |
5683 PZ_DestroyLock(symWrapKeysLock); | |
5684 symWrapKeysLock = NULL; | |
5685 return SECSuccess; | |
5686 } | |
5687 PORT_SetError(SEC_ERROR_NOT_INITIALIZED); | |
5688 return SECFailure; | |
5689 } | |
5690 | |
5691 SECStatus | |
5692 SSL3_ShutdownServerCache(void) | |
5693 { | |
5694 int i, j; | |
5695 | |
5696 if (!symWrapKeysLock) | |
5697 return SECSuccess; /* lock was never initialized */ | |
5698 PZ_Lock(symWrapKeysLock); | |
5699 /* get rid of all symWrapKeys */ | |
5700 for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) { | |
5701 for (j = 0; j < kt_kea_size; ++j) { | |
5702 PK11SymKey ** pSymWrapKey; | |
5703 pSymWrapKey = &symWrapKeys[i].symWrapKey[j]; | |
5704 if (*pSymWrapKey) { | |
5705 PK11_FreeSymKey(*pSymWrapKey); | |
5706 *pSymWrapKey = NULL; | |
5707 } | |
5708 } | |
5709 } | |
5710 | |
5711 PZ_Unlock(symWrapKeysLock); | |
5712 return SECSuccess; | |
5713 } | |
5714 | |
5715 SECStatus ssl_InitSymWrapKeysLock(void) | |
5716 { | |
5717 symWrapKeysLock = PZ_NewLock(nssILockOther); | |
5718 return symWrapKeysLock ? SECSuccess : SECFailure; | |
5719 } | |
5720 | |
5721 /* Try to get wrapping key for mechanism from in-memory array. | |
5722 * If that fails, look for one on disk. | |
5723 * If that fails, generate a new one, put the new one on disk, | |
5724 * Put the new key in the in-memory array. | |
5725 */ | |
5726 static PK11SymKey * | |
5727 getWrappingKey( sslSocket * ss, | |
5728 PK11SlotInfo * masterSecretSlot, | |
5729 SSL3KEAType exchKeyType, | |
5730 CK_MECHANISM_TYPE masterWrapMech, | |
5731 void * pwArg) | |
5732 { | |
5733 SECKEYPrivateKey * svrPrivKey; | |
5734 SECKEYPublicKey * svrPubKey = NULL; | |
5735 PK11SymKey * unwrappedWrappingKey = NULL; | |
5736 PK11SymKey ** pSymWrapKey; | |
5737 CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM; | |
5738 int length; | |
5739 int symWrapMechIndex; | |
5740 SECStatus rv; | |
5741 SECItem wrappedKey; | |
5742 SSLWrappedSymWrappingKey wswk; | |
5743 #ifdef NSS_ENABLE_ECC | |
5744 PK11SymKey * Ks = NULL; | |
5745 SECKEYPublicKey *pubWrapKey = NULL; | |
5746 SECKEYPrivateKey *privWrapKey = NULL; | |
5747 ECCWrappedKeyInfo *ecWrapped; | |
5748 #endif /* NSS_ENABLE_ECC */ | |
5749 | |
5750 svrPrivKey = ss->serverCerts[exchKeyType].SERVERKEY; | |
5751 PORT_Assert(svrPrivKey != NULL); | |
5752 if (!svrPrivKey) { | |
5753 return NULL; /* why are we here?!? */ | |
5754 } | |
5755 | |
5756 symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech); | |
5757 PORT_Assert(symWrapMechIndex >= 0); | |
5758 if (symWrapMechIndex < 0) | |
5759 return NULL; /* invalid masterWrapMech. */ | |
5760 | |
5761 pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType]; | |
5762 | |
5763 ssl_InitSessionCacheLocks(); | |
5764 | |
5765 PZ_Lock(symWrapKeysLock); | |
5766 | |
5767 unwrappedWrappingKey = *pSymWrapKey; | |
5768 if (unwrappedWrappingKey != NULL) { | |
5769 if (PK11_VerifyKeyOK(unwrappedWrappingKey)) { | |
5770 unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey); | |
5771 goto done; | |
5772 } | |
5773 /* slot series has changed, so this key is no good any more. */ | |
5774 PK11_FreeSymKey(unwrappedWrappingKey); | |
5775 *pSymWrapKey = unwrappedWrappingKey = NULL; | |
5776 } | |
5777 | |
5778 /* Try to get wrapped SymWrapping key out of the (disk) cache. */ | |
5779 /* Following call fills in wswk on success. */ | |
5780 if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) { | |
5781 /* found the wrapped sym wrapping key on disk. */ | |
5782 unwrappedWrappingKey = | |
5783 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, | |
5784 masterWrapMech, pwArg); | |
5785 if (unwrappedWrappingKey) { | |
5786 goto install; | |
5787 } | |
5788 } | |
5789 | |
5790 if (!masterSecretSlot) /* caller doesn't want to create a new one. */ | |
5791 goto loser; | |
5792 | |
5793 length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech); | |
5794 /* Zero length means fixed key length algorithm, or error. | |
5795 * It's ambiguous. | |
5796 */ | |
5797 unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL, | |
5798 length, pwArg); | |
5799 if (!unwrappedWrappingKey) { | |
5800 goto loser; | |
5801 } | |
5802 | |
5803 /* Prepare the buffer to receive the wrappedWrappingKey, | |
5804 * the symmetric wrapping key wrapped using the server's pub key. | |
5805 */ | |
5806 PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */ | |
5807 | |
5808 if (ss->serverCerts[exchKeyType].serverKeyPair) { | |
5809 svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey; | |
5810 } | |
5811 if (svrPubKey == NULL) { | |
5812 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
5813 goto loser; | |
5814 } | |
5815 wrappedKey.type = siBuffer; | |
5816 wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey); | |
5817 wrappedKey.data = wswk.wrappedSymmetricWrappingkey; | |
5818 | |
5819 PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey); | |
5820 if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey) | |
5821 goto loser; | |
5822 | |
5823 /* wrap symmetric wrapping key in server's public key. */ | |
5824 switch (exchKeyType) { | |
5825 case kt_rsa: | |
5826 asymWrapMechanism = CKM_RSA_PKCS; | |
5827 rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey, | |
5828 unwrappedWrappingKey, &wrappedKey); | |
5829 break; | |
5830 | |
5831 #ifdef NSS_ENABLE_ECC | |
5832 case kt_ecdh: | |
5833 /* | |
5834 * We generate an ephemeral EC key pair. Perform an ECDH | |
5835 * computation involving this ephemeral EC public key and | |
5836 * the SSL server's (long-term) EC private key. The resulting | |
5837 * shared secret is treated in the same way as Fortezza's Ks, | |
5838 * i.e., it is used to wrap the wrapping key. To facilitate | |
5839 * unwrapping in ssl_UnwrapWrappingKey, we also store all | |
5840 * relevant info about the ephemeral EC public key in | |
5841 * wswk.wrappedSymmetricWrappingkey and lay it out as | |
5842 * described in the ECCWrappedKeyInfo structure. | |
5843 */ | |
5844 PORT_Assert(svrPubKey->keyType == ecKey); | |
5845 if (svrPubKey->keyType != ecKey) { | |
5846 /* something is wrong in sslsecur.c if this isn't an ecKey */ | |
5847 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
5848 rv = SECFailure; | |
5849 goto ec_cleanup; | |
5850 } | |
5851 | |
5852 privWrapKey = SECKEY_CreateECPrivateKey( | |
5853 &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL); | |
5854 if ((privWrapKey == NULL) || (pubWrapKey == NULL)) { | |
5855 rv = SECFailure; | |
5856 goto ec_cleanup; | |
5857 } | |
5858 | |
5859 /* Set the key size in bits */ | |
5860 if (pubWrapKey->u.ec.size == 0) { | |
5861 pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey); | |
5862 } | |
5863 | |
5864 PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len + | |
5865 pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN); | |
5866 if (pubWrapKey->u.ec.DEREncodedParams.len + | |
5867 pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) { | |
5868 PORT_SetError(SEC_ERROR_INVALID_KEY); | |
5869 rv = SECFailure; | |
5870 goto ec_cleanup; | |
5871 } | |
5872 | |
5873 /* Derive Ks using ECDH */ | |
5874 Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL, | |
5875 NULL, CKM_ECDH1_DERIVE, masterWrapMech, | |
5876 CKA_DERIVE, 0, CKD_NULL, NULL, NULL); | |
5877 if (Ks == NULL) { | |
5878 rv = SECFailure; | |
5879 goto ec_cleanup; | |
5880 } | |
5881 | |
5882 ecWrapped = (ECCWrappedKeyInfo *) (wswk.wrappedSymmetricWrappingkey); | |
5883 ecWrapped->size = pubWrapKey->u.ec.size; | |
5884 ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len; | |
5885 PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data, | |
5886 pubWrapKey->u.ec.DEREncodedParams.len); | |
5887 | |
5888 ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len; | |
5889 PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen, | |
5890 pubWrapKey->u.ec.publicValue.data, | |
5891 pubWrapKey->u.ec.publicValue.len); | |
5892 | |
5893 wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN - | |
5894 (ecWrapped->encodedParamLen + ecWrapped->pubValueLen); | |
5895 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + | |
5896 ecWrapped->pubValueLen; | |
5897 | |
5898 /* wrap symmetricWrapping key with the local Ks */ | |
5899 rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks, | |
5900 unwrappedWrappingKey, &wrappedKey); | |
5901 | |
5902 if (rv != SECSuccess) { | |
5903 goto ec_cleanup; | |
5904 } | |
5905 | |
5906 /* Write down the length of wrapped key in the buffer | |
5907 * wswk.wrappedSymmetricWrappingkey at the appropriate offset | |
5908 */ | |
5909 ecWrapped->wrappedKeyLen = wrappedKey.len; | |
5910 | |
5911 ec_cleanup: | |
5912 if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey); | |
5913 if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey); | |
5914 if (Ks) PK11_FreeSymKey(Ks); | |
5915 asymWrapMechanism = masterWrapMech; | |
5916 break; | |
5917 #endif /* NSS_ENABLE_ECC */ | |
5918 | |
5919 default: | |
5920 rv = SECFailure; | |
5921 break; | |
5922 } | |
5923 | |
5924 if (rv != SECSuccess) { | |
5925 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
5926 goto loser; | |
5927 } | |
5928 | |
5929 PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM); | |
5930 | |
5931 wswk.symWrapMechanism = masterWrapMech; | |
5932 wswk.symWrapMechIndex = symWrapMechIndex; | |
5933 wswk.asymWrapMechanism = asymWrapMechanism; | |
5934 wswk.exchKeyType = exchKeyType; | |
5935 wswk.wrappedSymKeyLen = wrappedKey.len; | |
5936 | |
5937 /* put it on disk. */ | |
5938 /* If the wrapping key for this KEA type has already been set, | |
5939 * then abandon the value we just computed and | |
5940 * use the one we got from the disk. | |
5941 */ | |
5942 if (ssl_SetWrappingKey(&wswk)) { | |
5943 /* somebody beat us to it. The original contents of our wswk | |
5944 * has been replaced with the content on disk. Now, discard | |
5945 * the key we just created and unwrap this new one. | |
5946 */ | |
5947 PK11_FreeSymKey(unwrappedWrappingKey); | |
5948 | |
5949 unwrappedWrappingKey = | |
5950 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, | |
5951 masterWrapMech, pwArg); | |
5952 } | |
5953 | |
5954 install: | |
5955 if (unwrappedWrappingKey) { | |
5956 *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey); | |
5957 } | |
5958 | |
5959 loser: | |
5960 done: | |
5961 PZ_Unlock(symWrapKeysLock); | |
5962 return unwrappedWrappingKey; | |
5963 } | |
5964 | |
5965 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2| | |
5966 * bytes to |out|. */ | |
5967 static void | |
5968 hexEncode(char *out, const unsigned char *in, unsigned int length) | |
5969 { | |
5970 static const char hextable[] = "0123456789abcdef"; | |
5971 unsigned int i; | |
5972 | |
5973 for (i = 0; i < length; i++) { | |
5974 *(out++) = hextable[in[i] >> 4]; | |
5975 *(out++) = hextable[in[i] & 15]; | |
5976 } | |
5977 } | |
5978 | |
5979 /* Called from ssl3_SendClientKeyExchange(). */ | |
5980 /* Presently, this always uses PKCS11. There is no bypass for this. */ | |
5981 static SECStatus | |
5982 sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) | |
5983 { | |
5984 PK11SymKey * pms = NULL; | |
5985 SECStatus rv = SECFailure; | |
5986 SECItem enc_pms = {siBuffer, NULL, 0}; | |
5987 PRBool isTLS; | |
5988 | |
5989 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
5990 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
5991 | |
5992 /* Generate the pre-master secret ... */ | |
5993 ssl_GetSpecWriteLock(ss); | |
5994 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
5995 | |
5996 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL); | |
5997 ssl_ReleaseSpecWriteLock(ss); | |
5998 if (pms == NULL) { | |
5999 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
6000 goto loser; | |
6001 } | |
6002 | |
6003 /* Get the wrapped (encrypted) pre-master secret, enc_pms */ | |
6004 enc_pms.len = SECKEY_PublicKeyStrength(svrPubKey); | |
6005 enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len); | |
6006 if (enc_pms.data == NULL) { | |
6007 goto loser; /* err set by PORT_Alloc */ | |
6008 } | |
6009 | |
6010 /* wrap pre-master secret in server's public key. */ | |
6011 rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms); | |
6012 if (rv != SECSuccess) { | |
6013 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
6014 goto loser; | |
6015 } | |
6016 | |
6017 if (ssl_keylog_iob) { | |
6018 SECStatus extractRV = PK11_ExtractKeyValue(pms); | |
6019 if (extractRV == SECSuccess) { | |
6020 SECItem * keyData = PK11_GetKeyData(pms); | |
6021 if (keyData && keyData->data && keyData->len) { | |
6022 #ifdef TRACE | |
6023 if (ssl_trace >= 100) { | |
6024 ssl_PrintBuf(ss, "Pre-Master Secret", | |
6025 keyData->data, keyData->len); | |
6026 } | |
6027 #endif | |
6028 if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) { | |
6029 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ | |
6030 | |
6031 /* There could be multiple, concurrent writers to the | |
6032 * keylog, so we have to do everything in a single call to | |
6033 * fwrite. */ | |
6034 char buf[4 + 8*2 + 1 + 48*2 + 1]; | |
6035 | |
6036 strcpy(buf, "RSA "); | |
6037 hexEncode(buf + 4, enc_pms.data, 8); | |
6038 buf[20] = ' '; | |
6039 hexEncode(buf + 21, keyData->data, 48); | |
6040 buf[sizeof(buf) - 1] = '\n'; | |
6041 | |
6042 fwrite(buf, sizeof(buf), 1, ssl_keylog_iob); | |
6043 fflush(ssl_keylog_iob); | |
6044 } | |
6045 } | |
6046 } | |
6047 } | |
6048 | |
6049 rv = ssl3_InitPendingCipherSpec(ss, pms); | |
6050 PK11_FreeSymKey(pms); pms = NULL; | |
6051 | |
6052 if (rv != SECSuccess) { | |
6053 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
6054 goto loser; | |
6055 } | |
6056 | |
6057 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, | |
6058 isTLS ? enc_pms.len + 2 : enc_pms.len); | |
6059 if (rv != SECSuccess) { | |
6060 goto loser; /* err set by ssl3_AppendHandshake* */ | |
6061 } | |
6062 if (isTLS) { | |
6063 rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2); | |
6064 } else { | |
6065 rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len); | |
6066 } | |
6067 if (rv != SECSuccess) { | |
6068 goto loser; /* err set by ssl3_AppendHandshake* */ | |
6069 } | |
6070 | |
6071 rv = SECSuccess; | |
6072 | |
6073 loser: | |
6074 if (enc_pms.data != NULL) { | |
6075 PORT_Free(enc_pms.data); | |
6076 } | |
6077 if (pms != NULL) { | |
6078 PK11_FreeSymKey(pms); | |
6079 } | |
6080 return rv; | |
6081 } | |
6082 | |
6083 /* Called from ssl3_SendClientKeyExchange(). */ | |
6084 /* Presently, this always uses PKCS11. There is no bypass for this. */ | |
6085 static SECStatus | |
6086 sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) | |
6087 { | |
6088 PK11SymKey * pms = NULL; | |
6089 SECStatus rv = SECFailure; | |
6090 PRBool isTLS; | |
6091 CK_MECHANISM_TYPE target; | |
6092 | |
6093 SECKEYDHParams dhParam; /* DH parameters */ | |
6094 SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ | |
6095 SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */ | |
6096 | |
6097 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
6098 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
6099 | |
6100 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
6101 | |
6102 /* Copy DH parameters from server key */ | |
6103 | |
6104 if (svrPubKey->keyType != dhKey) { | |
6105 PORT_SetError(SEC_ERROR_BAD_KEY); | |
6106 goto loser; | |
6107 } | |
6108 dhParam.prime.data = svrPubKey->u.dh.prime.data; | |
6109 dhParam.prime.len = svrPubKey->u.dh.prime.len; | |
6110 dhParam.base.data = svrPubKey->u.dh.base.data; | |
6111 dhParam.base.len = svrPubKey->u.dh.base.len; | |
6112 | |
6113 /* Generate ephemeral DH keypair */ | |
6114 privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL); | |
6115 if (!privKey || !pubKey) { | |
6116 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); | |
6117 rv = SECFailure; | |
6118 goto loser; | |
6119 } | |
6120 PRINT_BUF(50, (ss, "DH public value:", | |
6121 pubKey->u.dh.publicValue.data, | |
6122 pubKey->u.dh.publicValue.len)); | |
6123 | |
6124 if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH; | |
6125 else target = CKM_SSL3_MASTER_KEY_DERIVE_DH; | |
6126 | |
6127 /* Determine the PMS */ | |
6128 | |
6129 pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL, | |
6130 CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL); | |
6131 | |
6132 if (pms == NULL) { | |
6133 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
6134 goto loser; | |
6135 } | |
6136 | |
6137 SECKEY_DestroyPrivateKey(privKey); | |
6138 privKey = NULL; | |
6139 | |
6140 rv = ssl3_InitPendingCipherSpec(ss, pms); | |
6141 PK11_FreeSymKey(pms); pms = NULL; | |
6142 | |
6143 if (rv != SECSuccess) { | |
6144 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
6145 goto loser; | |
6146 } | |
6147 | |
6148 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, | |
6149 pubKey->u.dh.publicValue.len + 2); | |
6150 if (rv != SECSuccess) { | |
6151 goto loser; /* err set by ssl3_AppendHandshake* */ | |
6152 } | |
6153 rv = ssl3_AppendHandshakeVariable(ss, | |
6154 pubKey->u.dh.publicValue.data, | |
6155 pubKey->u.dh.publicValue.len, 2); | |
6156 SECKEY_DestroyPublicKey(pubKey); | |
6157 pubKey = NULL; | |
6158 | |
6159 if (rv != SECSuccess) { | |
6160 goto loser; /* err set by ssl3_AppendHandshake* */ | |
6161 } | |
6162 | |
6163 rv = SECSuccess; | |
6164 | |
6165 | |
6166 loser: | |
6167 | |
6168 if(pms) PK11_FreeSymKey(pms); | |
6169 if(privKey) SECKEY_DestroyPrivateKey(privKey); | |
6170 if(pubKey) SECKEY_DestroyPublicKey(pubKey); | |
6171 return rv; | |
6172 } | |
6173 | |
6174 | |
6175 | |
6176 | |
6177 | |
6178 /* Called from ssl3_HandleServerHelloDone(). */ | |
6179 static SECStatus | |
6180 ssl3_SendClientKeyExchange(sslSocket *ss) | |
6181 { | |
6182 SECKEYPublicKey * serverKey = NULL; | |
6183 SECStatus rv = SECFailure; | |
6184 PRBool isTLS; | |
6185 | |
6186 SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake", | |
6187 SSL_GETPID(), ss->fd)); | |
6188 | |
6189 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
6190 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
6191 | |
6192 if (ss->sec.peerKey == NULL) { | |
6193 serverKey = CERT_ExtractPublicKey(ss->sec.peerCert); | |
6194 if (serverKey == NULL) { | |
6195 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); | |
6196 return SECFailure; | |
6197 } | |
6198 } else { | |
6199 serverKey = ss->sec.peerKey; | |
6200 ss->sec.peerKey = NULL; /* we're done with it now */ | |
6201 } | |
6202 | |
6203 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
6204 /* enforce limits on kea key sizes. */ | |
6205 if (ss->ssl3.hs.kea_def->is_limited) { | |
6206 int keyLen = SECKEY_PublicKeyStrength(serverKey); /* bytes */ | |
6207 | |
6208 if (keyLen * BPB > ss->ssl3.hs.kea_def->key_size_limit) { | |
6209 if (isTLS) | |
6210 (void)SSL3_SendAlert(ss, alert_fatal, export_restriction); | |
6211 else | |
6212 (void)ssl3_HandshakeFailure(ss); | |
6213 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); | |
6214 goto loser; | |
6215 } | |
6216 } | |
6217 | |
6218 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; | |
6219 ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey); | |
6220 | |
6221 switch (ss->ssl3.hs.kea_def->exchKeyType) { | |
6222 case kt_rsa: | |
6223 rv = sendRSAClientKeyExchange(ss, serverKey); | |
6224 break; | |
6225 | |
6226 case kt_dh: | |
6227 rv = sendDHClientKeyExchange(ss, serverKey); | |
6228 break; | |
6229 | |
6230 #ifdef NSS_ENABLE_ECC | |
6231 case kt_ecdh: | |
6232 rv = ssl3_SendECDHClientKeyExchange(ss, serverKey); | |
6233 break; | |
6234 #endif /* NSS_ENABLE_ECC */ | |
6235 | |
6236 default: | |
6237 /* got an unknown or unsupported Key Exchange Algorithm. */ | |
6238 SEND_ALERT | |
6239 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); | |
6240 break; | |
6241 } | |
6242 | |
6243 SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange", | |
6244 SSL_GETPID(), ss->fd)); | |
6245 | |
6246 loser: | |
6247 if (serverKey) | |
6248 SECKEY_DestroyPublicKey(serverKey); | |
6249 return rv; /* err code already set. */ | |
6250 } | |
6251 | |
6252 /* Called from ssl3_HandleServerHelloDone(). */ | |
6253 static SECStatus | |
6254 ssl3_SendCertificateVerify(sslSocket *ss) | |
6255 { | |
6256 SECStatus rv = SECFailure; | |
6257 PRBool isTLS; | |
6258 PRBool isTLS12; | |
6259 SECItem buf = {siBuffer, NULL, 0}; | |
6260 SSL3Hashes hashes; | |
6261 KeyType keyType; | |
6262 unsigned int len; | |
6263 SSL3SignatureAndHashAlgorithm sigAndHash; | |
6264 | |
6265 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
6266 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
6267 | |
6268 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake", | |
6269 SSL_GETPID(), ss->fd)); | |
6270 | |
6271 ssl_GetSpecReadLock(ss); | |
6272 if (ss->ssl3.hs.hashType == handshake_hash_single && | |
6273 ss->ssl3.hs.backupHash) { | |
6274 rv = ssl3_ComputeBackupHandshakeHashes(ss, &hashes); | |
6275 PORT_Assert(!ss->ssl3.hs.backupHash); | |
6276 } else { | |
6277 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0); | |
6278 } | |
6279 ssl_ReleaseSpecReadLock(ss); | |
6280 if (rv != SECSuccess) { | |
6281 goto done; /* err code was set by ssl3_ComputeHandshakeHashes */ | |
6282 } | |
6283 | |
6284 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
6285 isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
6286 if (ss->ssl3.platformClientKey) { | |
6287 #ifdef NSS_PLATFORM_CLIENT_AUTH | |
6288 keyType = CERT_GetCertKeyType( | |
6289 &ss->ssl3.clientCertificate->subjectPublicKeyInfo); | |
6290 rv = ssl3_PlatformSignHashes( | |
6291 &hashes, ss->ssl3.platformClientKey, &buf, isTLS, keyType); | |
6292 ssl_FreePlatformKey(ss->ssl3.platformClientKey); | |
6293 ss->ssl3.platformClientKey = (PlatformKey)NULL; | |
6294 #endif /* NSS_PLATFORM_CLIENT_AUTH */ | |
6295 } else { | |
6296 keyType = ss->ssl3.clientPrivateKey->keyType; | |
6297 rv = ssl3_SignHashes(&hashes, ss->ssl3.clientPrivateKey, &buf, isTLS); | |
6298 if (rv == SECSuccess) { | |
6299 PK11SlotInfo * slot; | |
6300 sslSessionID * sid = ss->sec.ci.sid; | |
6301 | |
6302 /* Remember the info about the slot that did the signing. | |
6303 ** Later, when doing an SSL restart handshake, verify this. | |
6304 ** These calls are mere accessors, and can't fail. | |
6305 */ | |
6306 slot = PK11_GetSlotFromPrivateKey(ss->ssl3.clientPrivateKey); | |
6307 sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot); | |
6308 sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot); | |
6309 sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot); | |
6310 sid->u.ssl3.clAuthValid = PR_TRUE; | |
6311 PK11_FreeSlot(slot); | |
6312 } | |
6313 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); | |
6314 ss->ssl3.clientPrivateKey = NULL; | |
6315 } | |
6316 if (rv != SECSuccess) { | |
6317 goto done; /* err code was set by ssl3_SignHashes */ | |
6318 } | |
6319 | |
6320 len = buf.len + 2 + (isTLS12 ? 2 : 0); | |
6321 | |
6322 rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len); | |
6323 if (rv != SECSuccess) { | |
6324 goto done; /* error code set by AppendHandshake */ | |
6325 } | |
6326 if (isTLS12) { | |
6327 rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType, | |
6328 &sigAndHash.sigAlg); | |
6329 if (rv != SECSuccess) { | |
6330 goto done; | |
6331 } | |
6332 sigAndHash.hashAlg = hashes.hashAlg; | |
6333 | |
6334 rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); | |
6335 if (rv != SECSuccess) { | |
6336 goto done; /* err set by AppendHandshake. */ | |
6337 } | |
6338 } | |
6339 rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2); | |
6340 if (rv != SECSuccess) { | |
6341 goto done; /* error code set by AppendHandshake */ | |
6342 } | |
6343 | |
6344 done: | |
6345 if (buf.data) | |
6346 PORT_Free(buf.data); | |
6347 return rv; | |
6348 } | |
6349 | |
6350 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete | |
6351 * ssl3 ServerHello message. | |
6352 * Caller must hold Handshake and RecvBuf locks. | |
6353 */ | |
6354 static SECStatus | |
6355 ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
6356 { | |
6357 sslSessionID *sid = ss->sec.ci.sid; | |
6358 PRInt32 temp; /* allow for consume number failure */ | |
6359 PRBool suite_found = PR_FALSE; | |
6360 int i; | |
6361 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; | |
6362 SECStatus rv; | |
6363 SECItem sidBytes = {siBuffer, NULL, 0}; | |
6364 PRBool sid_match; | |
6365 PRBool isTLS = PR_FALSE; | |
6366 SSL3AlertDescription desc = illegal_parameter; | |
6367 SSL3ProtocolVersion version; | |
6368 | |
6369 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake", | |
6370 SSL_GETPID(), ss->fd)); | |
6371 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
6372 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
6373 PORT_Assert( ss->ssl3.initialized ); | |
6374 | |
6375 if (ss->ssl3.hs.ws != wait_server_hello) { | |
6376 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO; | |
6377 desc = unexpected_message; | |
6378 goto alert_loser; | |
6379 } | |
6380 | |
6381 /* clean up anything left from previous handshake. */ | |
6382 if (ss->ssl3.clientCertChain != NULL) { | |
6383 CERT_DestroyCertificateList(ss->ssl3.clientCertChain); | |
6384 ss->ssl3.clientCertChain = NULL; | |
6385 } | |
6386 if (ss->ssl3.clientCertificate != NULL) { | |
6387 CERT_DestroyCertificate(ss->ssl3.clientCertificate); | |
6388 ss->ssl3.clientCertificate = NULL; | |
6389 } | |
6390 if (ss->ssl3.clientPrivateKey != NULL) { | |
6391 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); | |
6392 ss->ssl3.clientPrivateKey = NULL; | |
6393 } | |
6394 #ifdef NSS_PLATFORM_CLIENT_AUTH | |
6395 if (ss->ssl3.platformClientKey) { | |
6396 ssl_FreePlatformKey(ss->ssl3.platformClientKey); | |
6397 ss->ssl3.platformClientKey = (PlatformKey)NULL; | |
6398 } | |
6399 #endif /* NSS_PLATFORM_CLIENT_AUTH */ | |
6400 | |
6401 if (ss->ssl3.channelID != NULL) { | |
6402 SECKEY_DestroyPrivateKey(ss->ssl3.channelID); | |
6403 ss->ssl3.channelID = NULL; | |
6404 } | |
6405 if (ss->ssl3.channelIDPub != NULL) { | |
6406 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub); | |
6407 ss->ssl3.channelIDPub = NULL; | |
6408 } | |
6409 | |
6410 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); | |
6411 if (temp < 0) { | |
6412 goto loser; /* alert has been sent */ | |
6413 } | |
6414 version = (SSL3ProtocolVersion)temp; | |
6415 | |
6416 if (IS_DTLS(ss)) { | |
6417 /* RFC 4347 required that you verify that the server versions | |
6418 * match (Section 4.2.1) in the HelloVerifyRequest and the | |
6419 * ServerHello. | |
6420 * | |
6421 * RFC 6347 suggests (SHOULD) that servers always use 1.0 | |
6422 * in HelloVerifyRequest and allows the versions not to match, | |
6423 * especially when 1.2 is being negotiated. | |
6424 * | |
6425 * Therefore we do not check for matching here. | |
6426 */ | |
6427 version = dtls_DTLSVersionToTLSVersion(version); | |
6428 if (version == 0) { /* Insane version number */ | |
6429 goto alert_loser; | |
6430 } | |
6431 } | |
6432 | |
6433 rv = ssl3_NegotiateVersion(ss, version, PR_FALSE); | |
6434 if (rv != SECSuccess) { | |
6435 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version | |
6436 : handshake_failure; | |
6437 errCode = SSL_ERROR_NO_CYPHER_OVERLAP; | |
6438 goto alert_loser; | |
6439 } | |
6440 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0); | |
6441 | |
6442 rv = ssl3_InitHandshakeHashes(ss); | |
6443 if (rv != SECSuccess) { | |
6444 desc = internal_error; | |
6445 errCode = PORT_GetError(); | |
6446 goto alert_loser; | |
6447 } | |
6448 | |
6449 rv = ssl3_ConsumeHandshake( | |
6450 ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length); | |
6451 if (rv != SECSuccess) { | |
6452 goto loser; /* alert has been sent */ | |
6453 } | |
6454 | |
6455 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); | |
6456 if (rv != SECSuccess) { | |
6457 goto loser; /* alert has been sent */ | |
6458 } | |
6459 if (sidBytes.len > SSL3_SESSIONID_BYTES) { | |
6460 if (isTLS) | |
6461 desc = decode_error; | |
6462 goto alert_loser; /* malformed. */ | |
6463 } | |
6464 | |
6465 /* find selected cipher suite in our list. */ | |
6466 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); | |
6467 if (temp < 0) { | |
6468 goto loser; /* alert has been sent */ | |
6469 } | |
6470 ssl3_config_match_init(ss); | |
6471 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { | |
6472 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; | |
6473 if (temp == suite->cipher_suite) { | |
6474 SSLVersionRange vrange = {ss->version, ss->version}; | |
6475 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) { | |
6476 /* config_match already checks whether the cipher suite is | |
6477 * acceptable for the version, but the check is repeated here | |
6478 * in order to give a more precise error code. */ | |
6479 if (!ssl3_CipherSuiteAllowedForVersionRange(temp, &vrange)) { | |
6480 desc = handshake_failure; | |
6481 errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION; | |
6482 goto alert_loser; | |
6483 } | |
6484 | |
6485 break; /* failure */ | |
6486 } | |
6487 | |
6488 suite_found = PR_TRUE; | |
6489 break; /* success */ | |
6490 } | |
6491 } | |
6492 if (!suite_found) { | |
6493 desc = handshake_failure; | |
6494 errCode = SSL_ERROR_NO_CYPHER_OVERLAP; | |
6495 goto alert_loser; | |
6496 } | |
6497 ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp; | |
6498 ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp); | |
6499 PORT_Assert(ss->ssl3.hs.suite_def); | |
6500 if (!ss->ssl3.hs.suite_def) { | |
6501 PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE); | |
6502 goto loser; /* we don't send alerts for our screw-ups. */ | |
6503 } | |
6504 | |
6505 /* find selected compression method in our list. */ | |
6506 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); | |
6507 if (temp < 0) { | |
6508 goto loser; /* alert has been sent */ | |
6509 } | |
6510 suite_found = PR_FALSE; | |
6511 for (i = 0; i < compressionMethodsCount; i++) { | |
6512 if (temp == compressions[i]) { | |
6513 if (!compressionEnabled(ss, compressions[i])) { | |
6514 break; /* failure */ | |
6515 } | |
6516 suite_found = PR_TRUE; | |
6517 break; /* success */ | |
6518 } | |
6519 } | |
6520 if (!suite_found) { | |
6521 desc = handshake_failure; | |
6522 errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; | |
6523 goto alert_loser; | |
6524 } | |
6525 ss->ssl3.hs.compression = (SSLCompressionMethod)temp; | |
6526 | |
6527 /* Note that if !isTLS and the extra stuff is not extensions, we | |
6528 * do NOT goto alert_loser. | |
6529 * There are some old SSL 3.0 implementations that do send stuff | |
6530 * after the end of the server hello, and we deliberately ignore | |
6531 * such stuff in the interest of maximal interoperability (being | |
6532 * "generous in what you accept"). | |
6533 * Update: Starting in NSS 3.12.6, we handle the renegotiation_info | |
6534 * extension in SSL 3.0. | |
6535 */ | |
6536 if (length != 0) { | |
6537 SECItem extensions; | |
6538 rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length); | |
6539 if (rv != SECSuccess || length != 0) { | |
6540 if (isTLS) | |
6541 goto alert_loser; | |
6542 } else { | |
6543 rv = ssl3_HandleHelloExtensions(ss, &extensions.data, | |
6544 &extensions.len); | |
6545 if (rv != SECSuccess) | |
6546 goto alert_loser; | |
6547 } | |
6548 } | |
6549 if ((ss->opt.requireSafeNegotiation || | |
6550 (ss->firstHsDone && (ss->peerRequestedProtection || | |
6551 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN))) && | |
6552 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { | |
6553 desc = handshake_failure; | |
6554 errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED | |
6555 : SSL_ERROR_UNSAFE_NEGOTIATION; | |
6556 goto alert_loser; | |
6557 } | |
6558 | |
6559 /* Any errors after this point are not "malformed" errors. */ | |
6560 desc = handshake_failure; | |
6561 | |
6562 /* we need to call ssl3_SetupPendingCipherSpec here so we can check the | |
6563 * key exchange algorithm. */ | |
6564 rv = ssl3_SetupPendingCipherSpec(ss); | |
6565 if (rv != SECSuccess) { | |
6566 goto alert_loser; /* error code is set. */ | |
6567 } | |
6568 | |
6569 /* We may or may not have sent a session id, we may get one back or | |
6570 * not and if so it may match the one we sent. | |
6571 * Attempt to restore the master secret to see if this is so... | |
6572 * Don't consider failure to find a matching SID an error. | |
6573 */ | |
6574 sid_match = (PRBool)(sidBytes.len > 0 && | |
6575 sidBytes.len == sid->u.ssl3.sessionIDLength && | |
6576 !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len)); | |
6577 | |
6578 if (sid_match && | |
6579 sid->version == ss->version && | |
6580 sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do { | |
6581 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; | |
6582 | |
6583 SECItem wrappedMS; /* wrapped master secret. */ | |
6584 | |
6585 ss->sec.authAlgorithm = sid->authAlgorithm; | |
6586 ss->sec.authKeyBits = sid->authKeyBits; | |
6587 ss->sec.keaType = sid->keaType; | |
6588 ss->sec.keaKeyBits = sid->keaKeyBits; | |
6589 | |
6590 /* 3 cases here: | |
6591 * a) key is wrapped (implies using PKCS11) | |
6592 * b) key is unwrapped, but we're still using PKCS11 | |
6593 * c) key is unwrapped, and we're bypassing PKCS11. | |
6594 */ | |
6595 if (sid->u.ssl3.keys.msIsWrapped) { | |
6596 PK11SlotInfo *slot; | |
6597 PK11SymKey * wrapKey; /* wrapping key */ | |
6598 CK_FLAGS keyFlags = 0; | |
6599 | |
6600 #ifndef NO_PKCS11_BYPASS | |
6601 if (ss->opt.bypassPKCS11) { | |
6602 /* we cannot restart a non-bypass session in a | |
6603 ** bypass socket. | |
6604 */ | |
6605 break; | |
6606 } | |
6607 #endif | |
6608 /* unwrap master secret with PKCS11 */ | |
6609 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, | |
6610 sid->u.ssl3.masterSlotID); | |
6611 if (slot == NULL) { | |
6612 break; /* not considered an error. */ | |
6613 } | |
6614 if (!PK11_IsPresent(slot)) { | |
6615 PK11_FreeSlot(slot); | |
6616 break; /* not considered an error. */ | |
6617 } | |
6618 wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex, | |
6619 sid->u.ssl3.masterWrapMech, | |
6620 sid->u.ssl3.masterWrapSeries, | |
6621 ss->pkcs11PinArg); | |
6622 PK11_FreeSlot(slot); | |
6623 if (wrapKey == NULL) { | |
6624 break; /* not considered an error. */ | |
6625 } | |
6626 | |
6627 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ | |
6628 keyFlags = CKF_SIGN | CKF_VERIFY; | |
6629 } | |
6630 | |
6631 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; | |
6632 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; | |
6633 pwSpec->master_secret = | |
6634 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, | |
6635 NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, | |
6636 CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); | |
6637 errCode = PORT_GetError(); | |
6638 PK11_FreeSymKey(wrapKey); | |
6639 if (pwSpec->master_secret == NULL) { | |
6640 break; /* errorCode set just after call to UnwrapSymKey. */ | |
6641 } | |
6642 #ifndef NO_PKCS11_BYPASS | |
6643 } else if (ss->opt.bypassPKCS11) { | |
6644 /* MS is not wrapped */ | |
6645 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; | |
6646 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; | |
6647 memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); | |
6648 pwSpec->msItem.data = pwSpec->raw_master_secret; | |
6649 pwSpec->msItem.len = wrappedMS.len; | |
6650 #endif | |
6651 } else { | |
6652 /* We CAN restart a bypass session in a non-bypass socket. */ | |
6653 /* need to import the raw master secret to session object */ | |
6654 PK11SlotInfo *slot = PK11_GetInternalSlot(); | |
6655 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; | |
6656 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; | |
6657 pwSpec->master_secret = | |
6658 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, | |
6659 PK11_OriginUnwrap, CKA_ENCRYPT, | |
6660 &wrappedMS, NULL); | |
6661 PK11_FreeSlot(slot); | |
6662 if (pwSpec->master_secret == NULL) { | |
6663 break; | |
6664 } | |
6665 } | |
6666 | |
6667 /* Got a Match */ | |
6668 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_hits ); | |
6669 | |
6670 /* If we sent a session ticket, then this is a stateless resume. */ | |
6671 if (ss->xtnData.sentSessionTicketInClientHello) | |
6672 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_stateless_resumes ); | |
6673 | |
6674 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) | |
6675 ss->ssl3.hs.ws = wait_new_session_ticket; | |
6676 else | |
6677 ss->ssl3.hs.ws = wait_change_cipher; | |
6678 | |
6679 ss->ssl3.hs.isResuming = PR_TRUE; | |
6680 | |
6681 /* copy the peer cert from the SID */ | |
6682 if (sid->peerCert != NULL) { | |
6683 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); | |
6684 ssl3_CopyPeerCertsFromSID(ss, sid); | |
6685 } | |
6686 | |
6687 /* NULL value for PMS signifies re-use of the old MS */ | |
6688 rv = ssl3_InitPendingCipherSpec(ss, NULL); | |
6689 if (rv != SECSuccess) { | |
6690 goto alert_loser; /* err code was set */ | |
6691 } | |
6692 goto winner; | |
6693 } while (0); | |
6694 | |
6695 if (sid_match) | |
6696 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_not_ok ); | |
6697 else | |
6698 SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses ); | |
6699 | |
6700 /* throw the old one away */ | |
6701 sid->u.ssl3.keys.resumable = PR_FALSE; | |
6702 if (ss->sec.uncache) | |
6703 (*ss->sec.uncache)(sid); | |
6704 ssl_FreeSID(sid); | |
6705 | |
6706 /* get a new sid */ | |
6707 ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE); | |
6708 if (sid == NULL) { | |
6709 goto alert_loser; /* memory error is set. */ | |
6710 } | |
6711 | |
6712 sid->version = ss->version; | |
6713 sid->u.ssl3.sessionIDLength = sidBytes.len; | |
6714 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len); | |
6715 | |
6716 /* Copy Signed Certificate Timestamps, if any. */ | |
6717 if (ss->xtnData.signedCertTimestamps.data) { | |
6718 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps, | |
6719 &ss->xtnData.signedCertTimestamps); | |
6720 if (rv != SECSuccess) | |
6721 goto loser; | |
6722 } | |
6723 | |
6724 ss->ssl3.hs.isResuming = PR_FALSE; | |
6725 ss->ssl3.hs.ws = wait_server_cert; | |
6726 | |
6727 winner: | |
6728 /* Clean up the temporary pointer to the handshake buffer. */ | |
6729 ss->xtnData.signedCertTimestamps.data = NULL; | |
6730 ss->xtnData.signedCertTimestamps.len = 0; | |
6731 | |
6732 /* If we will need a ChannelID key then we make the callback now. This | |
6733 * allows the handshake to be restarted cleanly if the callback returns | |
6734 * SECWouldBlock. */ | |
6735 if (ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) { | |
6736 rv = ss->getChannelID(ss->getChannelIDArg, ss->fd, | |
6737 &ss->ssl3.channelIDPub, &ss->ssl3.channelID); | |
6738 if (rv == SECWouldBlock) { | |
6739 ssl3_SetAlwaysBlock(ss); | |
6740 return rv; | |
6741 } | |
6742 if (rv != SECSuccess || | |
6743 ss->ssl3.channelIDPub == NULL || | |
6744 ss->ssl3.channelID == NULL) { | |
6745 PORT_SetError(SSL_ERROR_GET_CHANNEL_ID_FAILED); | |
6746 desc = internal_error; | |
6747 goto alert_loser; | |
6748 } | |
6749 } | |
6750 | |
6751 return SECSuccess; | |
6752 | |
6753 alert_loser: | |
6754 (void)SSL3_SendAlert(ss, alert_fatal, desc); | |
6755 | |
6756 loser: | |
6757 /* Clean up the temporary pointer to the handshake buffer. */ | |
6758 ss->xtnData.signedCertTimestamps.data = NULL; | |
6759 ss->xtnData.signedCertTimestamps.len = 0; | |
6760 errCode = ssl_MapLowLevelError(errCode); | |
6761 return SECFailure; | |
6762 } | |
6763 | |
6764 /* ssl3_BigIntGreaterThanOne returns true iff |mpint|, taken as an unsigned, | |
6765 * big-endian integer is > 1 */ | |
6766 static PRBool | |
6767 ssl3_BigIntGreaterThanOne(const SECItem* mpint) { | |
6768 unsigned char firstNonZeroByte = 0; | |
6769 unsigned int i; | |
6770 | |
6771 for (i = 0; i < mpint->len; i++) { | |
6772 if (mpint->data[i]) { | |
6773 firstNonZeroByte = mpint->data[i]; | |
6774 break; | |
6775 } | |
6776 } | |
6777 | |
6778 if (firstNonZeroByte == 0) | |
6779 return PR_FALSE; | |
6780 if (firstNonZeroByte > 1) | |
6781 return PR_TRUE; | |
6782 | |
6783 /* firstNonZeroByte == 1, therefore mpint > 1 iff the first non-zero byte | |
6784 * is followed by another byte. */ | |
6785 return (i < mpint->len - 1); | |
6786 } | |
6787 | |
6788 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete | |
6789 * ssl3 ServerKeyExchange message. | |
6790 * Caller must hold Handshake and RecvBuf locks. | |
6791 */ | |
6792 static SECStatus | |
6793 ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
6794 { | |
6795 PLArenaPool * arena = NULL; | |
6796 SECKEYPublicKey *peerKey = NULL; | |
6797 PRBool isTLS, isTLS12; | |
6798 SECStatus rv; | |
6799 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH; | |
6800 SSL3AlertDescription desc = illegal_parameter; | |
6801 SSL3Hashes hashes; | |
6802 SECItem signature = {siBuffer, NULL, 0}; | |
6803 SSL3SignatureAndHashAlgorithm sigAndHash; | |
6804 | |
6805 sigAndHash.hashAlg = SEC_OID_UNKNOWN; | |
6806 | |
6807 SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake", | |
6808 SSL_GETPID(), ss->fd)); | |
6809 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
6810 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
6811 | |
6812 if (ss->ssl3.hs.ws != wait_server_key && | |
6813 ss->ssl3.hs.ws != wait_server_cert) { | |
6814 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH; | |
6815 desc = unexpected_message; | |
6816 goto alert_loser; | |
6817 } | |
6818 if (ss->sec.peerCert == NULL) { | |
6819 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH; | |
6820 desc = unexpected_message; | |
6821 goto alert_loser; | |
6822 } | |
6823 | |
6824 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); | |
6825 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
6826 | |
6827 switch (ss->ssl3.hs.kea_def->exchKeyType) { | |
6828 | |
6829 case kt_rsa: { | |
6830 SECItem modulus = {siBuffer, NULL, 0}; | |
6831 SECItem exponent = {siBuffer, NULL, 0}; | |
6832 | |
6833 rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length); | |
6834 if (rv != SECSuccess) { | |
6835 goto loser; /* malformed. */ | |
6836 } | |
6837 rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length); | |
6838 if (rv != SECSuccess) { | |
6839 goto loser; /* malformed. */ | |
6840 } | |
6841 if (isTLS12) { | |
6842 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, | |
6843 &sigAndHash); | |
6844 if (rv != SECSuccess) { | |
6845 goto loser; /* malformed or unsupported. */ | |
6846 } | |
6847 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( | |
6848 &sigAndHash, ss->sec.peerCert); | |
6849 if (rv != SECSuccess) { | |
6850 goto loser; | |
6851 } | |
6852 } | |
6853 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); | |
6854 if (rv != SECSuccess) { | |
6855 goto loser; /* malformed. */ | |
6856 } | |
6857 if (length != 0) { | |
6858 if (isTLS) | |
6859 desc = decode_error; | |
6860 goto alert_loser; /* malformed. */ | |
6861 } | |
6862 | |
6863 /* failures after this point are not malformed handshakes. */ | |
6864 /* TLS: send decrypt_error if signature failed. */ | |
6865 desc = isTLS ? decrypt_error : handshake_failure; | |
6866 | |
6867 /* | |
6868 * check to make sure the hash is signed by right guy | |
6869 */ | |
6870 rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, exponent, | |
6871 &ss->ssl3.hs.client_random, | |
6872 &ss->ssl3.hs.server_random, | |
6873 &hashes, ss->opt.bypassPKCS11); | |
6874 if (rv != SECSuccess) { | |
6875 errCode = | |
6876 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
6877 goto alert_loser; | |
6878 } | |
6879 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, | |
6880 isTLS, ss->pkcs11PinArg); | |
6881 if (rv != SECSuccess) { | |
6882 errCode = | |
6883 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
6884 goto alert_loser; | |
6885 } | |
6886 | |
6887 /* | |
6888 * we really need to build a new key here because we can no longer | |
6889 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate | |
6890 * pkcs11 slots and ID's. | |
6891 */ | |
6892 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); | |
6893 if (arena == NULL) { | |
6894 goto no_memory; | |
6895 } | |
6896 | |
6897 peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); | |
6898 if (peerKey == NULL) { | |
6899 PORT_FreeArena(arena, PR_FALSE); | |
6900 goto no_memory; | |
6901 } | |
6902 | |
6903 peerKey->arena = arena; | |
6904 peerKey->keyType = rsaKey; | |
6905 peerKey->pkcs11Slot = NULL; | |
6906 peerKey->pkcs11ID = CK_INVALID_HANDLE; | |
6907 if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus, &modulus) || | |
6908 SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent)) | |
6909 { | |
6910 PORT_FreeArena(arena, PR_FALSE); | |
6911 goto no_memory; | |
6912 } | |
6913 ss->sec.peerKey = peerKey; | |
6914 ss->ssl3.hs.ws = wait_cert_request; | |
6915 return SECSuccess; | |
6916 } | |
6917 | |
6918 case kt_dh: { | |
6919 SECItem dh_p = {siBuffer, NULL, 0}; | |
6920 SECItem dh_g = {siBuffer, NULL, 0}; | |
6921 SECItem dh_Ys = {siBuffer, NULL, 0}; | |
6922 | |
6923 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length); | |
6924 if (rv != SECSuccess) { | |
6925 goto loser; /* malformed. */ | |
6926 } | |
6927 if (dh_p.len < 512/8) { | |
6928 errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY; | |
6929 goto alert_loser; | |
6930 } | |
6931 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length); | |
6932 if (rv != SECSuccess) { | |
6933 goto loser; /* malformed. */ | |
6934 } | |
6935 if (dh_g.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_g)) | |
6936 goto alert_loser; | |
6937 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length); | |
6938 if (rv != SECSuccess) { | |
6939 goto loser; /* malformed. */ | |
6940 } | |
6941 if (dh_Ys.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_Ys)) | |
6942 goto alert_loser; | |
6943 if (isTLS12) { | |
6944 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, | |
6945 &sigAndHash); | |
6946 if (rv != SECSuccess) { | |
6947 goto loser; /* malformed or unsupported. */ | |
6948 } | |
6949 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( | |
6950 &sigAndHash, ss->sec.peerCert); | |
6951 if (rv != SECSuccess) { | |
6952 goto loser; | |
6953 } | |
6954 } | |
6955 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); | |
6956 if (rv != SECSuccess) { | |
6957 goto loser; /* malformed. */ | |
6958 } | |
6959 if (length != 0) { | |
6960 if (isTLS) | |
6961 desc = decode_error; | |
6962 goto alert_loser; /* malformed. */ | |
6963 } | |
6964 | |
6965 PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len)); | |
6966 PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len)); | |
6967 PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len)); | |
6968 | |
6969 /* failures after this point are not malformed handshakes. */ | |
6970 /* TLS: send decrypt_error if signature failed. */ | |
6971 desc = isTLS ? decrypt_error : handshake_failure; | |
6972 | |
6973 /* | |
6974 * check to make sure the hash is signed by right guy | |
6975 */ | |
6976 rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys, | |
6977 &ss->ssl3.hs.client_random, | |
6978 &ss->ssl3.hs.server_random, | |
6979 &hashes, ss->opt.bypassPKCS11); | |
6980 if (rv != SECSuccess) { | |
6981 errCode = | |
6982 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
6983 goto alert_loser; | |
6984 } | |
6985 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, | |
6986 isTLS, ss->pkcs11PinArg); | |
6987 if (rv != SECSuccess) { | |
6988 errCode = | |
6989 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
6990 goto alert_loser; | |
6991 } | |
6992 | |
6993 /* | |
6994 * we really need to build a new key here because we can no longer | |
6995 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate | |
6996 * pkcs11 slots and ID's. | |
6997 */ | |
6998 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); | |
6999 if (arena == NULL) { | |
7000 goto no_memory; | |
7001 } | |
7002 | |
7003 ss->sec.peerKey = peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); | |
7004 if (peerKey == NULL) { | |
7005 goto no_memory; | |
7006 } | |
7007 | |
7008 peerKey->arena = arena; | |
7009 peerKey->keyType = dhKey; | |
7010 peerKey->pkcs11Slot = NULL; | |
7011 peerKey->pkcs11ID = CK_INVALID_HANDLE; | |
7012 | |
7013 if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) || | |
7014 SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) || | |
7015 SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) | |
7016 { | |
7017 PORT_FreeArena(arena, PR_FALSE); | |
7018 goto no_memory; | |
7019 } | |
7020 ss->sec.peerKey = peerKey; | |
7021 ss->ssl3.hs.ws = wait_cert_request; | |
7022 return SECSuccess; | |
7023 } | |
7024 | |
7025 #ifdef NSS_ENABLE_ECC | |
7026 case kt_ecdh: | |
7027 rv = ssl3_HandleECDHServerKeyExchange(ss, b, length); | |
7028 return rv; | |
7029 #endif /* NSS_ENABLE_ECC */ | |
7030 | |
7031 default: | |
7032 desc = handshake_failure; | |
7033 errCode = SEC_ERROR_UNSUPPORTED_KEYALG; | |
7034 break; /* goto alert_loser; */ | |
7035 } | |
7036 | |
7037 alert_loser: | |
7038 (void)SSL3_SendAlert(ss, alert_fatal, desc); | |
7039 loser: | |
7040 PORT_SetError( errCode ); | |
7041 return SECFailure; | |
7042 | |
7043 no_memory: /* no-memory error has already been set. */ | |
7044 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
7045 return SECFailure; | |
7046 } | |
7047 | |
7048 | |
7049 /* | |
7050 * Returns the TLS signature algorithm for the client authentication key and | |
7051 * whether it is an RSA or DSA key that may be able to sign only SHA-1 hashes. | |
7052 */ | |
7053 static SECStatus | |
7054 ssl3_ExtractClientKeyInfo(sslSocket *ss, | |
7055 TLSSignatureAlgorithm *sigAlg, | |
7056 PRBool *preferSha1) | |
7057 { | |
7058 SECStatus rv = SECSuccess; | |
7059 SECKEYPublicKey *pubk; | |
7060 | |
7061 pubk = CERT_ExtractPublicKey(ss->ssl3.clientCertificate); | |
7062 if (pubk == NULL) { | |
7063 rv = SECFailure; | |
7064 goto done; | |
7065 } | |
7066 | |
7067 rv = ssl3_TLSSignatureAlgorithmForKeyType(pubk->keyType, sigAlg); | |
7068 if (rv != SECSuccess) { | |
7069 goto done; | |
7070 } | |
7071 | |
7072 #if defined(NSS_PLATFORM_CLIENT_AUTH) && defined(_WIN32) | |
7073 /* If the key is in CAPI, assume conservatively that the CAPI service | |
7074 * provider may be unable to sign SHA-256 hashes. | |
7075 */ | |
7076 if (ss->ssl3.platformClientKey->dwKeySpec != CERT_NCRYPT_KEY_SPEC) { | |
7077 /* CAPI only supports RSA and DSA signatures, so we don't need to | |
7078 * check the key type. */ | |
7079 *preferSha1 = PR_TRUE; | |
7080 goto done; | |
7081 } | |
7082 #endif /* NSS_PLATFORM_CLIENT_AUTH && _WIN32 */ | |
7083 | |
7084 /* If the key is a 1024-bit RSA or DSA key, assume conservatively that | |
7085 * it may be unable to sign SHA-256 hashes. This is the case for older | |
7086 * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and | |
7087 * older, DSA key size is at most 1024 bits and the hash function must | |
7088 * be SHA-1. | |
7089 */ | |
7090 if (pubk->keyType == rsaKey || pubk->keyType == dsaKey) { | |
7091 *preferSha1 = SECKEY_PublicKeyStrength(pubk) <= 128; | |
7092 } else { | |
7093 *preferSha1 = PR_FALSE; | |
7094 } | |
7095 | |
7096 done: | |
7097 if (pubk) | |
7098 SECKEY_DestroyPublicKey(pubk); | |
7099 return rv; | |
7100 } | |
7101 | |
7102 /* Destroys the backup handshake hash context if we don't need it. Note that | |
7103 * this function selects the hash algorithm for client authentication | |
7104 * signatures; ssl3_SendCertificateVerify uses the presence of the backup hash | |
7105 * to determine whether to use SHA-1 or SHA-256. */ | |
7106 static void | |
7107 ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss, | |
7108 const SECItem *algorithms) | |
7109 { | |
7110 SECStatus rv; | |
7111 TLSSignatureAlgorithm sigAlg; | |
7112 PRBool preferSha1; | |
7113 PRBool supportsSha1 = PR_FALSE; | |
7114 PRBool supportsSha256 = PR_FALSE; | |
7115 PRBool needBackupHash = PR_FALSE; | |
7116 unsigned int i; | |
7117 | |
7118 #ifndef NO_PKCS11_BYPASS | |
7119 /* Backup handshake hash is not supported in PKCS #11 bypass mode. */ | |
7120 if (ss->opt.bypassPKCS11) { | |
7121 PORT_Assert(!ss->ssl3.hs.backupHash); | |
7122 return; | |
7123 } | |
7124 #endif | |
7125 PORT_Assert(ss->ssl3.hs.backupHash); | |
7126 | |
7127 /* Determine the key's signature algorithm and whether it prefers SHA-1. */ | |
7128 rv = ssl3_ExtractClientKeyInfo(ss, &sigAlg, &preferSha1); | |
7129 if (rv != SECSuccess) { | |
7130 goto done; | |
7131 } | |
7132 | |
7133 /* Determine the server's hash support for that signature algorithm. */ | |
7134 for (i = 0; i < algorithms->len; i += 2) { | |
7135 if (algorithms->data[i+1] == sigAlg) { | |
7136 if (algorithms->data[i] == tls_hash_sha1) { | |
7137 supportsSha1 = PR_TRUE; | |
7138 } else if (algorithms->data[i] == tls_hash_sha256) { | |
7139 supportsSha256 = PR_TRUE; | |
7140 } | |
7141 } | |
7142 } | |
7143 | |
7144 /* If either the server does not support SHA-256 or the client key prefers | |
7145 * SHA-1, leave the backup hash. */ | |
7146 if (supportsSha1 && (preferSha1 || !supportsSha256)) { | |
7147 needBackupHash = PR_TRUE; | |
7148 } | |
7149 | |
7150 done: | |
7151 if (!needBackupHash) { | |
7152 PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); | |
7153 ss->ssl3.hs.backupHash = NULL; | |
7154 } | |
7155 } | |
7156 | |
7157 typedef struct dnameNode { | |
7158 struct dnameNode *next; | |
7159 SECItem name; | |
7160 } dnameNode; | |
7161 | |
7162 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete | |
7163 * ssl3 Certificate Request message. | |
7164 * Caller must hold Handshake and RecvBuf locks. | |
7165 */ | |
7166 static SECStatus | |
7167 ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
7168 { | |
7169 PLArenaPool * arena = NULL; | |
7170 dnameNode * node; | |
7171 PRInt32 remaining; | |
7172 PRBool isTLS = PR_FALSE; | |
7173 PRBool isTLS12 = PR_FALSE; | |
7174 int i; | |
7175 int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST; | |
7176 int nnames = 0; | |
7177 SECStatus rv; | |
7178 SSL3AlertDescription desc = illegal_parameter; | |
7179 SECItem cert_types = {siBuffer, NULL, 0}; | |
7180 SECItem algorithms = {siBuffer, NULL, 0}; | |
7181 CERTDistNames ca_list; | |
7182 #ifdef NSS_PLATFORM_CLIENT_AUTH | |
7183 CERTCertList * platform_cert_list = NULL; | |
7184 CERTCertListNode * certNode = NULL; | |
7185 #endif /* NSS_PLATFORM_CLIENT_AUTH */ | |
7186 | |
7187 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake", | |
7188 SSL_GETPID(), ss->fd)); | |
7189 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
7190 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
7191 | |
7192 if (ss->ssl3.hs.ws != wait_cert_request && | |
7193 ss->ssl3.hs.ws != wait_server_key) { | |
7194 desc = unexpected_message; | |
7195 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST; | |
7196 goto alert_loser; | |
7197 } | |
7198 | |
7199 PORT_Assert(ss->ssl3.clientCertChain == NULL); | |
7200 PORT_Assert(ss->ssl3.clientCertificate == NULL); | |
7201 PORT_Assert(ss->ssl3.clientPrivateKey == NULL); | |
7202 PORT_Assert(ss->ssl3.platformClientKey == (PlatformKey)NULL); | |
7203 | |
7204 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); | |
7205 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
7206 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length); | |
7207 if (rv != SECSuccess) | |
7208 goto loser; /* malformed, alert has been sent */ | |
7209 | |
7210 PORT_Assert(!ss->requestedCertTypes); | |
7211 ss->requestedCertTypes = &cert_types; | |
7212 | |
7213 if (isTLS12) { | |
7214 rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length); | |
7215 if (rv != SECSuccess) | |
7216 goto loser; /* malformed, alert has been sent */ | |
7217 /* An empty or odd-length value is invalid. | |
7218 * SignatureAndHashAlgorithm | |
7219 * supported_signature_algorithms<2..2^16-2>; | |
7220 */ | |
7221 if (algorithms.len == 0 || (algorithms.len & 1) != 0) | |
7222 goto alert_loser; | |
7223 } | |
7224 | |
7225 arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); | |
7226 if (arena == NULL) | |
7227 goto no_mem; | |
7228 | |
7229 remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); | |
7230 if (remaining < 0) | |
7231 goto loser; /* malformed, alert has been sent */ | |
7232 | |
7233 if ((PRUint32)remaining > length) | |
7234 goto alert_loser; | |
7235 | |
7236 ca_list.head = node = PORT_ArenaZNew(arena, dnameNode); | |
7237 if (node == NULL) | |
7238 goto no_mem; | |
7239 | |
7240 while (remaining > 0) { | |
7241 PRInt32 len; | |
7242 | |
7243 if (remaining < 2) | |
7244 goto alert_loser; /* malformed */ | |
7245 | |
7246 node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); | |
7247 if (len <= 0) | |
7248 goto loser; /* malformed, alert has been sent */ | |
7249 | |
7250 remaining -= 2; | |
7251 if (remaining < len) | |
7252 goto alert_loser; /* malformed */ | |
7253 | |
7254 node->name.data = b; | |
7255 b += len; | |
7256 length -= len; | |
7257 remaining -= len; | |
7258 nnames++; | |
7259 if (remaining <= 0) | |
7260 break; /* success */ | |
7261 | |
7262 node->next = PORT_ArenaZNew(arena, dnameNode); | |
7263 node = node->next; | |
7264 if (node == NULL) | |
7265 goto no_mem; | |
7266 } | |
7267 | |
7268 ca_list.nnames = nnames; | |
7269 ca_list.names = PORT_ArenaNewArray(arena, SECItem, nnames); | |
7270 if (nnames > 0 && ca_list.names == NULL) | |
7271 goto no_mem; | |
7272 | |
7273 for(i = 0, node = (dnameNode*)ca_list.head; | |
7274 i < nnames; | |
7275 i++, node = node->next) { | |
7276 ca_list.names[i] = node->name; | |
7277 } | |
7278 | |
7279 if (length != 0) | |
7280 goto alert_loser; /* malformed */ | |
7281 | |
7282 desc = no_certificate; | |
7283 ss->ssl3.hs.ws = wait_hello_done; | |
7284 | |
7285 #ifdef NSS_PLATFORM_CLIENT_AUTH | |
7286 if (ss->getPlatformClientAuthData != NULL) { | |
7287 /* XXX Should pass cert_types and algorithms in this call!! */ | |
7288 rv = (SECStatus)(*ss->getPlatformClientAuthData)( | |
7289 ss->getPlatformClientAuthDataArg, | |
7290 ss->fd, &ca_list, | |
7291 &platform_cert_list, | |
7292 (void**)&ss->ssl3.platformClientKey, | |
7293 &ss->ssl3.clientCertificate, | |
7294 &ss->ssl3.clientPrivateKey); | |
7295 } else | |
7296 #endif | |
7297 if (ss->getClientAuthData != NULL) { | |
7298 /* XXX Should pass cert_types and algorithms in this call!! */ | |
7299 rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg, | |
7300 ss->fd, &ca_list, | |
7301 &ss->ssl3.clientCertificate, | |
7302 &ss->ssl3.clientPrivateKey); | |
7303 } else { | |
7304 rv = SECFailure; /* force it to send a no_certificate alert */ | |
7305 } | |
7306 | |
7307 switch (rv) { | |
7308 case SECWouldBlock: /* getClientAuthData has put up a dialog box. */ | |
7309 ssl3_SetAlwaysBlock(ss); | |
7310 break; /* not an error */ | |
7311 | |
7312 case SECSuccess: | |
7313 #ifdef NSS_PLATFORM_CLIENT_AUTH | |
7314 if (!platform_cert_list || CERT_LIST_EMPTY(platform_cert_list) || | |
7315 !ss->ssl3.platformClientKey) { | |
7316 if (platform_cert_list) { | |
7317 CERT_DestroyCertList(platform_cert_list); | |
7318 platform_cert_list = NULL; | |
7319 } | |
7320 if (ss->ssl3.platformClientKey) { | |
7321 ssl_FreePlatformKey(ss->ssl3.platformClientKey); | |
7322 ss->ssl3.platformClientKey = (PlatformKey)NULL; | |
7323 } | |
7324 /* Fall through to NSS client auth check */ | |
7325 } else { | |
7326 certNode = CERT_LIST_HEAD(platform_cert_list); | |
7327 ss->ssl3.clientCertificate = CERT_DupCertificate(certNode->cert); | |
7328 | |
7329 /* Setting ssl3.clientCertChain non-NULL will cause | |
7330 * ssl3_HandleServerHelloDone to call SendCertificate. | |
7331 * Note: clientCertChain should include the EE cert as | |
7332 * clientCertificate is ignored during the actual sending | |
7333 */ | |
7334 ss->ssl3.clientCertChain = | |
7335 hack_NewCertificateListFromCertList(platform_cert_list); | |
7336 CERT_DestroyCertList(platform_cert_list); | |
7337 platform_cert_list = NULL; | |
7338 if (ss->ssl3.clientCertChain == NULL) { | |
7339 if (ss->ssl3.clientCertificate != NULL) { | |
7340 CERT_DestroyCertificate(ss->ssl3.clientCertificate); | |
7341 ss->ssl3.clientCertificate = NULL; | |
7342 } | |
7343 if (ss->ssl3.platformClientKey) { | |
7344 ssl_FreePlatformKey(ss->ssl3.platformClientKey); | |
7345 ss->ssl3.platformClientKey = (PlatformKey)NULL; | |
7346 } | |
7347 goto send_no_certificate; | |
7348 } | |
7349 if (ss->ssl3.hs.hashType == handshake_hash_single) { | |
7350 ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms); | |
7351 } | |
7352 break; /* not an error */ | |
7353 } | |
7354 #endif /* NSS_PLATFORM_CLIENT_AUTH */ | |
7355 /* check what the callback function returned */ | |
7356 if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) { | |
7357 /* we are missing either the key or cert */ | |
7358 if (ss->ssl3.clientCertificate) { | |
7359 /* got a cert, but no key - free it */ | |
7360 CERT_DestroyCertificate(ss->ssl3.clientCertificate); | |
7361 ss->ssl3.clientCertificate = NULL; | |
7362 } | |
7363 if (ss->ssl3.clientPrivateKey) { | |
7364 /* got a key, but no cert - free it */ | |
7365 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); | |
7366 ss->ssl3.clientPrivateKey = NULL; | |
7367 } | |
7368 goto send_no_certificate; | |
7369 } | |
7370 /* Setting ssl3.clientCertChain non-NULL will cause | |
7371 * ssl3_HandleServerHelloDone to call SendCertificate. | |
7372 */ | |
7373 ss->ssl3.clientCertChain = CERT_CertChainFromCert( | |
7374 ss->ssl3.clientCertificate, | |
7375 certUsageSSLClient, PR_FALSE); | |
7376 if (ss->ssl3.clientCertChain == NULL) { | |
7377 CERT_DestroyCertificate(ss->ssl3.clientCertificate); | |
7378 ss->ssl3.clientCertificate = NULL; | |
7379 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); | |
7380 ss->ssl3.clientPrivateKey = NULL; | |
7381 goto send_no_certificate; | |
7382 } | |
7383 if (ss->ssl3.hs.hashType == handshake_hash_single) { | |
7384 ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms); | |
7385 } | |
7386 break; /* not an error */ | |
7387 | |
7388 case SECFailure: | |
7389 default: | |
7390 send_no_certificate: | |
7391 if (isTLS) { | |
7392 ss->ssl3.sendEmptyCert = PR_TRUE; | |
7393 } else { | |
7394 (void)SSL3_SendAlert(ss, alert_warning, no_certificate); | |
7395 } | |
7396 rv = SECSuccess; | |
7397 break; | |
7398 } | |
7399 goto done; | |
7400 | |
7401 no_mem: | |
7402 rv = SECFailure; | |
7403 PORT_SetError(SEC_ERROR_NO_MEMORY); | |
7404 goto done; | |
7405 | |
7406 alert_loser: | |
7407 if (isTLS && desc == illegal_parameter) | |
7408 desc = decode_error; | |
7409 (void)SSL3_SendAlert(ss, alert_fatal, desc); | |
7410 loser: | |
7411 PORT_SetError(errCode); | |
7412 rv = SECFailure; | |
7413 done: | |
7414 ss->requestedCertTypes = NULL; | |
7415 if (arena != NULL) | |
7416 PORT_FreeArena(arena, PR_FALSE); | |
7417 #ifdef NSS_PLATFORM_CLIENT_AUTH | |
7418 if (platform_cert_list) | |
7419 CERT_DestroyCertList(platform_cert_list); | |
7420 #endif | |
7421 return rv; | |
7422 } | |
7423 | |
7424 /* | |
7425 * attempt to restart the handshake after asynchronously handling | |
7426 * a request for the client's certificate. | |
7427 * | |
7428 * inputs: | |
7429 * cert Client cert chosen by application. | |
7430 * Note: ssl takes this reference, and does not bump the | |
7431 * reference count. The caller should drop its reference | |
7432 * without calling CERT_DestroyCert after calling this function. | |
7433 * | |
7434 * key Private key associated with cert. This function takes | |
7435 * ownership of the private key, so the caller should drop its | |
7436 * reference without destroying the private key after this | |
7437 * function returns. | |
7438 * | |
7439 * certChain DER-encoded certs, client cert and its signers. | |
7440 * Note: ssl takes this reference, and does not copy the chain. | |
7441 * The caller should drop its reference without destroying the | |
7442 * chain. SSL will free the chain when it is done with it. | |
7443 * | |
7444 * Return value: XXX | |
7445 * | |
7446 * XXX This code only works on the initial handshake on a connection, XXX | |
7447 * It does not work on a subsequent handshake (redo). | |
7448 * | |
7449 * Caller holds 1stHandshakeLock. | |
7450 */ | |
7451 SECStatus | |
7452 ssl3_RestartHandshakeAfterCertReq(sslSocket * ss, | |
7453 CERTCertificate * cert, | |
7454 SECKEYPrivateKey * key, | |
7455 CERTCertificateList *certChain) | |
7456 { | |
7457 SECStatus rv = SECSuccess; | |
7458 | |
7459 /* XXX This code only works on the initial handshake on a connection, | |
7460 ** XXX It does not work on a subsequent handshake (redo). | |
7461 */ | |
7462 if (ss->handshake != 0) { | |
7463 ss->handshake = ssl_GatherRecord1stHandshake; | |
7464 ss->ssl3.clientCertificate = cert; | |
7465 ss->ssl3.clientPrivateKey = key; | |
7466 ss->ssl3.clientCertChain = certChain; | |
7467 if (!cert || !key || !certChain) { | |
7468 /* we are missing the key, cert, or cert chain */ | |
7469 if (ss->ssl3.clientCertificate) { | |
7470 CERT_DestroyCertificate(ss->ssl3.clientCertificate); | |
7471 ss->ssl3.clientCertificate = NULL; | |
7472 } | |
7473 if (ss->ssl3.clientPrivateKey) { | |
7474 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); | |
7475 ss->ssl3.clientPrivateKey = NULL; | |
7476 } | |
7477 if (ss->ssl3.clientCertChain != NULL) { | |
7478 CERT_DestroyCertificateList(ss->ssl3.clientCertChain); | |
7479 ss->ssl3.clientCertChain = NULL; | |
7480 } | |
7481 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { | |
7482 ss->ssl3.sendEmptyCert = PR_TRUE; | |
7483 } else { | |
7484 (void)SSL3_SendAlert(ss, alert_warning, no_certificate); | |
7485 } | |
7486 } | |
7487 } else { | |
7488 if (cert) { | |
7489 CERT_DestroyCertificate(cert); | |
7490 } | |
7491 if (key) { | |
7492 SECKEY_DestroyPrivateKey(key); | |
7493 } | |
7494 if (certChain) { | |
7495 CERT_DestroyCertificateList(certChain); | |
7496 } | |
7497 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
7498 rv = SECFailure; | |
7499 } | |
7500 return rv; | |
7501 } | |
7502 | |
7503 static SECStatus | |
7504 ssl3_CheckFalseStart(sslSocket *ss) | |
7505 { | |
7506 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
7507 PORT_Assert( !ss->ssl3.hs.authCertificatePending ); | |
7508 PORT_Assert( !ss->ssl3.hs.canFalseStart ); | |
7509 | |
7510 if (!ss->canFalseStartCallback) { | |
7511 SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start", | |
7512 SSL_GETPID(), ss->fd)); | |
7513 } else { | |
7514 PRBool maybeFalseStart; | |
7515 SECStatus rv; | |
7516 | |
7517 /* An attacker can control the selected ciphersuite so we only wish to | |
7518 * do False Start in the case that the selected ciphersuite is | |
7519 * sufficiently strong that the attack can gain no advantage. | |
7520 * Therefore we always require an 80-bit cipher. */ | |
7521 ssl_GetSpecReadLock(ss); | |
7522 maybeFalseStart = ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10; | |
7523 ssl_ReleaseSpecReadLock(ss); | |
7524 | |
7525 if (!maybeFalseStart) { | |
7526 SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher", | |
7527 SSL_GETPID(), ss->fd)); | |
7528 } else { | |
7529 rv = (ss->canFalseStartCallback)(ss->fd, | |
7530 ss->canFalseStartCallbackData, | |
7531 &ss->ssl3.hs.canFalseStart); | |
7532 if (rv == SECSuccess) { | |
7533 SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s", | |
7534 SSL_GETPID(), ss->fd, | |
7535 ss->ssl3.hs.canFalseStart ? "TRUE" : "FALSE")); | |
7536 } else { | |
7537 SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)", | |
7538 SSL_GETPID(), ss->fd, | |
7539 PR_ErrorToName(PR_GetError()))); | |
7540 } | |
7541 return rv; | |
7542 } | |
7543 } | |
7544 | |
7545 ss->ssl3.hs.canFalseStart = PR_FALSE; | |
7546 return SECSuccess; | |
7547 } | |
7548 | |
7549 PRBool | |
7550 ssl3_WaitingForStartOfServerSecondRound(sslSocket *ss) | |
7551 { | |
7552 PRBool result; | |
7553 | |
7554 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
7555 | |
7556 switch (ss->ssl3.hs.ws) { | |
7557 case wait_new_session_ticket: | |
7558 result = PR_TRUE; | |
7559 break; | |
7560 case wait_change_cipher: | |
7561 result = !ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn); | |
7562 break; | |
7563 default: | |
7564 result = PR_FALSE; | |
7565 break; | |
7566 } | |
7567 | |
7568 return result; | |
7569 } | |
7570 | |
7571 static SECStatus ssl3_SendClientSecondRound(sslSocket *ss); | |
7572 | |
7573 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete | |
7574 * ssl3 Server Hello Done message. | |
7575 * Caller must hold Handshake and RecvBuf locks. | |
7576 */ | |
7577 static SECStatus | |
7578 ssl3_HandleServerHelloDone(sslSocket *ss) | |
7579 { | |
7580 SECStatus rv; | |
7581 SSL3WaitState ws = ss->ssl3.hs.ws; | |
7582 | |
7583 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake", | |
7584 SSL_GETPID(), ss->fd)); | |
7585 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
7586 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
7587 | |
7588 if (ws != wait_hello_done && | |
7589 ws != wait_server_cert && | |
7590 ws != wait_server_key && | |
7591 ws != wait_cert_request) { | |
7592 SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
7593 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); | |
7594 return SECFailure; | |
7595 } | |
7596 | |
7597 rv = ssl3_SendClientSecondRound(ss); | |
7598 | |
7599 return rv; | |
7600 } | |
7601 | |
7602 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete. | |
7603 * | |
7604 * Caller must hold Handshake and RecvBuf locks. | |
7605 */ | |
7606 static SECStatus | |
7607 ssl3_SendClientSecondRound(sslSocket *ss) | |
7608 { | |
7609 SECStatus rv; | |
7610 PRBool sendClientCert; | |
7611 | |
7612 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
7613 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
7614 | |
7615 sendClientCert = !ss->ssl3.sendEmptyCert && | |
7616 ss->ssl3.clientCertChain != NULL && | |
7617 (ss->ssl3.platformClientKey || | |
7618 ss->ssl3.clientPrivateKey != NULL); | |
7619 | |
7620 if (!sendClientCert && | |
7621 ss->ssl3.hs.hashType == handshake_hash_single && | |
7622 ss->ssl3.hs.backupHash) { | |
7623 /* Don't need the backup handshake hash. */ | |
7624 PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); | |
7625 ss->ssl3.hs.backupHash = NULL; | |
7626 } | |
7627 | |
7628 /* We must wait for the server's certificate to be authenticated before | |
7629 * sending the client certificate in order to disclosing the client | |
7630 * certificate to an attacker that does not have a valid cert for the | |
7631 * domain we are connecting to. | |
7632 * | |
7633 * XXX: We should do the same for the NPN extension, but for that we | |
7634 * need an option to give the application the ability to leak the NPN | |
7635 * information to get better performance. | |
7636 * | |
7637 * During the initial handshake on a connection, we never send/receive | |
7638 * application data until we have authenticated the server's certificate; | |
7639 * i.e. we have fully authenticated the handshake before using the cipher | |
7640 * specs agreed upon for that handshake. During a renegotiation, we may | |
7641 * continue sending and receiving application data during the handshake | |
7642 * interleaved with the handshake records. If we were to send the client's | |
7643 * second round for a renegotiation before the server's certificate was | |
7644 * authenticated, then the application data sent/received after this point | |
7645 * would be using cipher spec that hadn't been authenticated. By waiting | |
7646 * until the server's certificate has been authenticated during | |
7647 * renegotiations, we ensure that renegotiations have the same property | |
7648 * as initial handshakes; i.e. we have fully authenticated the handshake | |
7649 * before using the cipher specs agreed upon for that handshake for | |
7650 * application data. | |
7651 */ | |
7652 if (ss->ssl3.hs.restartTarget) { | |
7653 PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget"); | |
7654 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
7655 return SECFailure; | |
7656 } | |
7657 if (ss->ssl3.hs.authCertificatePending && | |
7658 (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) { | |
7659 SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because" | |
7660 " certificate authentication is still pending.", | |
7661 SSL_GETPID(), ss->fd)); | |
7662 ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound; | |
7663 return SECWouldBlock; | |
7664 } | |
7665 | |
7666 ssl_GetXmitBufLock(ss); /*******************************/ | |
7667 | |
7668 if (ss->ssl3.sendEmptyCert) { | |
7669 ss->ssl3.sendEmptyCert = PR_FALSE; | |
7670 rv = ssl3_SendEmptyCertificate(ss); | |
7671 /* Don't send verify */ | |
7672 if (rv != SECSuccess) { | |
7673 goto loser; /* error code is set. */ | |
7674 } | |
7675 } else if (sendClientCert) { | |
7676 rv = ssl3_SendCertificate(ss); | |
7677 if (rv != SECSuccess) { | |
7678 goto loser; /* error code is set. */ | |
7679 } | |
7680 } | |
7681 | |
7682 rv = ssl3_SendClientKeyExchange(ss); | |
7683 if (rv != SECSuccess) { | |
7684 goto loser; /* err is set. */ | |
7685 } | |
7686 | |
7687 if (sendClientCert) { | |
7688 rv = ssl3_SendCertificateVerify(ss); | |
7689 if (rv != SECSuccess) { | |
7690 goto loser; /* err is set. */ | |
7691 } | |
7692 } | |
7693 | |
7694 rv = ssl3_SendChangeCipherSpecs(ss); | |
7695 if (rv != SECSuccess) { | |
7696 goto loser; /* err code was set. */ | |
7697 } | |
7698 | |
7699 /* This must be done after we've set ss->ssl3.cwSpec in | |
7700 * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information | |
7701 * from cwSpec. This must be done before we call ssl3_CheckFalseStart | |
7702 * because the false start callback (if any) may need the information from | |
7703 * the functions that depend on this being set. | |
7704 */ | |
7705 ss->enoughFirstHsDone = PR_TRUE; | |
7706 | |
7707 if (!ss->firstHsDone) { | |
7708 /* XXX: If the server's certificate hasn't been authenticated by this | |
7709 * point, then we may be leaking this NPN message to an attacker. | |
7710 */ | |
7711 rv = ssl3_SendNextProto(ss); | |
7712 if (rv != SECSuccess) { | |
7713 goto loser; /* err code was set. */ | |
7714 } | |
7715 } | |
7716 | |
7717 rv = ssl3_SendEncryptedExtensions(ss); | |
7718 if (rv != SECSuccess) { | |
7719 goto loser; /* err code was set. */ | |
7720 } | |
7721 | |
7722 if (!ss->firstHsDone) { | |
7723 if (ss->opt.enableFalseStart) { | |
7724 if (!ss->ssl3.hs.authCertificatePending) { | |
7725 /* When we fix bug 589047, we will need to know whether we are | |
7726 * false starting before we try to flush the client second | |
7727 * round to the network. With that in mind, we purposefully | |
7728 * call ssl3_CheckFalseStart before calling ssl3_SendFinished, | |
7729 * which includes a call to ssl3_FlushHandshake, so that | |
7730 * no application develops a reliance on such flushing being | |
7731 * done before its false start callback is called. | |
7732 */ | |
7733 ssl_ReleaseXmitBufLock(ss); | |
7734 rv = ssl3_CheckFalseStart(ss); | |
7735 ssl_GetXmitBufLock(ss); | |
7736 if (rv != SECSuccess) { | |
7737 goto loser; | |
7738 } | |
7739 } else { | |
7740 /* The certificate authentication and the server's Finished | |
7741 * message are racing each other. If the certificate | |
7742 * authentication wins, then we will try to false start in | |
7743 * ssl3_AuthCertificateComplete. | |
7744 */ | |
7745 SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because" | |
7746 " certificate authentication is still pending.", | |
7747 SSL_GETPID(), ss->fd)); | |
7748 } | |
7749 } | |
7750 } | |
7751 | |
7752 rv = ssl3_SendFinished(ss, 0); | |
7753 if (rv != SECSuccess) { | |
7754 goto loser; /* err code was set. */ | |
7755 } | |
7756 | |
7757 ssl_ReleaseXmitBufLock(ss); /*******************************/ | |
7758 | |
7759 if (!ss->ssl3.hs.isResuming && | |
7760 ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) { | |
7761 /* If we are negotiating ChannelID on a full handshake then we record | |
7762 * the handshake hashes in |sid| at this point. They will be needed in | |
7763 * the event that we resume this session and use ChannelID on the | |
7764 * resumption handshake. */ | |
7765 SSL3Hashes hashes; | |
7766 SECItem *originalHandshakeHash = | |
7767 &ss->sec.ci.sid->u.ssl3.originalHandshakeHash; | |
7768 PORT_Assert(ss->sec.ci.sid->cached == never_cached); | |
7769 | |
7770 ssl_GetSpecReadLock(ss); | |
7771 PORT_Assert(ss->version > SSL_LIBRARY_VERSION_3_0); | |
7772 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0); | |
7773 ssl_ReleaseSpecReadLock(ss); | |
7774 if (rv != SECSuccess) { | |
7775 return rv; | |
7776 } | |
7777 | |
7778 PORT_Assert(originalHandshakeHash->len == 0); | |
7779 originalHandshakeHash->data = PORT_Alloc(hashes.len); | |
7780 if (!originalHandshakeHash->data) | |
7781 return SECFailure; | |
7782 originalHandshakeHash->len = hashes.len; | |
7783 memcpy(originalHandshakeHash->data, hashes.u.raw, hashes.len); | |
7784 } | |
7785 | |
7786 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) | |
7787 ss->ssl3.hs.ws = wait_new_session_ticket; | |
7788 else | |
7789 ss->ssl3.hs.ws = wait_change_cipher; | |
7790 | |
7791 PORT_Assert(ssl3_WaitingForStartOfServerSecondRound(ss)); | |
7792 | |
7793 return SECSuccess; | |
7794 | |
7795 loser: | |
7796 ssl_ReleaseXmitBufLock(ss); | |
7797 return rv; | |
7798 } | |
7799 | |
7800 /* | |
7801 * Routines used by servers | |
7802 */ | |
7803 static SECStatus | |
7804 ssl3_SendHelloRequest(sslSocket *ss) | |
7805 { | |
7806 SECStatus rv; | |
7807 | |
7808 SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(), | |
7809 ss->fd)); | |
7810 | |
7811 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
7812 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); | |
7813 | |
7814 rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0); | |
7815 if (rv != SECSuccess) { | |
7816 return rv; /* err set by AppendHandshake */ | |
7817 } | |
7818 rv = ssl3_FlushHandshake(ss, 0); | |
7819 if (rv != SECSuccess) { | |
7820 return rv; /* error code set by ssl3_FlushHandshake */ | |
7821 } | |
7822 ss->ssl3.hs.ws = wait_client_hello; | |
7823 return SECSuccess; | |
7824 } | |
7825 | |
7826 /* | |
7827 * Called from: | |
7828 * ssl3_HandleClientHello() | |
7829 */ | |
7830 static SECComparison | |
7831 ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2) | |
7832 { | |
7833 if (!name1 != !name2) { | |
7834 return SECLessThan; | |
7835 } | |
7836 if (!name1) { | |
7837 return SECEqual; | |
7838 } | |
7839 if (name1->type != name2->type) { | |
7840 return SECLessThan; | |
7841 } | |
7842 return SECITEM_CompareItem(name1, name2); | |
7843 } | |
7844 | |
7845 /* Sets memory error when returning NULL. | |
7846 * Called from: | |
7847 * ssl3_SendClientHello() | |
7848 * ssl3_HandleServerHello() | |
7849 * ssl3_HandleClientHello() | |
7850 * ssl3_HandleV2ClientHello() | |
7851 */ | |
7852 sslSessionID * | |
7853 ssl3_NewSessionID(sslSocket *ss, PRBool is_server) | |
7854 { | |
7855 sslSessionID *sid; | |
7856 | |
7857 sid = PORT_ZNew(sslSessionID); | |
7858 if (sid == NULL) | |
7859 return sid; | |
7860 | |
7861 if (is_server) { | |
7862 const SECItem * srvName; | |
7863 SECStatus rv = SECSuccess; | |
7864 | |
7865 ssl_GetSpecReadLock(ss); /********************************/ | |
7866 srvName = &ss->ssl3.prSpec->srvVirtName; | |
7867 if (srvName->len && srvName->data) { | |
7868 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName); | |
7869 } | |
7870 ssl_ReleaseSpecReadLock(ss); /************************************/ | |
7871 if (rv != SECSuccess) { | |
7872 PORT_Free(sid); | |
7873 return NULL; | |
7874 } | |
7875 } | |
7876 sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID); | |
7877 sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url); | |
7878 sid->addr = ss->sec.ci.peer; | |
7879 sid->port = ss->sec.ci.port; | |
7880 sid->references = 1; | |
7881 sid->cached = never_cached; | |
7882 sid->version = ss->version; | |
7883 | |
7884 sid->u.ssl3.keys.resumable = PR_TRUE; | |
7885 sid->u.ssl3.policy = SSL_ALLOWED; | |
7886 sid->u.ssl3.clientWriteKey = NULL; | |
7887 sid->u.ssl3.serverWriteKey = NULL; | |
7888 | |
7889 if (is_server) { | |
7890 SECStatus rv; | |
7891 int pid = SSL_GETPID(); | |
7892 | |
7893 sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES; | |
7894 sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff; | |
7895 sid->u.ssl3.sessionID[1] = pid & 0xff; | |
7896 rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2, | |
7897 SSL3_SESSIONID_BYTES -2); | |
7898 if (rv != SECSuccess) { | |
7899 ssl_FreeSID(sid); | |
7900 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); | |
7901 return NULL; | |
7902 } | |
7903 } | |
7904 return sid; | |
7905 } | |
7906 | |
7907 /* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */ | |
7908 static SECStatus | |
7909 ssl3_SendServerHelloSequence(sslSocket *ss) | |
7910 { | |
7911 const ssl3KEADef *kea_def; | |
7912 SECStatus rv; | |
7913 | |
7914 SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence", | |
7915 SSL_GETPID(), ss->fd)); | |
7916 | |
7917 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
7918 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); | |
7919 | |
7920 rv = ssl3_SendServerHello(ss); | |
7921 if (rv != SECSuccess) { | |
7922 return rv; /* err code is set. */ | |
7923 } | |
7924 rv = ssl3_SendCertificate(ss); | |
7925 if (rv != SECSuccess) { | |
7926 return rv; /* error code is set. */ | |
7927 } | |
7928 rv = ssl3_SendCertificateStatus(ss); | |
7929 if (rv != SECSuccess) { | |
7930 return rv; /* error code is set. */ | |
7931 } | |
7932 /* We have to do this after the call to ssl3_SendServerHello, | |
7933 * because kea_def is set up by ssl3_SendServerHello(). | |
7934 */ | |
7935 kea_def = ss->ssl3.hs.kea_def; | |
7936 ss->ssl3.hs.usedStepDownKey = PR_FALSE; | |
7937 | |
7938 if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) { | |
7939 /* see if we can legally use the key in the cert. */ | |
7940 int keyLen; /* bytes */ | |
7941 | |
7942 keyLen = PK11_GetPrivateModulusLen( | |
7943 ss->serverCerts[kea_def->exchKeyType].SERVERKEY); | |
7944 | |
7945 if (keyLen > 0 && | |
7946 keyLen * BPB <= kea_def->key_size_limit ) { | |
7947 /* XXX AND cert is not signing only!! */ | |
7948 /* just fall through and use it. */ | |
7949 } else if (ss->stepDownKeyPair != NULL) { | |
7950 ss->ssl3.hs.usedStepDownKey = PR_TRUE; | |
7951 rv = ssl3_SendServerKeyExchange(ss); | |
7952 if (rv != SECSuccess) { | |
7953 return rv; /* err code was set. */ | |
7954 } | |
7955 } else { | |
7956 #ifndef HACKED_EXPORT_SERVER | |
7957 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); | |
7958 return rv; | |
7959 #endif | |
7960 } | |
7961 #ifdef NSS_ENABLE_ECC | |
7962 } else if ((kea_def->kea == kea_ecdhe_rsa) || | |
7963 (kea_def->kea == kea_ecdhe_ecdsa)) { | |
7964 rv = ssl3_SendServerKeyExchange(ss); | |
7965 if (rv != SECSuccess) { | |
7966 return rv; /* err code was set. */ | |
7967 } | |
7968 #endif /* NSS_ENABLE_ECC */ | |
7969 } | |
7970 | |
7971 if (ss->opt.requestCertificate) { | |
7972 rv = ssl3_SendCertificateRequest(ss); | |
7973 if (rv != SECSuccess) { | |
7974 return rv; /* err code is set. */ | |
7975 } | |
7976 } | |
7977 rv = ssl3_SendServerHelloDone(ss); | |
7978 if (rv != SECSuccess) { | |
7979 return rv; /* err code is set. */ | |
7980 } | |
7981 | |
7982 ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert | |
7983 : wait_client_key; | |
7984 return SECSuccess; | |
7985 } | |
7986 | |
7987 /* An empty TLS Renegotiation Info (RI) extension */ | |
7988 static const PRUint8 emptyRIext[5] = {0xff, 0x01, 0x00, 0x01, 0x00}; | |
7989 | |
7990 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete | |
7991 * ssl3 Client Hello message. | |
7992 * Caller must hold Handshake and RecvBuf locks. | |
7993 */ | |
7994 static SECStatus | |
7995 ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
7996 { | |
7997 sslSessionID * sid = NULL; | |
7998 PRInt32 tmp; | |
7999 unsigned int i; | |
8000 int j; | |
8001 SECStatus rv; | |
8002 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; | |
8003 SSL3AlertDescription desc = illegal_parameter; | |
8004 SSL3AlertLevel level = alert_fatal; | |
8005 SSL3ProtocolVersion version; | |
8006 SECItem sidBytes = {siBuffer, NULL, 0}; | |
8007 SECItem cookieBytes = {siBuffer, NULL, 0}; | |
8008 SECItem suites = {siBuffer, NULL, 0}; | |
8009 SECItem comps = {siBuffer, NULL, 0}; | |
8010 PRBool haveSpecWriteLock = PR_FALSE; | |
8011 PRBool haveXmitBufLock = PR_FALSE; | |
8012 | |
8013 SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake", | |
8014 SSL_GETPID(), ss->fd)); | |
8015 | |
8016 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
8017 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
8018 PORT_Assert( ss->ssl3.initialized ); | |
8019 | |
8020 /* Get peer name of client */ | |
8021 rv = ssl_GetPeerInfo(ss); | |
8022 if (rv != SECSuccess) { | |
8023 return rv; /* error code is set. */ | |
8024 } | |
8025 | |
8026 /* Clearing the handshake pointers so that ssl_Do1stHandshake won't | |
8027 * call ssl2_HandleMessage. | |
8028 * | |
8029 * The issue here is that TLS ordinarily starts out in | |
8030 * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility | |
8031 * code paths. That function zeroes these next pointers. But with DTLS, | |
8032 * we don't even try to do the v2 ClientHello so we skip that function | |
8033 * and need to reset these values here. | |
8034 */ | |
8035 if (IS_DTLS(ss)) { | |
8036 ss->nextHandshake = 0; | |
8037 ss->securityHandshake = 0; | |
8038 } | |
8039 | |
8040 /* We might be starting session renegotiation in which case we should | |
8041 * clear previous state. | |
8042 */ | |
8043 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); | |
8044 ss->statelessResume = PR_FALSE; | |
8045 | |
8046 if ((ss->ssl3.hs.ws != wait_client_hello) && | |
8047 (ss->ssl3.hs.ws != idle_handshake)) { | |
8048 desc = unexpected_message; | |
8049 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; | |
8050 goto alert_loser; | |
8051 } | |
8052 if (ss->ssl3.hs.ws == idle_handshake && | |
8053 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { | |
8054 desc = no_renegotiation; | |
8055 level = alert_warning; | |
8056 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; | |
8057 goto alert_loser; | |
8058 } | |
8059 | |
8060 if (IS_DTLS(ss)) { | |
8061 dtls_RehandshakeCleanup(ss); | |
8062 } | |
8063 | |
8064 tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); | |
8065 if (tmp < 0) | |
8066 goto loser; /* malformed, alert already sent */ | |
8067 | |
8068 /* Translate the version */ | |
8069 if (IS_DTLS(ss)) { | |
8070 ss->clientHelloVersion = version = | |
8071 dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp); | |
8072 } else { | |
8073 ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp; | |
8074 } | |
8075 | |
8076 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); | |
8077 if (rv != SECSuccess) { | |
8078 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version | |
8079 : handshake_failure; | |
8080 errCode = SSL_ERROR_NO_CYPHER_OVERLAP; | |
8081 goto alert_loser; | |
8082 } | |
8083 | |
8084 rv = ssl3_InitHandshakeHashes(ss); | |
8085 if (rv != SECSuccess) { | |
8086 desc = internal_error; | |
8087 errCode = PORT_GetError(); | |
8088 goto alert_loser; | |
8089 } | |
8090 | |
8091 /* grab the client random data. */ | |
8092 rv = ssl3_ConsumeHandshake( | |
8093 ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length); | |
8094 if (rv != SECSuccess) { | |
8095 goto loser; /* malformed */ | |
8096 } | |
8097 | |
8098 /* grab the client's SID, if present. */ | |
8099 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); | |
8100 if (rv != SECSuccess) { | |
8101 goto loser; /* malformed */ | |
8102 } | |
8103 | |
8104 /* grab the client's cookie, if present. */ | |
8105 if (IS_DTLS(ss)) { | |
8106 rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length); | |
8107 if (rv != SECSuccess) { | |
8108 goto loser; /* malformed */ | |
8109 } | |
8110 } | |
8111 | |
8112 /* grab the list of cipher suites. */ | |
8113 rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length); | |
8114 if (rv != SECSuccess) { | |
8115 goto loser; /* malformed */ | |
8116 } | |
8117 | |
8118 /* If the ClientHello version is less than our maximum version, check for a | |
8119 * TLS_FALLBACK_SCSV and reject the connection if found. */ | |
8120 if (ss->vrange.max > ss->clientHelloVersion) { | |
8121 for (i = 0; i + 1 < suites.len; i += 2) { | |
8122 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; | |
8123 if (suite_i != TLS_FALLBACK_SCSV) | |
8124 continue; | |
8125 desc = inappropriate_fallback; | |
8126 errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; | |
8127 goto alert_loser; | |
8128 } | |
8129 } | |
8130 | |
8131 /* grab the list of compression methods. */ | |
8132 rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length); | |
8133 if (rv != SECSuccess) { | |
8134 goto loser; /* malformed */ | |
8135 } | |
8136 | |
8137 desc = handshake_failure; | |
8138 | |
8139 /* Handle TLS hello extensions for SSL3 & TLS. We do not know if | |
8140 * we are restarting a previous session until extensions have been | |
8141 * parsed, since we might have received a SessionTicket extension. | |
8142 * Note: we allow extensions even when negotiating SSL3 for the sake | |
8143 * of interoperability (and backwards compatibility). | |
8144 */ | |
8145 | |
8146 if (length) { | |
8147 /* Get length of hello extensions */ | |
8148 PRInt32 extension_length; | |
8149 extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); | |
8150 if (extension_length < 0) { | |
8151 goto loser; /* alert already sent */ | |
8152 } | |
8153 if (extension_length != length) { | |
8154 ssl3_DecodeError(ss); /* send alert */ | |
8155 goto loser; | |
8156 } | |
8157 rv = ssl3_HandleHelloExtensions(ss, &b, &length); | |
8158 if (rv != SECSuccess) { | |
8159 goto loser; /* malformed */ | |
8160 } | |
8161 } | |
8162 if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { | |
8163 /* If we didn't receive an RI extension, look for the SCSV, | |
8164 * and if found, treat it just like an empty RI extension | |
8165 * by processing a local copy of an empty RI extension. | |
8166 */ | |
8167 for (i = 0; i + 1 < suites.len; i += 2) { | |
8168 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; | |
8169 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { | |
8170 SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext; | |
8171 PRUint32 L2 = sizeof emptyRIext; | |
8172 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2); | |
8173 break; | |
8174 } | |
8175 } | |
8176 } | |
8177 if (ss->firstHsDone && | |
8178 (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN || | |
8179 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) && | |
8180 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { | |
8181 desc = no_renegotiation; | |
8182 level = alert_warning; | |
8183 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; | |
8184 goto alert_loser; | |
8185 } | |
8186 if ((ss->opt.requireSafeNegotiation || | |
8187 (ss->firstHsDone && ss->peerRequestedProtection)) && | |
8188 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { | |
8189 desc = handshake_failure; | |
8190 errCode = SSL_ERROR_UNSAFE_NEGOTIATION; | |
8191 goto alert_loser; | |
8192 } | |
8193 | |
8194 /* We do stateful resumes only if either of the following | |
8195 * conditions are satisfied: (1) the client does not support the | |
8196 * session ticket extension, or (2) the client support the session | |
8197 * ticket extension, but sent an empty ticket. | |
8198 */ | |
8199 if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) || | |
8200 ss->xtnData.emptySessionTicket) { | |
8201 if (sidBytes.len > 0 && !ss->opt.noCache) { | |
8202 SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%0
8x%08x%08x%08x", | |
8203 SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0], | |
8204 ss->sec.ci.peer.pr_s6_addr32[1], | |
8205 ss->sec.ci.peer.pr_s6_addr32[2], | |
8206 ss->sec.ci.peer.pr_s6_addr32[3])); | |
8207 if (ssl_sid_lookup) { | |
8208 sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data, | |
8209 sidBytes.len, ss->dbHandle); | |
8210 } else { | |
8211 errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED; | |
8212 goto loser; | |
8213 } | |
8214 } | |
8215 } else if (ss->statelessResume) { | |
8216 /* Fill in the client's session ID if doing a stateless resume. | |
8217 * (When doing stateless resumes, server echos client's SessionID.) | |
8218 */ | |
8219 sid = ss->sec.ci.sid; | |
8220 PORT_Assert(sid != NULL); /* Should have already been filled in.*/ | |
8221 | |
8222 if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) { | |
8223 sid->u.ssl3.sessionIDLength = sidBytes.len; | |
8224 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, | |
8225 sidBytes.len); | |
8226 sid->u.ssl3.sessionIDLength = sidBytes.len; | |
8227 } else { | |
8228 sid->u.ssl3.sessionIDLength = 0; | |
8229 } | |
8230 ss->sec.ci.sid = NULL; | |
8231 } | |
8232 | |
8233 /* We only send a session ticket extension if the client supports | |
8234 * the extension and we are unable to do either a stateful or | |
8235 * stateless resume. | |
8236 * | |
8237 * TODO: send a session ticket if performing a stateful | |
8238 * resumption. (As per RFC4507, a server may issue a session | |
8239 * ticket while doing a (stateless or stateful) session resume, | |
8240 * but OpenSSL-0.9.8g does not accept session tickets while | |
8241 * resuming.) | |
8242 */ | |
8243 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) { | |
8244 ssl3_RegisterServerHelloExtensionSender(ss, | |
8245 ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn); | |
8246 } | |
8247 | |
8248 if (sid != NULL) { | |
8249 /* We've found a session cache entry for this client. | |
8250 * Now, if we're going to require a client-auth cert, | |
8251 * and we don't already have this client's cert in the session cache, | |
8252 * and this is the first handshake on this connection (not a redo), | |
8253 * then drop this old cache entry and start a new session. | |
8254 */ | |
8255 if ((sid->peerCert == NULL) && ss->opt.requestCertificate && | |
8256 ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || | |
8257 (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) || | |
8258 ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) | |
8259 && !ss->firstHsDone))) { | |
8260 | |
8261 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok ); | |
8262 if (ss->sec.uncache) | |
8263 ss->sec.uncache(sid); | |
8264 ssl_FreeSID(sid); | |
8265 sid = NULL; | |
8266 } | |
8267 } | |
8268 | |
8269 #ifdef NSS_ENABLE_ECC | |
8270 /* Disable any ECC cipher suites for which we have no cert. */ | |
8271 ssl3_FilterECCipherSuitesByServerCerts(ss); | |
8272 #endif | |
8273 | |
8274 if (IS_DTLS(ss)) { | |
8275 ssl3_DisableNonDTLSSuites(ss); | |
8276 } | |
8277 | |
8278 if (!ssl3_HasGCMSupport()) { | |
8279 ssl3_DisableGCMSuites(ss); | |
8280 } | |
8281 | |
8282 #ifdef PARANOID | |
8283 /* Look for a matching cipher suite. */ | |
8284 j = ssl3_config_match_init(ss); | |
8285 if (j <= 0) { /* no ciphers are working/supported by PK11 */ | |
8286 errCode = PORT_GetError(); /* error code is already set. */ | |
8287 goto alert_loser; | |
8288 } | |
8289 #endif | |
8290 | |
8291 /* If we already have a session for this client, be sure to pick the | |
8292 ** same cipher suite and compression method we picked before. | |
8293 ** This is not a loop, despite appearances. | |
8294 */ | |
8295 if (sid) do { | |
8296 ssl3CipherSuiteCfg *suite; | |
8297 #ifdef PARANOID | |
8298 SSLVersionRange vrange = {ss->version, ss->version}; | |
8299 #endif | |
8300 | |
8301 /* Check that the cached compression method is still enabled. */ | |
8302 if (!compressionEnabled(ss, sid->u.ssl3.compression)) | |
8303 break; | |
8304 | |
8305 /* Check that the cached compression method is in the client's list */ | |
8306 for (i = 0; i < comps.len; i++) { | |
8307 if (comps.data[i] == sid->u.ssl3.compression) | |
8308 break; | |
8309 } | |
8310 if (i == comps.len) | |
8311 break; | |
8312 | |
8313 suite = ss->cipherSuites; | |
8314 /* Find the entry for the cipher suite used in the cached session. */ | |
8315 for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) { | |
8316 if (suite->cipher_suite == sid->u.ssl3.cipherSuite) | |
8317 break; | |
8318 } | |
8319 PORT_Assert(j > 0); | |
8320 if (j <= 0) | |
8321 break; | |
8322 #ifdef PARANOID | |
8323 /* Double check that the cached cipher suite is still enabled, | |
8324 * implemented, and allowed by policy. Might have been disabled. | |
8325 * The product policy won't change during the process lifetime. | |
8326 * Implemented ("isPresent") shouldn't change for servers. | |
8327 */ | |
8328 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) | |
8329 break; | |
8330 #else | |
8331 if (!suite->enabled) | |
8332 break; | |
8333 #endif | |
8334 /* Double check that the cached cipher suite is in the client's list */ | |
8335 for (i = 0; i + 1 < suites.len; i += 2) { | |
8336 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; | |
8337 if (suite_i == suite->cipher_suite) { | |
8338 ss->ssl3.hs.cipher_suite = suite->cipher_suite; | |
8339 ss->ssl3.hs.suite_def = | |
8340 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); | |
8341 | |
8342 /* Use the cached compression method. */ | |
8343 ss->ssl3.hs.compression = sid->u.ssl3.compression; | |
8344 goto compression_found; | |
8345 } | |
8346 } | |
8347 } while (0); | |
8348 | |
8349 /* START A NEW SESSION */ | |
8350 | |
8351 #ifndef PARANOID | |
8352 /* Look for a matching cipher suite. */ | |
8353 j = ssl3_config_match_init(ss); | |
8354 if (j <= 0) { /* no ciphers are working/supported by PK11 */ | |
8355 errCode = PORT_GetError(); /* error code is already set. */ | |
8356 goto alert_loser; | |
8357 } | |
8358 #endif | |
8359 | |
8360 /* Select a cipher suite. | |
8361 ** | |
8362 ** NOTE: This suite selection algorithm should be the same as the one in | |
8363 ** ssl3_HandleV2ClientHello(). | |
8364 ** | |
8365 ** If TLS 1.0 is enabled, we could handle the case where the client | |
8366 ** offered TLS 1.1 but offered only export cipher suites by choosing TLS | |
8367 ** 1.0 and selecting one of those export cipher suites. However, a secure | |
8368 ** TLS 1.1 client should not have export cipher suites enabled at all, | |
8369 ** and a TLS 1.1 client should definitely not be offering *only* export | |
8370 ** cipher suites. Therefore, we refuse to negotiate export cipher suites | |
8371 ** with any client that indicates support for TLS 1.1 or higher when we | |
8372 ** (the server) have TLS 1.1 support enabled. | |
8373 */ | |
8374 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { | |
8375 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; | |
8376 SSLVersionRange vrange = {ss->version, ss->version}; | |
8377 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) { | |
8378 continue; | |
8379 } | |
8380 for (i = 0; i + 1 < suites.len; i += 2) { | |
8381 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; | |
8382 if (suite_i == suite->cipher_suite) { | |
8383 ss->ssl3.hs.cipher_suite = suite->cipher_suite; | |
8384 ss->ssl3.hs.suite_def = | |
8385 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); | |
8386 goto suite_found; | |
8387 } | |
8388 } | |
8389 } | |
8390 errCode = SSL_ERROR_NO_CYPHER_OVERLAP; | |
8391 goto alert_loser; | |
8392 | |
8393 suite_found: | |
8394 /* Select a compression algorithm. */ | |
8395 for (i = 0; i < comps.len; i++) { | |
8396 if (!compressionEnabled(ss, comps.data[i])) | |
8397 continue; | |
8398 for (j = 0; j < compressionMethodsCount; j++) { | |
8399 if (comps.data[i] == compressions[j]) { | |
8400 ss->ssl3.hs.compression = | |
8401 (SSLCompressionMethod)compressions[j]; | |
8402 goto compression_found; | |
8403 } | |
8404 } | |
8405 } | |
8406 errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; | |
8407 /* null compression must be supported */ | |
8408 goto alert_loser; | |
8409 | |
8410 compression_found: | |
8411 suites.data = NULL; | |
8412 comps.data = NULL; | |
8413 | |
8414 ss->sec.send = ssl3_SendApplicationData; | |
8415 | |
8416 /* If there are any failures while processing the old sid, | |
8417 * we don't consider them to be errors. Instead, We just behave | |
8418 * as if the client had sent us no sid to begin with, and make a new one. | |
8419 */ | |
8420 if (sid != NULL) do { | |
8421 ssl3CipherSpec *pwSpec; | |
8422 SECItem wrappedMS; /* wrapped key */ | |
8423 | |
8424 if (sid->version != ss->version || | |
8425 sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite || | |
8426 sid->u.ssl3.compression != ss->ssl3.hs.compression) { | |
8427 break; /* not an error */ | |
8428 } | |
8429 | |
8430 if (ss->sec.ci.sid) { | |
8431 if (ss->sec.uncache) | |
8432 ss->sec.uncache(ss->sec.ci.sid); | |
8433 PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ..
. */ | |
8434 if (ss->sec.ci.sid != sid) { | |
8435 ssl_FreeSID(ss->sec.ci.sid); | |
8436 } | |
8437 ss->sec.ci.sid = NULL; | |
8438 } | |
8439 /* we need to resurrect the master secret.... */ | |
8440 | |
8441 ssl_GetSpecWriteLock(ss); haveSpecWriteLock = PR_TRUE; | |
8442 pwSpec = ss->ssl3.pwSpec; | |
8443 if (sid->u.ssl3.keys.msIsWrapped) { | |
8444 PK11SymKey * wrapKey; /* wrapping key */ | |
8445 CK_FLAGS keyFlags = 0; | |
8446 #ifndef NO_PKCS11_BYPASS | |
8447 if (ss->opt.bypassPKCS11) { | |
8448 /* we cannot restart a non-bypass session in a | |
8449 ** bypass socket. | |
8450 */ | |
8451 break; | |
8452 } | |
8453 #endif | |
8454 | |
8455 wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType, | |
8456 sid->u.ssl3.masterWrapMech, | |
8457 ss->pkcs11PinArg); | |
8458 if (!wrapKey) { | |
8459 /* we have a SID cache entry, but no wrapping key for it??? */ | |
8460 break; | |
8461 } | |
8462 | |
8463 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ | |
8464 keyFlags = CKF_SIGN | CKF_VERIFY; | |
8465 } | |
8466 | |
8467 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; | |
8468 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; | |
8469 | |
8470 /* unwrap the master secret. */ | |
8471 pwSpec->master_secret = | |
8472 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, | |
8473 NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, | |
8474 CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); | |
8475 PK11_FreeSymKey(wrapKey); | |
8476 if (pwSpec->master_secret == NULL) { | |
8477 break; /* not an error */ | |
8478 } | |
8479 #ifndef NO_PKCS11_BYPASS | |
8480 } else if (ss->opt.bypassPKCS11) { | |
8481 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; | |
8482 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; | |
8483 memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); | |
8484 pwSpec->msItem.data = pwSpec->raw_master_secret; | |
8485 pwSpec->msItem.len = wrappedMS.len; | |
8486 #endif | |
8487 } else { | |
8488 /* We CAN restart a bypass session in a non-bypass socket. */ | |
8489 /* need to import the raw master secret to session object */ | |
8490 PK11SlotInfo * slot; | |
8491 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; | |
8492 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; | |
8493 slot = PK11_GetInternalSlot(); | |
8494 pwSpec->master_secret = | |
8495 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, | |
8496 PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS, | |
8497 NULL); | |
8498 PK11_FreeSlot(slot); | |
8499 if (pwSpec->master_secret == NULL) { | |
8500 break; /* not an error */ | |
8501 } | |
8502 } | |
8503 ss->sec.ci.sid = sid; | |
8504 if (sid->peerCert != NULL) { | |
8505 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); | |
8506 ssl3_CopyPeerCertsFromSID(ss, sid); | |
8507 } | |
8508 | |
8509 /* | |
8510 * Old SID passed all tests, so resume this old session. | |
8511 * | |
8512 * XXX make sure compression still matches | |
8513 */ | |
8514 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_hits ); | |
8515 if (ss->statelessResume) | |
8516 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_stateless_resumes ); | |
8517 ss->ssl3.hs.isResuming = PR_TRUE; | |
8518 | |
8519 ss->sec.authAlgorithm = sid->authAlgorithm; | |
8520 ss->sec.authKeyBits = sid->authKeyBits; | |
8521 ss->sec.keaType = sid->keaType; | |
8522 ss->sec.keaKeyBits = sid->keaKeyBits; | |
8523 | |
8524 /* server sids don't remember the server cert we previously sent, | |
8525 ** but they do remember the kea type we originally used, so we | |
8526 ** can locate it again, provided that the current ssl socket | |
8527 ** has had its server certs configured the same as the previous one. | |
8528 */ | |
8529 ss->sec.localCert = | |
8530 CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert); | |
8531 | |
8532 /* Copy cached name in to pending spec */ | |
8533 if (sid != NULL && | |
8534 sid->version > SSL_LIBRARY_VERSION_3_0 && | |
8535 sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) { | |
8536 /* Set server name from sid */ | |
8537 SECItem *sidName = &sid->u.ssl3.srvName; | |
8538 SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName; | |
8539 if (pwsName->data) { | |
8540 SECITEM_FreeItem(pwsName, PR_FALSE); | |
8541 } | |
8542 rv = SECITEM_CopyItem(NULL, pwsName, sidName); | |
8543 if (rv != SECSuccess) { | |
8544 errCode = PORT_GetError(); | |
8545 desc = internal_error; | |
8546 goto alert_loser; | |
8547 } | |
8548 } | |
8549 | |
8550 /* Clean up sni name array */ | |
8551 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) && | |
8552 ss->xtnData.sniNameArr) { | |
8553 PORT_Free(ss->xtnData.sniNameArr); | |
8554 ss->xtnData.sniNameArr = NULL; | |
8555 ss->xtnData.sniNameArrSize = 0; | |
8556 } | |
8557 | |
8558 ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE; | |
8559 | |
8560 rv = ssl3_SendServerHello(ss); | |
8561 if (rv != SECSuccess) { | |
8562 errCode = PORT_GetError(); | |
8563 goto loser; | |
8564 } | |
8565 | |
8566 if (haveSpecWriteLock) { | |
8567 ssl_ReleaseSpecWriteLock(ss); | |
8568 haveSpecWriteLock = PR_FALSE; | |
8569 } | |
8570 | |
8571 /* NULL value for PMS signifies re-use of the old MS */ | |
8572 rv = ssl3_InitPendingCipherSpec(ss, NULL); | |
8573 if (rv != SECSuccess) { | |
8574 errCode = PORT_GetError(); | |
8575 goto loser; | |
8576 } | |
8577 | |
8578 rv = ssl3_SendChangeCipherSpecs(ss); | |
8579 if (rv != SECSuccess) { | |
8580 errCode = PORT_GetError(); | |
8581 goto loser; | |
8582 } | |
8583 rv = ssl3_SendFinished(ss, 0); | |
8584 ss->ssl3.hs.ws = wait_change_cipher; | |
8585 if (rv != SECSuccess) { | |
8586 errCode = PORT_GetError(); | |
8587 goto loser; | |
8588 } | |
8589 | |
8590 if (haveXmitBufLock) { | |
8591 ssl_ReleaseXmitBufLock(ss); | |
8592 haveXmitBufLock = PR_FALSE; | |
8593 } | |
8594 | |
8595 return SECSuccess; | |
8596 } while (0); | |
8597 | |
8598 if (haveSpecWriteLock) { | |
8599 ssl_ReleaseSpecWriteLock(ss); | |
8600 haveSpecWriteLock = PR_FALSE; | |
8601 } | |
8602 | |
8603 if (sid) { /* we had a sid, but it's no longer valid, free it */ | |
8604 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok ); | |
8605 if (ss->sec.uncache) | |
8606 ss->sec.uncache(sid); | |
8607 ssl_FreeSID(sid); | |
8608 sid = NULL; | |
8609 } | |
8610 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses ); | |
8611 | |
8612 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) { | |
8613 int ret = 0; | |
8614 if (ss->sniSocketConfig) do { /* not a loop */ | |
8615 ret = SSL_SNI_SEND_ALERT; | |
8616 /* If extension is negotiated, the len of names should > 0. */ | |
8617 if (ss->xtnData.sniNameArrSize) { | |
8618 /* Calling client callback to reconfigure the socket. */ | |
8619 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd, | |
8620 ss->xtnData.sniNameArr, | |
8621 ss->xtnData.sniNameArrSize, | |
8622 ss->sniSocketConfigArg); | |
8623 } | |
8624 if (ret <= SSL_SNI_SEND_ALERT) { | |
8625 /* Application does not know the name or was not able to | |
8626 * properly reconfigure the socket. */ | |
8627 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; | |
8628 desc = unrecognized_name; | |
8629 break; | |
8630 } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) { | |
8631 SECStatus rv = SECSuccess; | |
8632 SECItem * cwsName, *pwsName; | |
8633 | |
8634 ssl_GetSpecWriteLock(ss); /*******************************/ | |
8635 pwsName = &ss->ssl3.pwSpec->srvVirtName; | |
8636 cwsName = &ss->ssl3.cwSpec->srvVirtName; | |
8637 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS | |
8638 /* not allow name change on the 2d HS */ | |
8639 if (ss->firstHsDone) { | |
8640 if (ssl3_ServerNameCompare(pwsName, cwsName)) { | |
8641 ssl_ReleaseSpecWriteLock(ss); /******************/ | |
8642 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; | |
8643 desc = handshake_failure; | |
8644 ret = SSL_SNI_SEND_ALERT; | |
8645 break; | |
8646 } | |
8647 } | |
8648 #endif | |
8649 if (pwsName->data) { | |
8650 SECITEM_FreeItem(pwsName, PR_FALSE); | |
8651 } | |
8652 if (cwsName->data) { | |
8653 rv = SECITEM_CopyItem(NULL, pwsName, cwsName); | |
8654 } | |
8655 ssl_ReleaseSpecWriteLock(ss); /**************************/ | |
8656 if (rv != SECSuccess) { | |
8657 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; | |
8658 desc = internal_error; | |
8659 ret = SSL_SNI_SEND_ALERT; | |
8660 break; | |
8661 } | |
8662 } else if (ret < ss->xtnData.sniNameArrSize) { | |
8663 /* Application has configured new socket info. Lets check it | |
8664 * and save the name. */ | |
8665 SECStatus rv; | |
8666 SECItem * name = &ss->xtnData.sniNameArr[ret]; | |
8667 int configedCiphers; | |
8668 SECItem * pwsName; | |
8669 | |
8670 /* get rid of the old name and save the newly picked. */ | |
8671 /* This code is protected by ssl3HandshakeLock. */ | |
8672 ssl_GetSpecWriteLock(ss); /*******************************/ | |
8673 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS | |
8674 /* not allow name change on the 2d HS */ | |
8675 if (ss->firstHsDone) { | |
8676 SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName; | |
8677 if (ssl3_ServerNameCompare(name, cwsName)) { | |
8678 ssl_ReleaseSpecWriteLock(ss); /******************/ | |
8679 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; | |
8680 desc = handshake_failure; | |
8681 ret = SSL_SNI_SEND_ALERT; | |
8682 break; | |
8683 } | |
8684 } | |
8685 #endif | |
8686 pwsName = &ss->ssl3.pwSpec->srvVirtName; | |
8687 if (pwsName->data) { | |
8688 SECITEM_FreeItem(pwsName, PR_FALSE); | |
8689 } | |
8690 rv = SECITEM_CopyItem(NULL, pwsName, name); | |
8691 ssl_ReleaseSpecWriteLock(ss); /***************************/ | |
8692 if (rv != SECSuccess) { | |
8693 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; | |
8694 desc = internal_error; | |
8695 ret = SSL_SNI_SEND_ALERT; | |
8696 break; | |
8697 } | |
8698 configedCiphers = ssl3_config_match_init(ss); | |
8699 if (configedCiphers <= 0) { | |
8700 /* no ciphers are working/supported */ | |
8701 errCode = PORT_GetError(); | |
8702 desc = handshake_failure; | |
8703 ret = SSL_SNI_SEND_ALERT; | |
8704 break; | |
8705 } | |
8706 /* Need to tell the client that application has picked | |
8707 * the name from the offered list and reconfigured the socket. | |
8708 */ | |
8709 ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn, | |
8710 ssl3_SendServerNameXtn); | |
8711 } else { | |
8712 /* Callback returned index outside of the boundary. */ | |
8713 PORT_Assert(ret < ss->xtnData.sniNameArrSize); | |
8714 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; | |
8715 desc = internal_error; | |
8716 ret = SSL_SNI_SEND_ALERT; | |
8717 break; | |
8718 } | |
8719 } while (0); | |
8720 /* Free sniNameArr. The data that each SECItem in the array | |
8721 * points into is the data from the input buffer "b". It will | |
8722 * not be available outside the scope of this or it's child | |
8723 * functions.*/ | |
8724 if (ss->xtnData.sniNameArr) { | |
8725 PORT_Free(ss->xtnData.sniNameArr); | |
8726 ss->xtnData.sniNameArr = NULL; | |
8727 ss->xtnData.sniNameArrSize = 0; | |
8728 } | |
8729 if (ret <= SSL_SNI_SEND_ALERT) { | |
8730 /* desc and errCode should be set. */ | |
8731 goto alert_loser; | |
8732 } | |
8733 } | |
8734 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS | |
8735 else if (ss->firstHsDone) { | |
8736 /* Check that we don't have the name is current spec | |
8737 * if this extension was not negotiated on the 2d hs. */ | |
8738 PRBool passed = PR_TRUE; | |
8739 ssl_GetSpecReadLock(ss); /*******************************/ | |
8740 if (ss->ssl3.cwSpec->srvVirtName.data) { | |
8741 passed = PR_FALSE; | |
8742 } | |
8743 ssl_ReleaseSpecReadLock(ss); /***************************/ | |
8744 if (!passed) { | |
8745 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; | |
8746 desc = handshake_failure; | |
8747 goto alert_loser; | |
8748 } | |
8749 } | |
8750 #endif | |
8751 | |
8752 sid = ssl3_NewSessionID(ss, PR_TRUE); | |
8753 if (sid == NULL) { | |
8754 errCode = PORT_GetError(); | |
8755 goto loser; /* memory error is set. */ | |
8756 } | |
8757 ss->sec.ci.sid = sid; | |
8758 | |
8759 ss->ssl3.hs.isResuming = PR_FALSE; | |
8760 ssl_GetXmitBufLock(ss); | |
8761 rv = ssl3_SendServerHelloSequence(ss); | |
8762 ssl_ReleaseXmitBufLock(ss); | |
8763 if (rv != SECSuccess) { | |
8764 errCode = PORT_GetError(); | |
8765 goto loser; | |
8766 } | |
8767 | |
8768 if (haveXmitBufLock) { | |
8769 ssl_ReleaseXmitBufLock(ss); | |
8770 haveXmitBufLock = PR_FALSE; | |
8771 } | |
8772 | |
8773 return SECSuccess; | |
8774 | |
8775 alert_loser: | |
8776 if (haveSpecWriteLock) { | |
8777 ssl_ReleaseSpecWriteLock(ss); | |
8778 haveSpecWriteLock = PR_FALSE; | |
8779 } | |
8780 (void)SSL3_SendAlert(ss, level, desc); | |
8781 /* FALLTHRU */ | |
8782 loser: | |
8783 if (haveSpecWriteLock) { | |
8784 ssl_ReleaseSpecWriteLock(ss); | |
8785 haveSpecWriteLock = PR_FALSE; | |
8786 } | |
8787 | |
8788 if (haveXmitBufLock) { | |
8789 ssl_ReleaseXmitBufLock(ss); | |
8790 haveXmitBufLock = PR_FALSE; | |
8791 } | |
8792 | |
8793 PORT_SetError(errCode); | |
8794 return SECFailure; | |
8795 } | |
8796 | |
8797 /* | |
8798 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes | |
8799 * in asking to use the V3 handshake. | |
8800 * Called from ssl2_HandleClientHelloMessage() in sslcon.c | |
8801 */ | |
8802 SECStatus | |
8803 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length) | |
8804 { | |
8805 sslSessionID * sid = NULL; | |
8806 unsigned char * suites; | |
8807 unsigned char * random; | |
8808 SSL3ProtocolVersion version; | |
8809 SECStatus rv; | |
8810 int i; | |
8811 int j; | |
8812 int sid_length; | |
8813 int suite_length; | |
8814 int rand_length; | |
8815 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; | |
8816 SSL3AlertDescription desc = handshake_failure; | |
8817 | |
8818 SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd)); | |
8819 | |
8820 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
8821 | |
8822 ssl_GetSSL3HandshakeLock(ss); | |
8823 | |
8824 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); | |
8825 | |
8826 rv = ssl3_InitState(ss); | |
8827 if (rv != SECSuccess) { | |
8828 ssl_ReleaseSSL3HandshakeLock(ss); | |
8829 return rv; /* ssl3_InitState has set the error code. */ | |
8830 } | |
8831 rv = ssl3_RestartHandshakeHashes(ss); | |
8832 if (rv != SECSuccess) { | |
8833 ssl_ReleaseSSL3HandshakeLock(ss); | |
8834 return rv; | |
8835 } | |
8836 | |
8837 if (ss->ssl3.hs.ws != wait_client_hello) { | |
8838 desc = unexpected_message; | |
8839 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; | |
8840 goto loser; /* alert_loser */ | |
8841 } | |
8842 | |
8843 version = (buffer[1] << 8) | buffer[2]; | |
8844 suite_length = (buffer[3] << 8) | buffer[4]; | |
8845 sid_length = (buffer[5] << 8) | buffer[6]; | |
8846 rand_length = (buffer[7] << 8) | buffer[8]; | |
8847 ss->clientHelloVersion = version; | |
8848 | |
8849 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); | |
8850 if (rv != SECSuccess) { | |
8851 /* send back which ever alert client will understand. */ | |
8852 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version : handshak
e_failure; | |
8853 errCode = SSL_ERROR_NO_CYPHER_OVERLAP; | |
8854 goto alert_loser; | |
8855 } | |
8856 | |
8857 rv = ssl3_InitHandshakeHashes(ss); | |
8858 if (rv != SECSuccess) { | |
8859 desc = internal_error; | |
8860 errCode = PORT_GetError(); | |
8861 goto alert_loser; | |
8862 } | |
8863 | |
8864 /* if we get a non-zero SID, just ignore it. */ | |
8865 if (length != | |
8866 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) { | |
8867 SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d", | |
8868 SSL_GETPID(), ss->fd, length, | |
8869 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + | |
8870 rand_length)); | |
8871 goto loser; /* malformed */ /* alert_loser */ | |
8872 } | |
8873 | |
8874 suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES; | |
8875 random = suites + suite_length + sid_length; | |
8876 | |
8877 if (rand_length < SSL_MIN_CHALLENGE_BYTES || | |
8878 rand_length > SSL_MAX_CHALLENGE_BYTES) { | |
8879 goto loser; /* malformed */ /* alert_loser */ | |
8880 } | |
8881 | |
8882 PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH); | |
8883 | |
8884 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); | |
8885 PORT_Memcpy( | |
8886 &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length], | |
8887 random, rand_length); | |
8888 | |
8889 PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0], | |
8890 SSL3_RANDOM_LENGTH)); | |
8891 #ifdef NSS_ENABLE_ECC | |
8892 /* Disable any ECC cipher suites for which we have no cert. */ | |
8893 ssl3_FilterECCipherSuitesByServerCerts(ss); | |
8894 #endif | |
8895 i = ssl3_config_match_init(ss); | |
8896 if (i <= 0) { | |
8897 errCode = PORT_GetError(); /* error code is already set. */ | |
8898 goto alert_loser; | |
8899 } | |
8900 | |
8901 /* Select a cipher suite. | |
8902 ** | |
8903 ** NOTE: This suite selection algorithm should be the same as the one in | |
8904 ** ssl3_HandleClientHello(). | |
8905 ** | |
8906 ** See the comments about export cipher suites in ssl3_HandleClientHello(). | |
8907 */ | |
8908 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { | |
8909 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; | |
8910 SSLVersionRange vrange = {ss->version, ss->version}; | |
8911 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) { | |
8912 continue; | |
8913 } | |
8914 for (i = 0; i+2 < suite_length; i += 3) { | |
8915 PRUint32 suite_i = (suites[i] << 16)|(suites[i+1] << 8)|suites[i+2]; | |
8916 if (suite_i == suite->cipher_suite) { | |
8917 ss->ssl3.hs.cipher_suite = suite->cipher_suite; | |
8918 ss->ssl3.hs.suite_def = | |
8919 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); | |
8920 goto suite_found; | |
8921 } | |
8922 } | |
8923 } | |
8924 errCode = SSL_ERROR_NO_CYPHER_OVERLAP; | |
8925 goto alert_loser; | |
8926 | |
8927 suite_found: | |
8928 | |
8929 /* Look for the SCSV, and if found, treat it just like an empty RI | |
8930 * extension by processing a local copy of an empty RI extension. | |
8931 */ | |
8932 for (i = 0; i+2 < suite_length; i += 3) { | |
8933 PRUint32 suite_i = (suites[i] << 16) | (suites[i+1] << 8) | suites[i+2]; | |
8934 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { | |
8935 SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext; | |
8936 PRUint32 L2 = sizeof emptyRIext; | |
8937 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2); | |
8938 break; | |
8939 } | |
8940 } | |
8941 | |
8942 if (ss->opt.requireSafeNegotiation && | |
8943 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { | |
8944 desc = handshake_failure; | |
8945 errCode = SSL_ERROR_UNSAFE_NEGOTIATION; | |
8946 goto alert_loser; | |
8947 } | |
8948 | |
8949 ss->ssl3.hs.compression = ssl_compression_null; | |
8950 ss->sec.send = ssl3_SendApplicationData; | |
8951 | |
8952 /* we don't even search for a cache hit here. It's just a miss. */ | |
8953 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses ); | |
8954 sid = ssl3_NewSessionID(ss, PR_TRUE); | |
8955 if (sid == NULL) { | |
8956 errCode = PORT_GetError(); | |
8957 goto loser; /* memory error is set. */ | |
8958 } | |
8959 ss->sec.ci.sid = sid; | |
8960 /* do not worry about memory leak of sid since it now belongs to ci */ | |
8961 | |
8962 /* We have to update the handshake hashes before we can send stuff */ | |
8963 rv = ssl3_UpdateHandshakeHashes(ss, buffer, length); | |
8964 if (rv != SECSuccess) { | |
8965 errCode = PORT_GetError(); | |
8966 goto loser; | |
8967 } | |
8968 | |
8969 ssl_GetXmitBufLock(ss); | |
8970 rv = ssl3_SendServerHelloSequence(ss); | |
8971 ssl_ReleaseXmitBufLock(ss); | |
8972 if (rv != SECSuccess) { | |
8973 errCode = PORT_GetError(); | |
8974 goto loser; | |
8975 } | |
8976 | |
8977 /* XXX_1 The call stack to here is: | |
8978 * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here. | |
8979 * ssl2_HandleClientHelloMessage returns whatever we return here. | |
8980 * ssl_Do1stHandshake will continue looping if it gets back either | |
8981 * SECSuccess or SECWouldBlock. | |
8982 * SECSuccess is preferable here. See XXX_1 in sslgathr.c. | |
8983 */ | |
8984 ssl_ReleaseSSL3HandshakeLock(ss); | |
8985 return SECSuccess; | |
8986 | |
8987 alert_loser: | |
8988 SSL3_SendAlert(ss, alert_fatal, desc); | |
8989 loser: | |
8990 ssl_ReleaseSSL3HandshakeLock(ss); | |
8991 PORT_SetError(errCode); | |
8992 return SECFailure; | |
8993 } | |
8994 | |
8995 /* The negotiated version number has been already placed in ss->version. | |
8996 ** | |
8997 ** Called from: ssl3_HandleClientHello (resuming session), | |
8998 ** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session), | |
8999 ** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session) | |
9000 */ | |
9001 static SECStatus | |
9002 ssl3_SendServerHello(sslSocket *ss) | |
9003 { | |
9004 sslSessionID *sid; | |
9005 SECStatus rv; | |
9006 PRUint32 maxBytes = 65535; | |
9007 PRUint32 length; | |
9008 PRInt32 extensions_len = 0; | |
9009 SSL3ProtocolVersion version; | |
9010 | |
9011 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(), | |
9012 ss->fd)); | |
9013 | |
9014 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
9015 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
9016 | |
9017 if (!IS_DTLS(ss)) { | |
9018 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0)); | |
9019 | |
9020 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) { | |
9021 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); | |
9022 return SECFailure; | |
9023 } | |
9024 } else { | |
9025 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0)); | |
9026 | |
9027 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) { | |
9028 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); | |
9029 return SECFailure; | |
9030 } | |
9031 } | |
9032 | |
9033 sid = ss->sec.ci.sid; | |
9034 | |
9035 extensions_len = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, | |
9036 &ss->xtnData.serverSenders[0]); | |
9037 if (extensions_len > 0) | |
9038 extensions_len += 2; /* Add sizeof total extension length */ | |
9039 | |
9040 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 + | |
9041 ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength) + | |
9042 sizeof(ssl3CipherSuite) + 1 + extensions_len; | |
9043 rv = ssl3_AppendHandshakeHeader(ss, server_hello, length); | |
9044 if (rv != SECSuccess) { | |
9045 return rv; /* err set by AppendHandshake. */ | |
9046 } | |
9047 | |
9048 if (IS_DTLS(ss)) { | |
9049 version = dtls_TLSVersionToDTLSVersion(ss->version); | |
9050 } else { | |
9051 version = ss->version; | |
9052 } | |
9053 | |
9054 rv = ssl3_AppendHandshakeNumber(ss, version, 2); | |
9055 if (rv != SECSuccess) { | |
9056 return rv; /* err set by AppendHandshake. */ | |
9057 } | |
9058 rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random); | |
9059 if (rv != SECSuccess) { | |
9060 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); | |
9061 return rv; | |
9062 } | |
9063 rv = ssl3_AppendHandshake( | |
9064 ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH); | |
9065 if (rv != SECSuccess) { | |
9066 return rv; /* err set by AppendHandshake. */ | |
9067 } | |
9068 | |
9069 if (sid) | |
9070 rv = ssl3_AppendHandshakeVariable( | |
9071 ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); | |
9072 else | |
9073 rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1); | |
9074 if (rv != SECSuccess) { | |
9075 return rv; /* err set by AppendHandshake. */ | |
9076 } | |
9077 | |
9078 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2); | |
9079 if (rv != SECSuccess) { | |
9080 return rv; /* err set by AppendHandshake. */ | |
9081 } | |
9082 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1); | |
9083 if (rv != SECSuccess) { | |
9084 return rv; /* err set by AppendHandshake. */ | |
9085 } | |
9086 if (extensions_len) { | |
9087 PRInt32 sent_len; | |
9088 | |
9089 extensions_len -= 2; | |
9090 rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2); | |
9091 if (rv != SECSuccess) | |
9092 return rv; /* err set by ssl3_SetupPendingCipherSpec */ | |
9093 sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len, | |
9094 &ss->xtnData.serverSenders[0]); | |
9095 PORT_Assert(sent_len == extensions_len); | |
9096 if (sent_len != extensions_len) { | |
9097 if (sent_len >= 0) | |
9098 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
9099 return SECFailure; | |
9100 } | |
9101 } | |
9102 rv = ssl3_SetupPendingCipherSpec(ss); | |
9103 if (rv != SECSuccess) { | |
9104 return rv; /* err set by ssl3_SetupPendingCipherSpec */ | |
9105 } | |
9106 | |
9107 return SECSuccess; | |
9108 } | |
9109 | |
9110 /* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing | |
9111 * elements of the handshake. (The negotiated cipher suite determines the | |
9112 * signature algorithm.) Prior to TLS 1.2, the MD5/SHA1 combination is always | |
9113 * used. With TLS 1.2, a client may advertise its support for signature and | |
9114 * hash combinations. */ | |
9115 static SECStatus | |
9116 ssl3_PickSignatureHashAlgorithm(sslSocket *ss, | |
9117 SSL3SignatureAndHashAlgorithm* out) | |
9118 { | |
9119 TLSSignatureAlgorithm sigAlg; | |
9120 unsigned int i, j; | |
9121 /* hashPreference expresses our preferences for hash algorithms, most | |
9122 * preferable first. */ | |
9123 static const PRUint8 hashPreference[] = { | |
9124 tls_hash_sha256, | |
9125 tls_hash_sha384, | |
9126 tls_hash_sha512, | |
9127 tls_hash_sha1, | |
9128 }; | |
9129 | |
9130 switch (ss->ssl3.hs.kea_def->kea) { | |
9131 case kea_rsa: | |
9132 case kea_rsa_export: | |
9133 case kea_rsa_export_1024: | |
9134 case kea_dh_rsa: | |
9135 case kea_dh_rsa_export: | |
9136 case kea_dhe_rsa: | |
9137 case kea_dhe_rsa_export: | |
9138 case kea_rsa_fips: | |
9139 case kea_ecdh_rsa: | |
9140 case kea_ecdhe_rsa: | |
9141 sigAlg = tls_sig_rsa; | |
9142 break; | |
9143 case kea_dh_dss: | |
9144 case kea_dh_dss_export: | |
9145 case kea_dhe_dss: | |
9146 case kea_dhe_dss_export: | |
9147 sigAlg = tls_sig_dsa; | |
9148 break; | |
9149 case kea_ecdh_ecdsa: | |
9150 case kea_ecdhe_ecdsa: | |
9151 sigAlg = tls_sig_ecdsa; | |
9152 break; | |
9153 default: | |
9154 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); | |
9155 return SECFailure; | |
9156 } | |
9157 out->sigAlg = sigAlg; | |
9158 | |
9159 if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) { | |
9160 /* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and | |
9161 * prior. */ | |
9162 out->hashAlg = SEC_OID_UNKNOWN; | |
9163 return SECSuccess; | |
9164 } | |
9165 | |
9166 if (ss->ssl3.hs.numClientSigAndHash == 0) { | |
9167 /* If the client didn't provide any signature_algorithms extension then | |
9168 * we can assume that they support SHA-1: | |
9169 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ | |
9170 out->hashAlg = SEC_OID_SHA1; | |
9171 return SECSuccess; | |
9172 } | |
9173 | |
9174 for (i = 0; i < PR_ARRAY_SIZE(hashPreference); i++) { | |
9175 for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) { | |
9176 const SSL3SignatureAndHashAlgorithm* sh = | |
9177 &ss->ssl3.hs.clientSigAndHash[j]; | |
9178 if (sh->sigAlg == sigAlg && sh->hashAlg == hashPreference[i]) { | |
9179 out->hashAlg = sh->hashAlg; | |
9180 return SECSuccess; | |
9181 } | |
9182 } | |
9183 } | |
9184 | |
9185 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); | |
9186 return SECFailure; | |
9187 } | |
9188 | |
9189 | |
9190 static SECStatus | |
9191 ssl3_SendServerKeyExchange(sslSocket *ss) | |
9192 { | |
9193 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; | |
9194 SECStatus rv = SECFailure; | |
9195 int length; | |
9196 PRBool isTLS; | |
9197 SECItem signed_hash = {siBuffer, NULL, 0}; | |
9198 SSL3Hashes hashes; | |
9199 SECKEYPublicKey * sdPub; /* public key for step-down */ | |
9200 SSL3SignatureAndHashAlgorithm sigAndHash; | |
9201 | |
9202 SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake", | |
9203 SSL_GETPID(), ss->fd)); | |
9204 | |
9205 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
9206 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
9207 | |
9208 if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) { | |
9209 return SECFailure; | |
9210 } | |
9211 | |
9212 switch (kea_def->exchKeyType) { | |
9213 case kt_rsa: | |
9214 /* Perform SSL Step-Down here. */ | |
9215 sdPub = ss->stepDownKeyPair->pubKey; | |
9216 PORT_Assert(sdPub != NULL); | |
9217 if (!sdPub) { | |
9218 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
9219 return SECFailure; | |
9220 } | |
9221 rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, | |
9222 sdPub->u.rsa.modulus, | |
9223 sdPub->u.rsa.publicExponent, | |
9224 &ss->ssl3.hs.client_random, | |
9225 &ss->ssl3.hs.server_random, | |
9226 &hashes, ss->opt.bypassPKCS11); | |
9227 if (rv != SECSuccess) { | |
9228 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
9229 return rv; | |
9230 } | |
9231 | |
9232 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
9233 rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY, | |
9234 &signed_hash, isTLS); | |
9235 if (rv != SECSuccess) { | |
9236 goto loser; /* ssl3_SignHashes has set err. */ | |
9237 } | |
9238 if (signed_hash.data == NULL) { | |
9239 /* how can this happen and rv == SECSuccess ?? */ | |
9240 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
9241 goto loser; | |
9242 } | |
9243 length = 2 + sdPub->u.rsa.modulus.len + | |
9244 2 + sdPub->u.rsa.publicExponent.len + | |
9245 2 + signed_hash.len; | |
9246 | |
9247 rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); | |
9248 if (rv != SECSuccess) { | |
9249 goto loser; /* err set by AppendHandshake. */ | |
9250 } | |
9251 | |
9252 rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data, | |
9253 sdPub->u.rsa.modulus.len, 2); | |
9254 if (rv != SECSuccess) { | |
9255 goto loser; /* err set by AppendHandshake. */ | |
9256 } | |
9257 | |
9258 rv = ssl3_AppendHandshakeVariable( | |
9259 ss, sdPub->u.rsa.publicExponent.data, | |
9260 sdPub->u.rsa.publicExponent.len, 2); | |
9261 if (rv != SECSuccess) { | |
9262 goto loser; /* err set by AppendHandshake. */ | |
9263 } | |
9264 | |
9265 if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
9266 rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); | |
9267 if (rv != SECSuccess) { | |
9268 goto loser; /* err set by AppendHandshake. */ | |
9269 } | |
9270 } | |
9271 | |
9272 rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data, | |
9273 signed_hash.len, 2); | |
9274 if (rv != SECSuccess) { | |
9275 goto loser; /* err set by AppendHandshake. */ | |
9276 } | |
9277 PORT_Free(signed_hash.data); | |
9278 return SECSuccess; | |
9279 | |
9280 #ifdef NSS_ENABLE_ECC | |
9281 case kt_ecdh: { | |
9282 rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash); | |
9283 return rv; | |
9284 } | |
9285 #endif /* NSS_ENABLE_ECC */ | |
9286 | |
9287 case kt_dh: | |
9288 case kt_null: | |
9289 default: | |
9290 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); | |
9291 break; | |
9292 } | |
9293 loser: | |
9294 if (signed_hash.data != NULL) | |
9295 PORT_Free(signed_hash.data); | |
9296 return SECFailure; | |
9297 } | |
9298 | |
9299 | |
9300 static SECStatus | |
9301 ssl3_SendCertificateRequest(sslSocket *ss) | |
9302 { | |
9303 PRBool isTLS12; | |
9304 SECItem * name; | |
9305 CERTDistNames *ca_list; | |
9306 const PRUint8 *certTypes; | |
9307 const PRUint8 *sigAlgs; | |
9308 SECItem * names = NULL; | |
9309 SECStatus rv; | |
9310 int length; | |
9311 int i; | |
9312 int calen = 0; | |
9313 int nnames = 0; | |
9314 int certTypesLength; | |
9315 int sigAlgsLength; | |
9316 | |
9317 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake", | |
9318 SSL_GETPID(), ss->fd)); | |
9319 | |
9320 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
9321 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
9322 | |
9323 isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
9324 | |
9325 /* ssl3.ca_list is initialized to NULL, and never changed. */ | |
9326 ca_list = ss->ssl3.ca_list; | |
9327 if (!ca_list) { | |
9328 ca_list = ssl3_server_ca_list; | |
9329 } | |
9330 | |
9331 if (ca_list != NULL) { | |
9332 names = ca_list->names; | |
9333 nnames = ca_list->nnames; | |
9334 } | |
9335 | |
9336 for (i = 0, name = names; i < nnames; i++, name++) { | |
9337 calen += 2 + name->len; | |
9338 } | |
9339 | |
9340 certTypes = certificate_types; | |
9341 certTypesLength = sizeof certificate_types; | |
9342 sigAlgs = supported_signature_algorithms; | |
9343 sigAlgsLength = sizeof supported_signature_algorithms; | |
9344 | |
9345 length = 1 + certTypesLength + 2 + calen; | |
9346 if (isTLS12) { | |
9347 length += 2 + sigAlgsLength; | |
9348 } | |
9349 | |
9350 rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length); | |
9351 if (rv != SECSuccess) { | |
9352 return rv; /* err set by AppendHandshake. */ | |
9353 } | |
9354 rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1); | |
9355 if (rv != SECSuccess) { | |
9356 return rv; /* err set by AppendHandshake. */ | |
9357 } | |
9358 if (isTLS12) { | |
9359 rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2); | |
9360 if (rv != SECSuccess) { | |
9361 return rv; /* err set by AppendHandshake. */ | |
9362 } | |
9363 } | |
9364 rv = ssl3_AppendHandshakeNumber(ss, calen, 2); | |
9365 if (rv != SECSuccess) { | |
9366 return rv; /* err set by AppendHandshake. */ | |
9367 } | |
9368 for (i = 0, name = names; i < nnames; i++, name++) { | |
9369 rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2); | |
9370 if (rv != SECSuccess) { | |
9371 return rv; /* err set by AppendHandshake. */ | |
9372 } | |
9373 } | |
9374 | |
9375 return SECSuccess; | |
9376 } | |
9377 | |
9378 static SECStatus | |
9379 ssl3_SendServerHelloDone(sslSocket *ss) | |
9380 { | |
9381 SECStatus rv; | |
9382 | |
9383 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake", | |
9384 SSL_GETPID(), ss->fd)); | |
9385 | |
9386 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
9387 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
9388 | |
9389 rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0); | |
9390 if (rv != SECSuccess) { | |
9391 return rv; /* err set by AppendHandshake. */ | |
9392 } | |
9393 rv = ssl3_FlushHandshake(ss, 0); | |
9394 if (rv != SECSuccess) { | |
9395 return rv; /* error code set by ssl3_FlushHandshake */ | |
9396 } | |
9397 return SECSuccess; | |
9398 } | |
9399 | |
9400 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete | |
9401 * ssl3 Certificate Verify message | |
9402 * Caller must hold Handshake and RecvBuf locks. | |
9403 */ | |
9404 static SECStatus | |
9405 ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length, | |
9406 SSL3Hashes *hashes) | |
9407 { | |
9408 SECItem signed_hash = {siBuffer, NULL, 0}; | |
9409 SECStatus rv; | |
9410 int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY; | |
9411 SSL3AlertDescription desc = handshake_failure; | |
9412 PRBool isTLS, isTLS12; | |
9413 SSL3SignatureAndHashAlgorithm sigAndHash; | |
9414 | |
9415 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake", | |
9416 SSL_GETPID(), ss->fd)); | |
9417 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
9418 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
9419 | |
9420 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); | |
9421 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
9422 | |
9423 if (ss->ssl3.hs.ws != wait_cert_verify || ss->sec.peerCert == NULL) { | |
9424 desc = unexpected_message; | |
9425 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY; | |
9426 goto alert_loser; | |
9427 } | |
9428 | |
9429 if (isTLS12) { | |
9430 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, | |
9431 &sigAndHash); | |
9432 if (rv != SECSuccess) { | |
9433 goto loser; /* malformed or unsupported. */ | |
9434 } | |
9435 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( | |
9436 &sigAndHash, ss->sec.peerCert); | |
9437 if (rv != SECSuccess) { | |
9438 errCode = PORT_GetError(); | |
9439 desc = decrypt_error; | |
9440 goto alert_loser; | |
9441 } | |
9442 | |
9443 /* We only support CertificateVerify messages that use the handshake | |
9444 * hash. */ | |
9445 if (sigAndHash.hashAlg != hashes->hashAlg) { | |
9446 errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM; | |
9447 desc = decrypt_error; | |
9448 goto alert_loser; | |
9449 } | |
9450 } | |
9451 | |
9452 rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length); | |
9453 if (rv != SECSuccess) { | |
9454 goto loser; /* malformed. */ | |
9455 } | |
9456 | |
9457 /* XXX verify that the key & kea match */ | |
9458 rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash, | |
9459 isTLS, ss->pkcs11PinArg); | |
9460 if (rv != SECSuccess) { | |
9461 errCode = PORT_GetError(); | |
9462 desc = isTLS ? decrypt_error : handshake_failure; | |
9463 goto alert_loser; | |
9464 } | |
9465 | |
9466 signed_hash.data = NULL; | |
9467 | |
9468 if (length != 0) { | |
9469 desc = isTLS ? decode_error : illegal_parameter; | |
9470 goto alert_loser; /* malformed */ | |
9471 } | |
9472 ss->ssl3.hs.ws = wait_change_cipher; | |
9473 return SECSuccess; | |
9474 | |
9475 alert_loser: | |
9476 SSL3_SendAlert(ss, alert_fatal, desc); | |
9477 loser: | |
9478 PORT_SetError(errCode); | |
9479 return SECFailure; | |
9480 } | |
9481 | |
9482 | |
9483 /* find a slot that is able to generate a PMS and wrap it with RSA. | |
9484 * Then generate and return the PMS. | |
9485 * If the serverKeySlot parameter is non-null, this function will use | |
9486 * that slot to do the job, otherwise it will find a slot. | |
9487 * | |
9488 * Called from ssl3_DeriveConnectionKeysPKCS11() (above) | |
9489 * sendRSAClientKeyExchange() (above) | |
9490 * ssl3_HandleRSAClientKeyExchange() (below) | |
9491 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock | |
9492 */ | |
9493 static PK11SymKey * | |
9494 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, | |
9495 PK11SlotInfo * serverKeySlot) | |
9496 { | |
9497 PK11SymKey * pms = NULL; | |
9498 PK11SlotInfo * slot = serverKeySlot; | |
9499 void * pwArg = ss->pkcs11PinArg; | |
9500 SECItem param; | |
9501 CK_VERSION version; | |
9502 CK_MECHANISM_TYPE mechanism_array[3]; | |
9503 | |
9504 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
9505 | |
9506 if (slot == NULL) { | |
9507 SSLCipherAlgorithm calg; | |
9508 /* The specReadLock would suffice here, but we cannot assert on | |
9509 ** read locks. Also, all the callers who call with a non-null | |
9510 ** slot already hold the SpecWriteLock. | |
9511 */ | |
9512 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); | |
9513 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
9514 | |
9515 calg = spec->cipher_def->calg; | |
9516 PORT_Assert(alg2Mech[calg].calg == calg); | |
9517 | |
9518 /* First get an appropriate slot. */ | |
9519 mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN; | |
9520 mechanism_array[1] = CKM_RSA_PKCS; | |
9521 mechanism_array[2] = alg2Mech[calg].cmech; | |
9522 | |
9523 slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg); | |
9524 if (slot == NULL) { | |
9525 /* can't find a slot with all three, find a slot with the minimum */ | |
9526 slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg); | |
9527 if (slot == NULL) { | |
9528 PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND); | |
9529 return pms; /* which is NULL */ | |
9530 } | |
9531 } | |
9532 } | |
9533 | |
9534 /* Generate the pre-master secret ... */ | |
9535 if (IS_DTLS(ss)) { | |
9536 SSL3ProtocolVersion temp; | |
9537 | |
9538 temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); | |
9539 version.major = MSB(temp); | |
9540 version.minor = LSB(temp); | |
9541 } else { | |
9542 version.major = MSB(ss->clientHelloVersion); | |
9543 version.minor = LSB(ss->clientHelloVersion); | |
9544 } | |
9545 | |
9546 param.data = (unsigned char *)&version; | |
9547 param.len = sizeof version; | |
9548 | |
9549 pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, ¶m, 0, pwArg); | |
9550 if (!serverKeySlot) | |
9551 PK11_FreeSlot(slot); | |
9552 if (pms == NULL) { | |
9553 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
9554 } | |
9555 return pms; | |
9556 } | |
9557 | |
9558 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER | |
9559 * return any indication of failure of the Client Key Exchange message, | |
9560 * where that failure is caused by the content of the client's message. | |
9561 * This function must not return SECFailure for any reason that is directly | |
9562 * or indirectly caused by the content of the client's encrypted PMS. | |
9563 * We must not send an alert and also not drop the connection. | |
9564 * Instead, we generate a random PMS. This will cause a failure | |
9565 * in the processing the finished message, which is exactly where | |
9566 * the failure must occur. | |
9567 * | |
9568 * Called from ssl3_HandleClientKeyExchange | |
9569 */ | |
9570 static SECStatus | |
9571 ssl3_HandleRSAClientKeyExchange(sslSocket *ss, | |
9572 SSL3Opaque *b, | |
9573 PRUint32 length, | |
9574 SECKEYPrivateKey *serverKey) | |
9575 { | |
9576 PK11SymKey * pms; | |
9577 #ifndef NO_PKCS11_BYPASS | |
9578 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; | |
9579 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; | |
9580 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; | |
9581 unsigned int outLen = 0; | |
9582 #endif | |
9583 PRBool isTLS = PR_FALSE; | |
9584 SECStatus rv; | |
9585 SECItem enc_pms; | |
9586 unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH]; | |
9587 SECItem pmsItem = {siBuffer, NULL, 0}; | |
9588 | |
9589 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
9590 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
9591 PORT_Assert( ss->ssl3.prSpec == ss->ssl3.pwSpec ); | |
9592 | |
9593 enc_pms.data = b; | |
9594 enc_pms.len = length; | |
9595 pmsItem.data = rsaPmsBuf; | |
9596 pmsItem.len = sizeof rsaPmsBuf; | |
9597 | |
9598 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ | |
9599 PRInt32 kLen; | |
9600 kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len); | |
9601 if (kLen < 0) { | |
9602 PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
9603 return SECFailure; | |
9604 } | |
9605 if ((unsigned)kLen < enc_pms.len) { | |
9606 enc_pms.len = kLen; | |
9607 } | |
9608 isTLS = PR_TRUE; | |
9609 } else { | |
9610 isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0); | |
9611 } | |
9612 | |
9613 #ifndef NO_PKCS11_BYPASS | |
9614 if (ss->opt.bypassPKCS11) { | |
9615 /* TRIPLE BYPASS, get PMS directly from RSA decryption. | |
9616 * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer, | |
9617 * then, check for version rollback attack, then | |
9618 * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in | |
9619 * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with | |
9620 * ss and NULL, so that it will use the MS we've already derived here. | |
9621 */ | |
9622 | |
9623 rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen, | |
9624 sizeof rsaPmsBuf, enc_pms.data, enc_pms.len); | |
9625 if (rv != SECSuccess) { | |
9626 /* triple bypass failed. Let's try for a double bypass. */ | |
9627 goto double_bypass; | |
9628 } else if (ss->opt.detectRollBack) { | |
9629 SSL3ProtocolVersion client_version = | |
9630 (rsaPmsBuf[0] << 8) | rsaPmsBuf[1]; | |
9631 | |
9632 if (IS_DTLS(ss)) { | |
9633 client_version = dtls_DTLSVersionToTLSVersion(client_version); | |
9634 } | |
9635 | |
9636 if (client_version != ss->clientHelloVersion) { | |
9637 /* Version roll-back detected. ensure failure. */ | |
9638 rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf); | |
9639 } | |
9640 } | |
9641 /* have PMS, build MS without PKCS11 */ | |
9642 rv = ssl3_MasterKeyDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS, | |
9643 PR_TRUE); | |
9644 if (rv != SECSuccess) { | |
9645 pwSpec->msItem.data = pwSpec->raw_master_secret; | |
9646 pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH; | |
9647 PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len); | |
9648 } | |
9649 rv = ssl3_InitPendingCipherSpec(ss, NULL); | |
9650 } else | |
9651 #endif | |
9652 { | |
9653 #ifndef NO_PKCS11_BYPASS | |
9654 double_bypass: | |
9655 #endif | |
9656 /* | |
9657 * unwrap pms out of the incoming buffer | |
9658 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do | |
9659 * the unwrap. Rather, it is the mechanism with which the | |
9660 * unwrapped pms will be used. | |
9661 */ | |
9662 pms = PK11_PubUnwrapSymKey(serverKey, &enc_pms, | |
9663 CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0); | |
9664 if (pms != NULL) { | |
9665 PRINT_BUF(60, (ss, "decrypted premaster secret:", | |
9666 PK11_GetKeyData(pms)->data, | |
9667 PK11_GetKeyData(pms)->len)); | |
9668 } else { | |
9669 /* unwrap failed. Generate a bogus PMS and carry on. */ | |
9670 PK11SlotInfo * slot = PK11_GetSlotFromPrivateKey(serverKey); | |
9671 | |
9672 ssl_GetSpecWriteLock(ss); | |
9673 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot); | |
9674 ssl_ReleaseSpecWriteLock(ss); | |
9675 PK11_FreeSlot(slot); | |
9676 } | |
9677 | |
9678 if (pms == NULL) { | |
9679 /* last gasp. */ | |
9680 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
9681 return SECFailure; | |
9682 } | |
9683 | |
9684 /* This step will derive the MS from the PMS, among other things. */ | |
9685 rv = ssl3_InitPendingCipherSpec(ss, pms); | |
9686 PK11_FreeSymKey(pms); | |
9687 } | |
9688 | |
9689 if (rv != SECSuccess) { | |
9690 SEND_ALERT | |
9691 return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */ | |
9692 } | |
9693 return SECSuccess; | |
9694 } | |
9695 | |
9696 | |
9697 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete | |
9698 * ssl3 ClientKeyExchange message from the remote client | |
9699 * Caller must hold Handshake and RecvBuf locks. | |
9700 */ | |
9701 static SECStatus | |
9702 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
9703 { | |
9704 SECKEYPrivateKey *serverKey = NULL; | |
9705 SECStatus rv; | |
9706 const ssl3KEADef *kea_def; | |
9707 ssl3KeyPair *serverKeyPair = NULL; | |
9708 #ifdef NSS_ENABLE_ECC | |
9709 SECKEYPublicKey *serverPubKey = NULL; | |
9710 #endif /* NSS_ENABLE_ECC */ | |
9711 | |
9712 SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake", | |
9713 SSL_GETPID(), ss->fd)); | |
9714 | |
9715 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
9716 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
9717 | |
9718 if (ss->ssl3.hs.ws != wait_client_key) { | |
9719 SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
9720 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); | |
9721 return SECFailure; | |
9722 } | |
9723 | |
9724 kea_def = ss->ssl3.hs.kea_def; | |
9725 | |
9726 if (ss->ssl3.hs.usedStepDownKey) { | |
9727 PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */ | |
9728 && kea_def->exchKeyType == kt_rsa | |
9729 && ss->stepDownKeyPair != NULL); | |
9730 if (!kea_def->is_limited || | |
9731 kea_def->exchKeyType != kt_rsa || | |
9732 ss->stepDownKeyPair == NULL) { | |
9733 /* shouldn't happen, don't use step down if it does */ | |
9734 goto skip; | |
9735 } | |
9736 serverKeyPair = ss->stepDownKeyPair; | |
9737 ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB; | |
9738 } else | |
9739 skip: | |
9740 #ifdef NSS_ENABLE_ECC | |
9741 /* XXX Using SSLKEAType to index server certifiates | |
9742 * does not work for (EC)DHE ciphers. Until we have | |
9743 * an indexing mechanism general enough for all key | |
9744 * exchange algorithms, we'll need to deal with each | |
9745 * one seprately. | |
9746 */ | |
9747 if ((kea_def->kea == kea_ecdhe_rsa) || | |
9748 (kea_def->kea == kea_ecdhe_ecdsa)) { | |
9749 if (ss->ephemeralECDHKeyPair != NULL) { | |
9750 serverKeyPair = ss->ephemeralECDHKeyPair; | |
9751 if (serverKeyPair->pubKey) { | |
9752 ss->sec.keaKeyBits = | |
9753 SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey); | |
9754 } | |
9755 } | |
9756 } else | |
9757 #endif | |
9758 { | |
9759 sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType; | |
9760 serverKeyPair = sc->serverKeyPair; | |
9761 ss->sec.keaKeyBits = sc->serverKeyBits; | |
9762 } | |
9763 | |
9764 if (serverKeyPair) { | |
9765 serverKey = serverKeyPair->privKey; | |
9766 } | |
9767 | |
9768 if (serverKey == NULL) { | |
9769 SEND_ALERT | |
9770 PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG); | |
9771 return SECFailure; | |
9772 } | |
9773 | |
9774 ss->sec.keaType = kea_def->exchKeyType; | |
9775 | |
9776 switch (kea_def->exchKeyType) { | |
9777 case kt_rsa: | |
9778 rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey); | |
9779 if (rv != SECSuccess) { | |
9780 SEND_ALERT | |
9781 return SECFailure; /* error code set */ | |
9782 } | |
9783 break; | |
9784 | |
9785 | |
9786 #ifdef NSS_ENABLE_ECC | |
9787 case kt_ecdh: | |
9788 /* XXX We really ought to be able to store multiple | |
9789 * EC certs (a requirement if we wish to support both | |
9790 * ECDH-RSA and ECDH-ECDSA key exchanges concurrently). | |
9791 * When we make that change, we'll need an index other | |
9792 * than kt_ecdh to pick the right EC certificate. | |
9793 */ | |
9794 if (serverKeyPair) { | |
9795 serverPubKey = serverKeyPair->pubKey; | |
9796 } | |
9797 if (serverPubKey == NULL) { | |
9798 /* XXX Is this the right error code? */ | |
9799 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); | |
9800 return SECFailure; | |
9801 } | |
9802 rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, | |
9803 serverPubKey, serverKey); | |
9804 if (rv != SECSuccess) { | |
9805 return SECFailure; /* error code set */ | |
9806 } | |
9807 break; | |
9808 #endif /* NSS_ENABLE_ECC */ | |
9809 | |
9810 default: | |
9811 (void) ssl3_HandshakeFailure(ss); | |
9812 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); | |
9813 return SECFailure; | |
9814 } | |
9815 ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher; | |
9816 return SECSuccess; | |
9817 | |
9818 } | |
9819 | |
9820 /* This is TLS's equivalent of sending a no_certificate alert. */ | |
9821 static SECStatus | |
9822 ssl3_SendEmptyCertificate(sslSocket *ss) | |
9823 { | |
9824 SECStatus rv; | |
9825 | |
9826 rv = ssl3_AppendHandshakeHeader(ss, certificate, 3); | |
9827 if (rv == SECSuccess) { | |
9828 rv = ssl3_AppendHandshakeNumber(ss, 0, 3); | |
9829 } | |
9830 return rv; /* error, if any, set by functions called above. */ | |
9831 } | |
9832 | |
9833 SECStatus | |
9834 ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
9835 { | |
9836 SECStatus rv; | |
9837 SECItem ticketData; | |
9838 | |
9839 SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake", | |
9840 SSL_GETPID(), ss->fd)); | |
9841 | |
9842 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
9843 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
9844 | |
9845 PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); | |
9846 PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket); | |
9847 | |
9848 if (ss->ssl3.hs.ws != wait_new_session_ticket) { | |
9849 SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
9850 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); | |
9851 return SECFailure; | |
9852 } | |
9853 | |
9854 /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid | |
9855 * until it has verified the server's Finished message." See the comment in | |
9856 * ssl3_FinishHandshake for more details. | |
9857 */ | |
9858 ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(); | |
9859 if (length < 4) { | |
9860 (void)SSL3_SendAlert(ss, alert_fatal, decode_error); | |
9861 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); | |
9862 return SECFailure; | |
9863 } | |
9864 ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = | |
9865 (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length); | |
9866 | |
9867 rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length); | |
9868 if (length != 0 || rv != SECSuccess) { | |
9869 (void)SSL3_SendAlert(ss, alert_fatal, decode_error); | |
9870 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); | |
9871 return SECFailure; /* malformed */ | |
9872 } | |
9873 rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket, | |
9874 &ticketData); | |
9875 if (rv != SECSuccess) { | |
9876 return rv; | |
9877 } | |
9878 ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE; | |
9879 | |
9880 ss->ssl3.hs.ws = wait_change_cipher; | |
9881 return SECSuccess; | |
9882 } | |
9883 | |
9884 #ifdef NISCC_TEST | |
9885 static PRInt32 connNum = 0; | |
9886 | |
9887 static SECStatus | |
9888 get_fake_cert(SECItem *pCertItem, int *pIndex) | |
9889 { | |
9890 PRFileDesc *cf; | |
9891 char * testdir; | |
9892 char * startat; | |
9893 char * stopat; | |
9894 const char *extension; | |
9895 int fileNum; | |
9896 PRInt32 numBytes = 0; | |
9897 PRStatus prStatus; | |
9898 PRFileInfo info; | |
9899 char cfn[100]; | |
9900 | |
9901 pCertItem->data = 0; | |
9902 if ((testdir = PR_GetEnv("NISCC_TEST")) == NULL) { | |
9903 return SECSuccess; | |
9904 } | |
9905 *pIndex = (NULL != strstr(testdir, "root")); | |
9906 extension = (strstr(testdir, "simple") ? "" : ".der"); | |
9907 fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1; | |
9908 if ((startat = PR_GetEnv("START_AT")) != NULL) { | |
9909 fileNum += atoi(startat); | |
9910 } | |
9911 if ((stopat = PR_GetEnv("STOP_AT")) != NULL && | |
9912 fileNum >= atoi(stopat)) { | |
9913 *pIndex = -1; | |
9914 return SECSuccess; | |
9915 } | |
9916 sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension); | |
9917 cf = PR_Open(cfn, PR_RDONLY, 0); | |
9918 if (!cf) { | |
9919 goto loser; | |
9920 } | |
9921 prStatus = PR_GetOpenFileInfo(cf, &info); | |
9922 if (prStatus != PR_SUCCESS) { | |
9923 PR_Close(cf); | |
9924 goto loser; | |
9925 } | |
9926 pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size); | |
9927 if (pCertItem) { | |
9928 numBytes = PR_Read(cf, pCertItem->data, info.size); | |
9929 } | |
9930 PR_Close(cf); | |
9931 if (numBytes != info.size) { | |
9932 SECITEM_FreeItem(pCertItem, PR_FALSE); | |
9933 PORT_SetError(SEC_ERROR_IO); | |
9934 goto loser; | |
9935 } | |
9936 fprintf(stderr, "using %s\n", cfn); | |
9937 return SECSuccess; | |
9938 | |
9939 loser: | |
9940 fprintf(stderr, "failed to use %s\n", cfn); | |
9941 *pIndex = -1; | |
9942 return SECFailure; | |
9943 } | |
9944 #endif | |
9945 | |
9946 /* | |
9947 * Used by both client and server. | |
9948 * Called from HandleServerHelloDone and from SendServerHelloSequence. | |
9949 */ | |
9950 static SECStatus | |
9951 ssl3_SendCertificate(sslSocket *ss) | |
9952 { | |
9953 SECStatus rv; | |
9954 CERTCertificateList *certChain; | |
9955 int len = 0; | |
9956 int i; | |
9957 SSL3KEAType certIndex; | |
9958 #ifdef NISCC_TEST | |
9959 SECItem fakeCert; | |
9960 int ndex = -1; | |
9961 #endif | |
9962 | |
9963 SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake", | |
9964 SSL_GETPID(), ss->fd)); | |
9965 | |
9966 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
9967 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
9968 | |
9969 if (ss->sec.localCert) | |
9970 CERT_DestroyCertificate(ss->sec.localCert); | |
9971 if (ss->sec.isServer) { | |
9972 sslServerCerts * sc = NULL; | |
9973 | |
9974 /* XXX SSLKEAType isn't really a good choice for | |
9975 * indexing certificates (it breaks when we deal | |
9976 * with (EC)DHE-* cipher suites. This hack ensures | |
9977 * the RSA cert is picked for (EC)DHE-RSA. | |
9978 * Revisit this when we add server side support | |
9979 * for ECDHE-ECDSA or client-side authentication | |
9980 * using EC certificates. | |
9981 */ | |
9982 if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || | |
9983 (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { | |
9984 certIndex = kt_rsa; | |
9985 } else { | |
9986 certIndex = ss->ssl3.hs.kea_def->exchKeyType; | |
9987 } | |
9988 sc = ss->serverCerts + certIndex; | |
9989 certChain = sc->serverCertChain; | |
9990 ss->sec.authKeyBits = sc->serverKeyBits; | |
9991 ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; | |
9992 ss->sec.localCert = CERT_DupCertificate(sc->serverCert); | |
9993 } else { | |
9994 certChain = ss->ssl3.clientCertChain; | |
9995 ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate); | |
9996 } | |
9997 | |
9998 #ifdef NISCC_TEST | |
9999 rv = get_fake_cert(&fakeCert, &ndex); | |
10000 #endif | |
10001 | |
10002 if (certChain) { | |
10003 for (i = 0; i < certChain->len; i++) { | |
10004 #ifdef NISCC_TEST | |
10005 if (fakeCert.len > 0 && i == ndex) { | |
10006 len += fakeCert.len + 3; | |
10007 } else { | |
10008 len += certChain->certs[i].len + 3; | |
10009 } | |
10010 #else | |
10011 len += certChain->certs[i].len + 3; | |
10012 #endif | |
10013 } | |
10014 } | |
10015 | |
10016 rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3); | |
10017 if (rv != SECSuccess) { | |
10018 return rv; /* err set by AppendHandshake. */ | |
10019 } | |
10020 rv = ssl3_AppendHandshakeNumber(ss, len, 3); | |
10021 if (rv != SECSuccess) { | |
10022 return rv; /* err set by AppendHandshake. */ | |
10023 } | |
10024 if (certChain) { | |
10025 for (i = 0; i < certChain->len; i++) { | |
10026 #ifdef NISCC_TEST | |
10027 if (fakeCert.len > 0 && i == ndex) { | |
10028 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data, | |
10029 fakeCert.len, 3); | |
10030 SECITEM_FreeItem(&fakeCert, PR_FALSE); | |
10031 } else { | |
10032 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, | |
10033 certChain->certs[i].len, 3); | |
10034 } | |
10035 #else | |
10036 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, | |
10037 certChain->certs[i].len, 3); | |
10038 #endif | |
10039 if (rv != SECSuccess) { | |
10040 return rv; /* err set by AppendHandshake. */ | |
10041 } | |
10042 } | |
10043 } | |
10044 | |
10045 return SECSuccess; | |
10046 } | |
10047 | |
10048 /* | |
10049 * Used by server only. | |
10050 * single-stapling, send only a single cert status | |
10051 */ | |
10052 static SECStatus | |
10053 ssl3_SendCertificateStatus(sslSocket *ss) | |
10054 { | |
10055 SECStatus rv; | |
10056 int len = 0; | |
10057 SECItemArray *statusToSend = NULL; | |
10058 SSL3KEAType certIndex; | |
10059 | |
10060 SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake", | |
10061 SSL_GETPID(), ss->fd)); | |
10062 | |
10063 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
10064 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10065 PORT_Assert( ss->sec.isServer); | |
10066 | |
10067 if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) | |
10068 return SECSuccess; | |
10069 | |
10070 /* Use certStatus based on the cert being used. */ | |
10071 if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || | |
10072 (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { | |
10073 certIndex = kt_rsa; | |
10074 } else { | |
10075 certIndex = ss->ssl3.hs.kea_def->exchKeyType; | |
10076 } | |
10077 if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) { | |
10078 statusToSend = ss->certStatusArray[certIndex]; | |
10079 } | |
10080 if (!statusToSend) | |
10081 return SECSuccess; | |
10082 | |
10083 /* Use the array's first item only (single stapling) */ | |
10084 len = 1 + statusToSend->items[0].len + 3; | |
10085 | |
10086 rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len); | |
10087 if (rv != SECSuccess) { | |
10088 return rv; /* err set by AppendHandshake. */ | |
10089 } | |
10090 rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1); | |
10091 if (rv != SECSuccess) | |
10092 return rv; /* err set by AppendHandshake. */ | |
10093 | |
10094 rv = ssl3_AppendHandshakeVariable(ss, | |
10095 statusToSend->items[0].data, | |
10096 statusToSend->items[0].len, | |
10097 3); | |
10098 if (rv != SECSuccess) | |
10099 return rv; /* err set by AppendHandshake. */ | |
10100 | |
10101 return SECSuccess; | |
10102 } | |
10103 | |
10104 /* This is used to delete the CA certificates in the peer certificate chain | |
10105 * from the cert database after they've been validated. | |
10106 */ | |
10107 static void | |
10108 ssl3_CleanupPeerCerts(sslSocket *ss) | |
10109 { | |
10110 PLArenaPool * arena = ss->ssl3.peerCertArena; | |
10111 ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain; | |
10112 | |
10113 for (; certs; certs = certs->next) { | |
10114 CERT_DestroyCertificate(certs->cert); | |
10115 } | |
10116 if (arena) PORT_FreeArena(arena, PR_FALSE); | |
10117 ss->ssl3.peerCertArena = NULL; | |
10118 ss->ssl3.peerCertChain = NULL; | |
10119 } | |
10120 | |
10121 static void | |
10122 ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid) | |
10123 { | |
10124 PLArenaPool *arena; | |
10125 ssl3CertNode *lastCert = NULL; | |
10126 ssl3CertNode *certs = NULL; | |
10127 int i; | |
10128 | |
10129 if (!sid->peerCertChain[0]) | |
10130 return; | |
10131 PORT_Assert(!ss->ssl3.peerCertArena); | |
10132 PORT_Assert(!ss->ssl3.peerCertChain); | |
10133 ss->ssl3.peerCertArena = arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); | |
10134 for (i = 0; i < MAX_PEER_CERT_CHAIN_SIZE && sid->peerCertChain[i]; i++) { | |
10135 ssl3CertNode *c = PORT_ArenaNew(arena, ssl3CertNode); | |
10136 c->cert = CERT_DupCertificate(sid->peerCertChain[i]); | |
10137 c->next = NULL; | |
10138 if (lastCert) { | |
10139 lastCert->next = c; | |
10140 } else { | |
10141 certs = c; | |
10142 } | |
10143 lastCert = c; | |
10144 } | |
10145 ss->ssl3.peerCertChain = certs; | |
10146 } | |
10147 | |
10148 static void | |
10149 ssl3_CopyPeerCertsToSID(ssl3CertNode *certs, sslSessionID *sid) | |
10150 { | |
10151 int i = 0; | |
10152 ssl3CertNode *c = certs; | |
10153 for (; i < MAX_PEER_CERT_CHAIN_SIZE && c; i++, c = c->next) { | |
10154 PORT_Assert(!sid->peerCertChain[i]); | |
10155 sid->peerCertChain[i] = CERT_DupCertificate(c->cert); | |
10156 } | |
10157 } | |
10158 | |
10159 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete | |
10160 * ssl3 CertificateStatus message. | |
10161 * Caller must hold Handshake and RecvBuf locks. | |
10162 * This is always called before ssl3_HandleCertificate, even if the Certificate | |
10163 * message is sent first. | |
10164 */ | |
10165 static SECStatus | |
10166 ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
10167 { | |
10168 PRInt32 status, len; | |
10169 | |
10170 if (ss->ssl3.hs.ws != wait_certificate_status) { | |
10171 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
10172 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS); | |
10173 return SECFailure; | |
10174 } | |
10175 | |
10176 PORT_Assert(!ss->sec.isServer); | |
10177 | |
10178 /* Consume the CertificateStatusType enum */ | |
10179 status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); | |
10180 if (status != 1 /* ocsp */) { | |
10181 goto format_loser; | |
10182 } | |
10183 | |
10184 len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); | |
10185 if (len != length) { | |
10186 goto format_loser; | |
10187 } | |
10188 | |
10189 #define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */ | |
10190 if (length > MAX_CERTSTATUS_LEN) | |
10191 goto format_loser; | |
10192 #undef MAX_CERTSTATUS_LEN | |
10193 | |
10194 /* Array size 1, because we currently implement single-stapling only */ | |
10195 SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1); | |
10196 if (!ss->sec.ci.sid->peerCertStatus.items) | |
10197 return SECFailure; | |
10198 | |
10199 ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length); | |
10200 | |
10201 if (!ss->sec.ci.sid->peerCertStatus.items[0].data) { | |
10202 SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE); | |
10203 return SECFailure; | |
10204 } | |
10205 | |
10206 PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length); | |
10207 ss->sec.ci.sid->peerCertStatus.items[0].len = length; | |
10208 ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer; | |
10209 | |
10210 return ssl3_AuthCertificate(ss); | |
10211 | |
10212 format_loser: | |
10213 return ssl3_DecodeError(ss); | |
10214 } | |
10215 | |
10216 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete | |
10217 * ssl3 Certificate message. | |
10218 * Caller must hold Handshake and RecvBuf locks. | |
10219 */ | |
10220 static SECStatus | |
10221 ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
10222 { | |
10223 ssl3CertNode * c; | |
10224 ssl3CertNode * lastCert = NULL; | |
10225 PRInt32 remaining = 0; | |
10226 PRInt32 size; | |
10227 SECStatus rv; | |
10228 PRBool isServer = (PRBool)(!!ss->sec.isServer); | |
10229 PRBool isTLS; | |
10230 SSL3AlertDescription desc; | |
10231 int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE; | |
10232 SECItem certItem; | |
10233 | |
10234 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake", | |
10235 SSL_GETPID(), ss->fd)); | |
10236 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
10237 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
10238 | |
10239 if ((ss->ssl3.hs.ws != wait_server_cert) && | |
10240 (ss->ssl3.hs.ws != wait_client_cert)) { | |
10241 desc = unexpected_message; | |
10242 errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE; | |
10243 goto alert_loser; | |
10244 } | |
10245 | |
10246 if (ss->sec.peerCert != NULL) { | |
10247 if (ss->sec.peerKey) { | |
10248 SECKEY_DestroyPublicKey(ss->sec.peerKey); | |
10249 ss->sec.peerKey = NULL; | |
10250 } | |
10251 CERT_DestroyCertificate(ss->sec.peerCert); | |
10252 ss->sec.peerCert = NULL; | |
10253 } | |
10254 | |
10255 ssl3_CleanupPeerCerts(ss); | |
10256 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); | |
10257 | |
10258 /* It is reported that some TLS client sends a Certificate message | |
10259 ** with a zero-length message body. We'll treat that case like a | |
10260 ** normal no_certificates message to maximize interoperability. | |
10261 */ | |
10262 if (length) { | |
10263 remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); | |
10264 if (remaining < 0) | |
10265 goto loser; /* fatal alert already sent by ConsumeHandshake. */ | |
10266 if ((PRUint32)remaining > length) | |
10267 goto decode_loser; | |
10268 } | |
10269 | |
10270 if (!remaining) { | |
10271 if (!(isTLS && isServer)) { | |
10272 desc = bad_certificate; | |
10273 goto alert_loser; | |
10274 } | |
10275 /* This is TLS's version of a no_certificate alert. */ | |
10276 /* I'm a server. I've requested a client cert. He hasn't got one. */ | |
10277 rv = ssl3_HandleNoCertificate(ss); | |
10278 if (rv != SECSuccess) { | |
10279 errCode = PORT_GetError(); | |
10280 goto loser; | |
10281 } | |
10282 ss->ssl3.hs.ws = wait_client_key; | |
10283 return SECSuccess; | |
10284 } | |
10285 | |
10286 ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); | |
10287 if (ss->ssl3.peerCertArena == NULL) { | |
10288 goto loser; /* don't send alerts on memory errors */ | |
10289 } | |
10290 | |
10291 /* First get the peer cert. */ | |
10292 remaining -= 3; | |
10293 if (remaining < 0) | |
10294 goto decode_loser; | |
10295 | |
10296 size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); | |
10297 if (size <= 0) | |
10298 goto loser; /* fatal alert already sent by ConsumeHandshake. */ | |
10299 | |
10300 if (remaining < size) | |
10301 goto decode_loser; | |
10302 | |
10303 certItem.data = b; | |
10304 certItem.len = size; | |
10305 b += size; | |
10306 length -= size; | |
10307 remaining -= size; | |
10308 | |
10309 ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, | |
10310 PR_FALSE, PR_TRUE); | |
10311 if (ss->sec.peerCert == NULL) { | |
10312 /* We should report an alert if the cert was bad, but not if the | |
10313 * problem was just some local problem, like memory error. | |
10314 */ | |
10315 goto ambiguous_err; | |
10316 } | |
10317 | |
10318 /* Now get all of the CA certs. */ | |
10319 while (remaining > 0) { | |
10320 remaining -= 3; | |
10321 if (remaining < 0) | |
10322 goto decode_loser; | |
10323 | |
10324 size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); | |
10325 if (size <= 0) | |
10326 goto loser; /* fatal alert already sent by ConsumeHandshake. */ | |
10327 | |
10328 if (remaining < size) | |
10329 goto decode_loser; | |
10330 | |
10331 certItem.data = b; | |
10332 certItem.len = size; | |
10333 b += size; | |
10334 length -= size; | |
10335 remaining -= size; | |
10336 | |
10337 c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode); | |
10338 if (c == NULL) { | |
10339 goto loser; /* don't send alerts on memory errors */ | |
10340 } | |
10341 | |
10342 c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, | |
10343 PR_FALSE, PR_TRUE); | |
10344 if (c->cert == NULL) { | |
10345 goto ambiguous_err; | |
10346 } | |
10347 | |
10348 c->next = NULL; | |
10349 if (lastCert) { | |
10350 lastCert->next = c; | |
10351 } else { | |
10352 ss->ssl3.peerCertChain = c; | |
10353 } | |
10354 lastCert = c; | |
10355 } | |
10356 | |
10357 if (remaining != 0) | |
10358 goto decode_loser; | |
10359 | |
10360 SECKEY_UpdateCertPQG(ss->sec.peerCert); | |
10361 | |
10362 if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) { | |
10363 ss->ssl3.hs.ws = wait_certificate_status; | |
10364 rv = SECSuccess; | |
10365 } else { | |
10366 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ | |
10367 } | |
10368 | |
10369 return rv; | |
10370 | |
10371 ambiguous_err: | |
10372 errCode = PORT_GetError(); | |
10373 switch (errCode) { | |
10374 case PR_OUT_OF_MEMORY_ERROR: | |
10375 case SEC_ERROR_BAD_DATABASE: | |
10376 case SEC_ERROR_NO_MEMORY: | |
10377 if (isTLS) { | |
10378 desc = internal_error; | |
10379 goto alert_loser; | |
10380 } | |
10381 goto loser; | |
10382 } | |
10383 ssl3_SendAlertForCertError(ss, errCode); | |
10384 goto loser; | |
10385 | |
10386 decode_loser: | |
10387 desc = isTLS ? decode_error : bad_certificate; | |
10388 | |
10389 alert_loser: | |
10390 (void)SSL3_SendAlert(ss, alert_fatal, desc); | |
10391 | |
10392 loser: | |
10393 (void)ssl_MapLowLevelError(errCode); | |
10394 return SECFailure; | |
10395 } | |
10396 | |
10397 static SECStatus | |
10398 ssl3_AuthCertificate(sslSocket *ss) | |
10399 { | |
10400 SECStatus rv; | |
10401 PRBool isServer = (PRBool)(!!ss->sec.isServer); | |
10402 int errCode; | |
10403 | |
10404 ss->ssl3.hs.authCertificatePending = PR_FALSE; | |
10405 | |
10406 /* | |
10407 * Ask caller-supplied callback function to validate cert chain. | |
10408 */ | |
10409 rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd, | |
10410 PR_TRUE, isServer); | |
10411 if (rv) { | |
10412 errCode = PORT_GetError(); | |
10413 if (rv != SECWouldBlock) { | |
10414 if (ss->handleBadCert) { | |
10415 rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd); | |
10416 } | |
10417 } | |
10418 | |
10419 if (rv == SECWouldBlock) { | |
10420 if (ss->sec.isServer) { | |
10421 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS; | |
10422 rv = SECFailure; | |
10423 goto loser; | |
10424 } | |
10425 | |
10426 ss->ssl3.hs.authCertificatePending = PR_TRUE; | |
10427 rv = SECSuccess; | |
10428 } | |
10429 | |
10430 if (rv != SECSuccess) { | |
10431 ssl3_SendAlertForCertError(ss, errCode); | |
10432 goto loser; | |
10433 } | |
10434 } | |
10435 | |
10436 ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert); | |
10437 ssl3_CopyPeerCertsToSID(ss->ssl3.peerCertChain, ss->sec.ci.sid); | |
10438 | |
10439 if (!ss->sec.isServer) { | |
10440 CERTCertificate *cert = ss->sec.peerCert; | |
10441 | |
10442 /* set the server authentication and key exchange types and sizes | |
10443 ** from the value in the cert. If the key exchange key is different, | |
10444 ** it will get fixed when we handle the server key exchange message. | |
10445 */ | |
10446 SECKEYPublicKey * pubKey = CERT_ExtractPublicKey(cert); | |
10447 ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; | |
10448 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; | |
10449 if (pubKey) { | |
10450 ss->sec.keaKeyBits = ss->sec.authKeyBits = | |
10451 SECKEY_PublicKeyStrengthInBits(pubKey); | |
10452 #ifdef NSS_ENABLE_ECC | |
10453 if (ss->sec.keaType == kt_ecdh) { | |
10454 /* Get authKeyBits from signing key. | |
10455 * XXX The code below uses a quick approximation of | |
10456 * key size based on cert->signatureWrap.signature.data | |
10457 * (which contains the DER encoded signature). The field | |
10458 * cert->signatureWrap.signature.len contains the | |
10459 * length of the encoded signature in bits. | |
10460 */ | |
10461 if (ss->ssl3.hs.kea_def->kea == kea_ecdh_ecdsa) { | |
10462 ss->sec.authKeyBits = | |
10463 cert->signatureWrap.signature.data[3]*8; | |
10464 if (cert->signatureWrap.signature.data[4] == 0x00) | |
10465 ss->sec.authKeyBits -= 8; | |
10466 /* | |
10467 * XXX: if cert is not signed by ecdsa we should | |
10468 * destroy pubKey and goto bad_cert | |
10469 */ | |
10470 } else if (ss->ssl3.hs.kea_def->kea == kea_ecdh_rsa) { | |
10471 ss->sec.authKeyBits = cert->signatureWrap.signature.len; | |
10472 /* | |
10473 * XXX: if cert is not signed by rsa we should | |
10474 * destroy pubKey and goto bad_cert | |
10475 */ | |
10476 } | |
10477 } | |
10478 #endif /* NSS_ENABLE_ECC */ | |
10479 SECKEY_DestroyPublicKey(pubKey); | |
10480 pubKey = NULL; | |
10481 } | |
10482 | |
10483 ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */ | |
10484 if (ss->ssl3.hs.kea_def->is_limited || | |
10485 /* XXX OR server cert is signing only. */ | |
10486 #ifdef NSS_ENABLE_ECC | |
10487 ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa || | |
10488 ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa || | |
10489 #endif /* NSS_ENABLE_ECC */ | |
10490 ss->ssl3.hs.kea_def->exchKeyType == kt_dh) { | |
10491 ss->ssl3.hs.ws = wait_server_key; /* allow server_key_exchange */ | |
10492 } | |
10493 } else { | |
10494 ss->ssl3.hs.ws = wait_client_key; | |
10495 } | |
10496 | |
10497 PORT_Assert(rv == SECSuccess); | |
10498 if (rv != SECSuccess) { | |
10499 errCode = SEC_ERROR_LIBRARY_FAILURE; | |
10500 rv = SECFailure; | |
10501 goto loser; | |
10502 } | |
10503 | |
10504 return rv; | |
10505 | |
10506 loser: | |
10507 (void)ssl_MapLowLevelError(errCode); | |
10508 return SECFailure; | |
10509 } | |
10510 | |
10511 static SECStatus ssl3_FinishHandshake(sslSocket *ss); | |
10512 | |
10513 static SECStatus | |
10514 ssl3_AlwaysFail(sslSocket * ss) | |
10515 { | |
10516 PORT_SetError(PR_INVALID_STATE_ERROR); | |
10517 return SECFailure; | |
10518 } | |
10519 | |
10520 /* Caller must hold 1stHandshakeLock. | |
10521 */ | |
10522 SECStatus | |
10523 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error) | |
10524 { | |
10525 SECStatus rv; | |
10526 | |
10527 PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); | |
10528 | |
10529 if (ss->sec.isServer) { | |
10530 PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS); | |
10531 return SECFailure; | |
10532 } | |
10533 | |
10534 ssl_GetRecvBufLock(ss); | |
10535 ssl_GetSSL3HandshakeLock(ss); | |
10536 | |
10537 if (!ss->ssl3.hs.authCertificatePending) { | |
10538 PORT_SetError(PR_INVALID_STATE_ERROR); | |
10539 rv = SECFailure; | |
10540 goto done; | |
10541 } | |
10542 | |
10543 ss->ssl3.hs.authCertificatePending = PR_FALSE; | |
10544 | |
10545 if (error != 0) { | |
10546 ss->ssl3.hs.restartTarget = ssl3_AlwaysFail; | |
10547 ssl3_SendAlertForCertError(ss, error); | |
10548 rv = SECSuccess; | |
10549 } else if (ss->ssl3.hs.restartTarget != NULL) { | |
10550 sslRestartTarget target = ss->ssl3.hs.restartTarget; | |
10551 ss->ssl3.hs.restartTarget = NULL; | |
10552 | |
10553 if (target == ssl3_FinishHandshake) { | |
10554 SSL_TRC(3,("%d: SSL3[%p]: certificate authentication lost the race" | |
10555 " with peer's finished message", SSL_GETPID(), ss->fd)); | |
10556 } | |
10557 | |
10558 rv = target(ss); | |
10559 /* Even if we blocked here, we have accomplished enough to claim | |
10560 * success. Any remaining work will be taken care of by subsequent | |
10561 * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc. | |
10562 */ | |
10563 if (rv == SECWouldBlock) { | |
10564 rv = SECSuccess; | |
10565 } | |
10566 } else { | |
10567 SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with" | |
10568 " peer's finished message", SSL_GETPID(), ss->fd)); | |
10569 | |
10570 PORT_Assert(!ss->ssl3.hs.isResuming); | |
10571 PORT_Assert(ss->ssl3.hs.ws != idle_handshake); | |
10572 | |
10573 if (ss->opt.enableFalseStart && | |
10574 !ss->firstHsDone && | |
10575 !ss->ssl3.hs.isResuming && | |
10576 ssl3_WaitingForStartOfServerSecondRound(ss)) { | |
10577 /* ssl3_SendClientSecondRound deferred the false start check because | |
10578 * certificate authentication was pending, so we do it now if we sti
ll | |
10579 * haven't received any of the server's second round yet. | |
10580 */ | |
10581 rv = ssl3_CheckFalseStart(ss); | |
10582 } else { | |
10583 rv = SECSuccess; | |
10584 } | |
10585 } | |
10586 | |
10587 done: | |
10588 ssl_ReleaseSSL3HandshakeLock(ss); | |
10589 ssl_ReleaseRecvBufLock(ss); | |
10590 | |
10591 return rv; | |
10592 } | |
10593 | |
10594 static SECStatus | |
10595 ssl3_ComputeTLSFinished(ssl3CipherSpec *spec, | |
10596 PRBool isServer, | |
10597 const SSL3Hashes * hashes, | |
10598 TLSFinished * tlsFinished) | |
10599 { | |
10600 const char * label; | |
10601 unsigned int len; | |
10602 SECStatus rv; | |
10603 | |
10604 label = isServer ? "server finished" : "client finished"; | |
10605 len = 15; | |
10606 | |
10607 rv = ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw, | |
10608 hashes->len, tlsFinished->verify_data, | |
10609 sizeof tlsFinished->verify_data); | |
10610 | |
10611 return rv; | |
10612 } | |
10613 | |
10614 /* The calling function must acquire and release the appropriate | |
10615 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for | |
10616 * ss->ssl3.crSpec). | |
10617 */ | |
10618 SECStatus | |
10619 ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label, | |
10620 unsigned int labelLen, const unsigned char *val, unsigned int valLen, | |
10621 unsigned char *out, unsigned int outLen) | |
10622 { | |
10623 SECStatus rv = SECSuccess; | |
10624 | |
10625 if (spec->master_secret && !spec->bypassCiphers) { | |
10626 SECItem param = {siBuffer, NULL, 0}; | |
10627 CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL; | |
10628 PK11Context *prf_context; | |
10629 unsigned int retLen; | |
10630 | |
10631 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
10632 mech = CKM_NSS_TLS_PRF_GENERAL_SHA256; | |
10633 } | |
10634 prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN, | |
10635 spec->master_secret, ¶m); | |
10636 if (!prf_context) | |
10637 return SECFailure; | |
10638 | |
10639 rv = PK11_DigestBegin(prf_context); | |
10640 rv |= PK11_DigestOp(prf_context, (unsigned char *) label, labelLen); | |
10641 rv |= PK11_DigestOp(prf_context, val, valLen); | |
10642 rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen); | |
10643 PORT_Assert(rv != SECSuccess || retLen == outLen); | |
10644 | |
10645 PK11_DestroyContext(prf_context, PR_TRUE); | |
10646 } else { | |
10647 /* bypass PKCS11 */ | |
10648 #ifdef NO_PKCS11_BYPASS | |
10649 PORT_Assert(spec->master_secret); | |
10650 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
10651 rv = SECFailure; | |
10652 #else | |
10653 SECItem inData = { siBuffer, }; | |
10654 SECItem outData = { siBuffer, }; | |
10655 PRBool isFIPS = PR_FALSE; | |
10656 | |
10657 inData.data = (unsigned char *) val; | |
10658 inData.len = valLen; | |
10659 outData.data = out; | |
10660 outData.len = outLen; | |
10661 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
10662 rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData, | |
10663 &outData, isFIPS); | |
10664 } else { | |
10665 rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS); | |
10666 } | |
10667 PORT_Assert(rv != SECSuccess || outData.len == outLen); | |
10668 #endif | |
10669 } | |
10670 return rv; | |
10671 } | |
10672 | |
10673 /* called from ssl3_SendClientSecondRound | |
10674 * ssl3_HandleFinished | |
10675 */ | |
10676 static SECStatus | |
10677 ssl3_SendNextProto(sslSocket *ss) | |
10678 { | |
10679 SECStatus rv; | |
10680 int padding_len; | |
10681 static const unsigned char padding[32] = {0}; | |
10682 | |
10683 if (ss->ssl3.nextProto.len == 0 || | |
10684 ss->ssl3.nextProtoState == SSL_NEXT_PROTO_SELECTED) { | |
10685 return SECSuccess; | |
10686 } | |
10687 | |
10688 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
10689 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10690 | |
10691 padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32); | |
10692 | |
10693 rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len + | |
10694 2 + padding_len); | |
10695 if (rv != SECSuccess) { | |
10696 return rv; /* error code set by AppendHandshakeHeader */ | |
10697 } | |
10698 rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data, | |
10699 ss->ssl3.nextProto.len, 1); | |
10700 if (rv != SECSuccess) { | |
10701 return rv; /* error code set by AppendHandshake */ | |
10702 } | |
10703 rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1); | |
10704 if (rv != SECSuccess) { | |
10705 return rv; /* error code set by AppendHandshake */ | |
10706 } | |
10707 return rv; | |
10708 } | |
10709 | |
10710 /* called from ssl3_SendFinished | |
10711 * | |
10712 * This function is simply a debugging aid and therefore does not return a | |
10713 * SECStatus. */ | |
10714 static void | |
10715 ssl3_RecordKeyLog(sslSocket *ss) | |
10716 { | |
10717 SECStatus rv; | |
10718 SECItem *keyData; | |
10719 char buf[14 /* "CLIENT_RANDOM " */ + | |
10720 SSL3_RANDOM_LENGTH*2 /* client_random */ + | |
10721 1 /* " " */ + | |
10722 48*2 /* master secret */ + | |
10723 1 /* new line */]; | |
10724 unsigned int j; | |
10725 | |
10726 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10727 | |
10728 if (!ssl_keylog_iob) | |
10729 return; | |
10730 | |
10731 rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret); | |
10732 if (rv != SECSuccess) | |
10733 return; | |
10734 | |
10735 ssl_GetSpecReadLock(ss); | |
10736 | |
10737 /* keyData does not need to be freed. */ | |
10738 keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret); | |
10739 if (!keyData || !keyData->data || keyData->len != 48) { | |
10740 ssl_ReleaseSpecReadLock(ss); | |
10741 return; | |
10742 } | |
10743 | |
10744 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ | |
10745 | |
10746 /* There could be multiple, concurrent writers to the | |
10747 * keylog, so we have to do everything in a single call to | |
10748 * fwrite. */ | |
10749 | |
10750 memcpy(buf, "CLIENT_RANDOM ", 14); | |
10751 j = 14; | |
10752 hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH); | |
10753 j += SSL3_RANDOM_LENGTH*2; | |
10754 buf[j++] = ' '; | |
10755 hexEncode(buf + j, keyData->data, 48); | |
10756 j += 48*2; | |
10757 buf[j++] = '\n'; | |
10758 | |
10759 PORT_Assert(j == sizeof(buf)); | |
10760 | |
10761 ssl_ReleaseSpecReadLock(ss); | |
10762 | |
10763 if (fwrite(buf, sizeof(buf), 1, ssl_keylog_iob) != 1) | |
10764 return; | |
10765 fflush(ssl_keylog_iob); | |
10766 return; | |
10767 } | |
10768 | |
10769 /* called from ssl3_SendClientSecondRound | |
10770 * ssl3_HandleFinished | |
10771 */ | |
10772 static SECStatus | |
10773 ssl3_SendEncryptedExtensions(sslSocket *ss) | |
10774 { | |
10775 static const char CHANNEL_ID_MAGIC[] = "TLS Channel ID signature"; | |
10776 static const char CHANNEL_ID_RESUMPTION_MAGIC[] = "Resumption"; | |
10777 /* This is the ASN.1 prefix for a P-256 public key. Specifically it's: | |
10778 * SEQUENCE | |
10779 * SEQUENCE | |
10780 * OID id-ecPublicKey | |
10781 * OID prime256v1 | |
10782 * BIT STRING, length 66, 0 trailing bits: 0x04 | |
10783 * | |
10784 * The 0x04 in the BIT STRING is the prefix for an uncompressed, X9.62 | |
10785 * public key. Following that are the two field elements as 32-byte, | |
10786 * big-endian numbers, as required by the Channel ID. */ | |
10787 static const unsigned char P256_SPKI_PREFIX[] = { | |
10788 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, | |
10789 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, | |
10790 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, | |
10791 0x42, 0x00, 0x04 | |
10792 }; | |
10793 /* ChannelIDs are always 128 bytes long: 64 bytes of P-256 public key and 64 | |
10794 * bytes of ECDSA signature. */ | |
10795 static const int CHANNEL_ID_PUBLIC_KEY_LENGTH = 64; | |
10796 static const int CHANNEL_ID_LENGTH = 128; | |
10797 | |
10798 SECStatus rv = SECFailure; | |
10799 SECItem *spki = NULL; | |
10800 SSL3Hashes hashes; | |
10801 const unsigned char *pub_bytes; | |
10802 unsigned char signed_data[sizeof(CHANNEL_ID_MAGIC) + | |
10803 sizeof(CHANNEL_ID_RESUMPTION_MAGIC) + | |
10804 sizeof(SSL3Hashes)*2]; | |
10805 size_t signed_data_len; | |
10806 unsigned char digest[SHA256_LENGTH]; | |
10807 SECItem digest_item; | |
10808 unsigned char signature[64]; | |
10809 SECItem signature_item; | |
10810 | |
10811 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
10812 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10813 | |
10814 if (ss->ssl3.channelID == NULL) | |
10815 return SECSuccess; | |
10816 | |
10817 PORT_Assert(ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)); | |
10818 | |
10819 if (SECKEY_GetPrivateKeyType(ss->ssl3.channelID) != ecKey || | |
10820 PK11_SignatureLen(ss->ssl3.channelID) != sizeof(signature)) { | |
10821 PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY); | |
10822 rv = SECFailure; | |
10823 goto loser; | |
10824 } | |
10825 | |
10826 ssl_GetSpecReadLock(ss); | |
10827 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0); | |
10828 ssl_ReleaseSpecReadLock(ss); | |
10829 | |
10830 if (rv != SECSuccess) | |
10831 goto loser; | |
10832 | |
10833 rv = ssl3_AppendHandshakeHeader(ss, encrypted_extensions, | |
10834 2 + 2 + CHANNEL_ID_LENGTH); | |
10835 if (rv != SECSuccess) | |
10836 goto loser; /* error code set by AppendHandshakeHeader */ | |
10837 rv = ssl3_AppendHandshakeNumber(ss, ssl_channel_id_xtn, 2); | |
10838 if (rv != SECSuccess) | |
10839 goto loser; /* error code set by AppendHandshake */ | |
10840 rv = ssl3_AppendHandshakeNumber(ss, CHANNEL_ID_LENGTH, 2); | |
10841 if (rv != SECSuccess) | |
10842 goto loser; /* error code set by AppendHandshake */ | |
10843 | |
10844 spki = SECKEY_EncodeDERSubjectPublicKeyInfo(ss->ssl3.channelIDPub); | |
10845 | |
10846 if (spki->len != sizeof(P256_SPKI_PREFIX) + CHANNEL_ID_PUBLIC_KEY_LENGTH || | |
10847 memcmp(spki->data, P256_SPKI_PREFIX, sizeof(P256_SPKI_PREFIX)) != 0) { | |
10848 PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY); | |
10849 rv = SECFailure; | |
10850 goto loser; | |
10851 } | |
10852 | |
10853 pub_bytes = spki->data + sizeof(P256_SPKI_PREFIX); | |
10854 | |
10855 signed_data_len = 0; | |
10856 memcpy(signed_data + signed_data_len, CHANNEL_ID_MAGIC, | |
10857 sizeof(CHANNEL_ID_MAGIC)); | |
10858 signed_data_len += sizeof(CHANNEL_ID_MAGIC); | |
10859 if (ss->ssl3.hs.isResuming) { | |
10860 SECItem *originalHandshakeHash = | |
10861 &ss->sec.ci.sid->u.ssl3.originalHandshakeHash; | |
10862 PORT_Assert(originalHandshakeHash->len > 0); | |
10863 | |
10864 memcpy(signed_data + signed_data_len, CHANNEL_ID_RESUMPTION_MAGIC, | |
10865 sizeof(CHANNEL_ID_RESUMPTION_MAGIC)); | |
10866 signed_data_len += sizeof(CHANNEL_ID_RESUMPTION_MAGIC); | |
10867 memcpy(signed_data + signed_data_len, originalHandshakeHash->data, | |
10868 originalHandshakeHash->len); | |
10869 signed_data_len += originalHandshakeHash->len; | |
10870 } | |
10871 memcpy(signed_data + signed_data_len, hashes.u.raw, hashes.len); | |
10872 signed_data_len += hashes.len; | |
10873 | |
10874 rv = PK11_HashBuf(SEC_OID_SHA256, digest, signed_data, signed_data_len); | |
10875 if (rv != SECSuccess) | |
10876 goto loser; | |
10877 | |
10878 digest_item.data = digest; | |
10879 digest_item.len = sizeof(digest); | |
10880 | |
10881 signature_item.data = signature; | |
10882 signature_item.len = sizeof(signature); | |
10883 | |
10884 rv = PK11_Sign(ss->ssl3.channelID, &signature_item, &digest_item); | |
10885 if (rv != SECSuccess) | |
10886 goto loser; | |
10887 | |
10888 rv = ssl3_AppendHandshake(ss, pub_bytes, CHANNEL_ID_PUBLIC_KEY_LENGTH); | |
10889 if (rv != SECSuccess) | |
10890 goto loser; | |
10891 rv = ssl3_AppendHandshake(ss, signature, sizeof(signature)); | |
10892 | |
10893 loser: | |
10894 if (spki) | |
10895 SECITEM_FreeItem(spki, PR_TRUE); | |
10896 if (ss->ssl3.channelID) { | |
10897 SECKEY_DestroyPrivateKey(ss->ssl3.channelID); | |
10898 ss->ssl3.channelID = NULL; | |
10899 } | |
10900 if (ss->ssl3.channelIDPub) { | |
10901 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub); | |
10902 ss->ssl3.channelIDPub = NULL; | |
10903 } | |
10904 | |
10905 return rv; | |
10906 } | |
10907 | |
10908 /* ssl3_RestartHandshakeAfterChannelIDReq is called to restart a handshake | |
10909 * after a ChannelID callback returned SECWouldBlock. At this point we have | |
10910 * processed the server's ServerHello but not yet any further messages. We will | |
10911 * always get a message from the server after a ServerHello so either they are | |
10912 * waiting in the buffer or we'll get network I/O. */ | |
10913 SECStatus | |
10914 ssl3_RestartHandshakeAfterChannelIDReq(sslSocket *ss, | |
10915 SECKEYPublicKey *channelIDPub, | |
10916 SECKEYPrivateKey *channelID) | |
10917 { | |
10918 if (ss->handshake == 0) { | |
10919 SECKEY_DestroyPublicKey(channelIDPub); | |
10920 SECKEY_DestroyPrivateKey(channelID); | |
10921 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
10922 return SECFailure; | |
10923 } | |
10924 | |
10925 if (channelIDPub == NULL || | |
10926 channelID == NULL) { | |
10927 if (channelIDPub) | |
10928 SECKEY_DestroyPublicKey(channelIDPub); | |
10929 if (channelID) | |
10930 SECKEY_DestroyPrivateKey(channelID); | |
10931 PORT_SetError(PR_INVALID_ARGUMENT_ERROR); | |
10932 return SECFailure; | |
10933 } | |
10934 | |
10935 if (ss->ssl3.channelID) | |
10936 SECKEY_DestroyPrivateKey(ss->ssl3.channelID); | |
10937 if (ss->ssl3.channelIDPub) | |
10938 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub); | |
10939 | |
10940 ss->handshake = ssl_GatherRecord1stHandshake; | |
10941 ss->ssl3.channelID = channelID; | |
10942 ss->ssl3.channelIDPub = channelIDPub; | |
10943 | |
10944 return SECSuccess; | |
10945 } | |
10946 | |
10947 /* called from ssl3_SendClientSecondRound | |
10948 * ssl3_HandleClientHello | |
10949 * ssl3_HandleFinished | |
10950 */ | |
10951 static SECStatus | |
10952 ssl3_SendFinished(sslSocket *ss, PRInt32 flags) | |
10953 { | |
10954 ssl3CipherSpec *cwSpec; | |
10955 PRBool isTLS; | |
10956 PRBool isServer = ss->sec.isServer; | |
10957 SECStatus rv; | |
10958 SSL3Sender sender = isServer ? sender_server : sender_client; | |
10959 SSL3Hashes hashes; | |
10960 TLSFinished tlsFinished; | |
10961 | |
10962 SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd)); | |
10963 | |
10964 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
10965 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10966 | |
10967 ssl_GetSpecReadLock(ss); | |
10968 cwSpec = ss->ssl3.cwSpec; | |
10969 isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
10970 rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender); | |
10971 if (isTLS && rv == SECSuccess) { | |
10972 rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished); | |
10973 } | |
10974 ssl_ReleaseSpecReadLock(ss); | |
10975 if (rv != SECSuccess) { | |
10976 goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */ | |
10977 } | |
10978 | |
10979 if (isTLS) { | |
10980 if (isServer) | |
10981 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; | |
10982 else | |
10983 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; | |
10984 ss->ssl3.hs.finishedBytes = sizeof tlsFinished; | |
10985 rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished); | |
10986 if (rv != SECSuccess) | |
10987 goto fail; /* err set by AppendHandshake. */ | |
10988 rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished); | |
10989 if (rv != SECSuccess) | |
10990 goto fail; /* err set by AppendHandshake. */ | |
10991 } else { | |
10992 if (isServer) | |
10993 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s; | |
10994 else | |
10995 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s; | |
10996 PORT_Assert(hashes.len == sizeof hashes.u.s); | |
10997 ss->ssl3.hs.finishedBytes = sizeof hashes.u.s; | |
10998 rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s); | |
10999 if (rv != SECSuccess) | |
11000 goto fail; /* err set by AppendHandshake. */ | |
11001 rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s); | |
11002 if (rv != SECSuccess) | |
11003 goto fail; /* err set by AppendHandshake. */ | |
11004 } | |
11005 rv = ssl3_FlushHandshake(ss, flags); | |
11006 if (rv != SECSuccess) { | |
11007 goto fail; /* error code set by ssl3_FlushHandshake */ | |
11008 } | |
11009 | |
11010 ssl3_RecordKeyLog(ss); | |
11011 | |
11012 return SECSuccess; | |
11013 | |
11014 fail: | |
11015 return rv; | |
11016 } | |
11017 | |
11018 /* wrap the master secret, and put it into the SID. | |
11019 * Caller holds the Spec read lock. | |
11020 */ | |
11021 SECStatus | |
11022 ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid, | |
11023 ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType) | |
11024 { | |
11025 PK11SymKey * wrappingKey = NULL; | |
11026 PK11SlotInfo * symKeySlot; | |
11027 void * pwArg = ss->pkcs11PinArg; | |
11028 SECStatus rv = SECFailure; | |
11029 PRBool isServer = ss->sec.isServer; | |
11030 CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM; | |
11031 symKeySlot = PK11_GetSlotFromKey(spec->master_secret); | |
11032 if (!isServer) { | |
11033 int wrapKeyIndex; | |
11034 int incarnation; | |
11035 | |
11036 /* these next few functions are mere accessors and don't fail. */ | |
11037 sid->u.ssl3.masterWrapIndex = wrapKeyIndex = | |
11038 PK11_GetCurrentWrapIndex(symKeySlot); | |
11039 PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */ | |
11040 | |
11041 sid->u.ssl3.masterWrapSeries = incarnation = | |
11042 PK11_GetSlotSeries(symKeySlot); | |
11043 sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot); | |
11044 sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot); | |
11045 sid->u.ssl3.masterValid = PR_TRUE; | |
11046 /* Get the default wrapping key, for wrapping the master secret before | |
11047 * placing it in the SID cache entry. */ | |
11048 wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex, | |
11049 CKM_INVALID_MECHANISM, incarnation, | |
11050 pwArg); | |
11051 if (wrappingKey) { | |
11052 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ | |
11053 } else { | |
11054 int keyLength; | |
11055 /* if the wrappingKey doesn't exist, attempt to create it. | |
11056 * Note: we intentionally ignore errors here. If we cannot | |
11057 * generate a wrapping key, it is not fatal to this SSL connection, | |
11058 * but we will not be able to restart this session. | |
11059 */ | |
11060 mechanism = PK11_GetBestWrapMechanism(symKeySlot); | |
11061 keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism); | |
11062 /* Zero length means fixed key length algorithm, or error. | |
11063 * It's ambiguous. | |
11064 */ | |
11065 wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL, | |
11066 keyLength, pwArg); | |
11067 if (wrappingKey) { | |
11068 PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey); | |
11069 } | |
11070 } | |
11071 } else { | |
11072 /* server socket using session cache. */ | |
11073 mechanism = PK11_GetBestWrapMechanism(symKeySlot); | |
11074 if (mechanism != CKM_INVALID_MECHANISM) { | |
11075 wrappingKey = | |
11076 getWrappingKey(ss, symKeySlot, effectiveExchKeyType, | |
11077 mechanism, pwArg); | |
11078 if (wrappingKey) { | |
11079 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ | |
11080 } | |
11081 } | |
11082 } | |
11083 | |
11084 sid->u.ssl3.masterWrapMech = mechanism; | |
11085 PK11_FreeSlot(symKeySlot); | |
11086 | |
11087 if (wrappingKey) { | |
11088 SECItem wmsItem; | |
11089 | |
11090 wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret; | |
11091 wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret; | |
11092 rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey, | |
11093 spec->master_secret, &wmsItem); | |
11094 /* rv is examined below. */ | |
11095 sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len; | |
11096 PK11_FreeSymKey(wrappingKey); | |
11097 } | |
11098 return rv; | |
11099 } | |
11100 | |
11101 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete | |
11102 * ssl3 Finished message from the peer. | |
11103 * Caller must hold Handshake and RecvBuf locks. | |
11104 */ | |
11105 static SECStatus | |
11106 ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length, | |
11107 const SSL3Hashes *hashes) | |
11108 { | |
11109 sslSessionID * sid = ss->sec.ci.sid; | |
11110 SECStatus rv = SECSuccess; | |
11111 PRBool isServer = ss->sec.isServer; | |
11112 PRBool isTLS; | |
11113 SSL3KEAType effectiveExchKeyType; | |
11114 | |
11115 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
11116 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
11117 | |
11118 SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake", | |
11119 SSL_GETPID(), ss->fd)); | |
11120 | |
11121 if (ss->ssl3.hs.ws != wait_finished) { | |
11122 SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11123 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED); | |
11124 return SECFailure; | |
11125 } | |
11126 | |
11127 isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0); | |
11128 if (isTLS) { | |
11129 TLSFinished tlsFinished; | |
11130 | |
11131 if (length != sizeof tlsFinished) { | |
11132 (void)SSL3_SendAlert(ss, alert_fatal, decode_error); | |
11133 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); | |
11134 return SECFailure; | |
11135 } | |
11136 rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer, | |
11137 hashes, &tlsFinished); | |
11138 if (!isServer) | |
11139 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; | |
11140 else | |
11141 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; | |
11142 ss->ssl3.hs.finishedBytes = sizeof tlsFinished; | |
11143 if (rv != SECSuccess || | |
11144 0 != NSS_SecureMemcmp(&tlsFinished, b, length)) { | |
11145 (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error); | |
11146 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); | |
11147 return SECFailure; | |
11148 } | |
11149 } else { | |
11150 if (length != sizeof(SSL3Finished)) { | |
11151 (void)ssl3_IllegalParameter(ss); | |
11152 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); | |
11153 return SECFailure; | |
11154 } | |
11155 | |
11156 if (!isServer) | |
11157 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s; | |
11158 else | |
11159 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s; | |
11160 PORT_Assert(hashes->len == sizeof hashes->u.s); | |
11161 ss->ssl3.hs.finishedBytes = sizeof hashes->u.s; | |
11162 if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) { | |
11163 (void)ssl3_HandshakeFailure(ss); | |
11164 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); | |
11165 return SECFailure; | |
11166 } | |
11167 } | |
11168 | |
11169 ssl_GetXmitBufLock(ss); /*************************************/ | |
11170 | |
11171 if ((isServer && !ss->ssl3.hs.isResuming) || | |
11172 (!isServer && ss->ssl3.hs.isResuming)) { | |
11173 PRInt32 flags = 0; | |
11174 | |
11175 /* Send a NewSessionTicket message if the client sent us | |
11176 * either an empty session ticket, or one that did not verify. | |
11177 * (Note that if either of these conditions was met, then the | |
11178 * server has sent a SessionTicket extension in the | |
11179 * ServerHello message.) | |
11180 */ | |
11181 if (isServer && !ss->ssl3.hs.isResuming && | |
11182 ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) { | |
11183 /* RFC 5077 Section 3.3: "In the case of a full handshake, the | |
11184 * server MUST verify the client's Finished message before sending | |
11185 * the ticket." Presumably, this also means that the client's | |
11186 * certificate, if any, must be verified beforehand too. | |
11187 */ | |
11188 rv = ssl3_SendNewSessionTicket(ss); | |
11189 if (rv != SECSuccess) { | |
11190 goto xmit_loser; | |
11191 } | |
11192 } | |
11193 | |
11194 rv = ssl3_SendChangeCipherSpecs(ss); | |
11195 if (rv != SECSuccess) { | |
11196 goto xmit_loser; /* err is set. */ | |
11197 } | |
11198 /* If this thread is in SSL_SecureSend (trying to write some data) | |
11199 ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the | |
11200 ** last two handshake messages (change cipher spec and finished) | |
11201 ** will be sent in the same send/write call as the application data. | |
11202 */ | |
11203 if (ss->writerThread == PR_GetCurrentThread()) { | |
11204 flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER; | |
11205 } | |
11206 | |
11207 if (!isServer) { | |
11208 if (!ss->firstHsDone) { | |
11209 rv = ssl3_SendNextProto(ss); | |
11210 if (rv != SECSuccess) { | |
11211 goto xmit_loser; /* err code was set. */ | |
11212 } | |
11213 } | |
11214 rv = ssl3_SendEncryptedExtensions(ss); | |
11215 if (rv != SECSuccess) | |
11216 goto xmit_loser; /* err code was set. */ | |
11217 } | |
11218 | |
11219 if (IS_DTLS(ss)) { | |
11220 flags |= ssl_SEND_FLAG_NO_RETRANSMIT; | |
11221 } | |
11222 | |
11223 rv = ssl3_SendFinished(ss, flags); | |
11224 if (rv != SECSuccess) { | |
11225 goto xmit_loser; /* err is set. */ | |
11226 } | |
11227 } | |
11228 | |
11229 xmit_loser: | |
11230 ssl_ReleaseXmitBufLock(ss); /*************************************/ | |
11231 if (rv != SECSuccess) { | |
11232 return rv; | |
11233 } | |
11234 | |
11235 if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) { | |
11236 effectiveExchKeyType = kt_rsa; | |
11237 } else { | |
11238 effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; | |
11239 } | |
11240 | |
11241 if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) { | |
11242 /* fill in the sid */ | |
11243 sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite; | |
11244 sid->u.ssl3.compression = ss->ssl3.hs.compression; | |
11245 sid->u.ssl3.policy = ss->ssl3.policy; | |
11246 #ifdef NSS_ENABLE_ECC | |
11247 sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves; | |
11248 #endif | |
11249 sid->u.ssl3.exchKeyType = effectiveExchKeyType; | |
11250 sid->version = ss->version; | |
11251 sid->authAlgorithm = ss->sec.authAlgorithm; | |
11252 sid->authKeyBits = ss->sec.authKeyBits; | |
11253 sid->keaType = ss->sec.keaType; | |
11254 sid->keaKeyBits = ss->sec.keaKeyBits; | |
11255 sid->lastAccessTime = sid->creationTime = ssl_Time(); | |
11256 sid->expirationTime = sid->creationTime + ssl3_sid_timeout; | |
11257 sid->localCert = CERT_DupCertificate(ss->sec.localCert); | |
11258 | |
11259 ssl_GetSpecReadLock(ss); /*************************************/ | |
11260 | |
11261 /* Copy the master secret (wrapped or unwrapped) into the sid */ | |
11262 if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) { | |
11263 sid->u.ssl3.keys.wrapped_master_secret_len = | |
11264 ss->ssl3.crSpec->msItem.len; | |
11265 memcpy(sid->u.ssl3.keys.wrapped_master_secret, | |
11266 ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len); | |
11267 sid->u.ssl3.masterValid = PR_TRUE; | |
11268 sid->u.ssl3.keys.msIsWrapped = PR_FALSE; | |
11269 rv = SECSuccess; | |
11270 } else { | |
11271 rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid, | |
11272 ss->ssl3.crSpec, | |
11273 effectiveExchKeyType); | |
11274 sid->u.ssl3.keys.msIsWrapped = PR_TRUE; | |
11275 } | |
11276 ssl_ReleaseSpecReadLock(ss); /*************************************/ | |
11277 | |
11278 /* If the wrap failed, we don't cache the sid. | |
11279 * The connection continues normally however. | |
11280 */ | |
11281 ss->ssl3.hs.cacheSID = rv == SECSuccess; | |
11282 } | |
11283 | |
11284 if (ss->ssl3.hs.authCertificatePending) { | |
11285 if (ss->ssl3.hs.restartTarget) { | |
11286 PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget"); | |
11287 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
11288 return SECFailure; | |
11289 } | |
11290 | |
11291 ss->ssl3.hs.restartTarget = ssl3_FinishHandshake; | |
11292 return SECWouldBlock; | |
11293 } | |
11294 | |
11295 rv = ssl3_FinishHandshake(ss); | |
11296 return rv; | |
11297 } | |
11298 | |
11299 /* The return type is SECStatus instead of void because this function needs | |
11300 * to have type sslRestartTarget. | |
11301 */ | |
11302 SECStatus | |
11303 ssl3_FinishHandshake(sslSocket * ss) | |
11304 { | |
11305 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
11306 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
11307 PORT_Assert( ss->ssl3.hs.restartTarget == NULL ); | |
11308 | |
11309 /* The first handshake is now completed. */ | |
11310 ss->handshake = NULL; | |
11311 | |
11312 /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid | |
11313 * until it has verified the server's Finished message." When the server | |
11314 * sends a NewSessionTicket in a resumption handshake, we must wait until | |
11315 * the handshake is finished (we have verified the server's Finished | |
11316 * AND the server's certificate) before we update the ticket in the sid. | |
11317 * | |
11318 * This must be done before we call (*ss->sec.cache)(ss->sec.ci.sid) | |
11319 * because CacheSID requires the session ticket to already be set, and also | |
11320 * because of the lazy lock creation scheme used by CacheSID and | |
11321 * ssl3_SetSIDSessionTicket. | |
11322 */ | |
11323 if (ss->ssl3.hs.receivedNewSessionTicket) { | |
11324 PORT_Assert(!ss->sec.isServer); | |
11325 ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ss->ssl3.hs.newSessionTicket); | |
11326 /* The sid took over the ticket data */ | |
11327 PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); | |
11328 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; | |
11329 } | |
11330 | |
11331 if (ss->ssl3.hs.cacheSID && ss->sec.isServer) { | |
11332 PORT_Assert(ss->sec.ci.sid->cached == never_cached); | |
11333 (*ss->sec.cache)(ss->sec.ci.sid); | |
11334 ss->ssl3.hs.cacheSID = PR_FALSE; | |
11335 } | |
11336 | |
11337 ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */ | |
11338 ss->ssl3.hs.ws = idle_handshake; | |
11339 | |
11340 ssl_FinishHandshake(ss); | |
11341 | |
11342 return SECSuccess; | |
11343 } | |
11344 | |
11345 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3 | |
11346 * hanshake message. | |
11347 * Caller must hold Handshake and RecvBuf locks. | |
11348 */ | |
11349 SECStatus | |
11350 ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
11351 { | |
11352 SECStatus rv = SECSuccess; | |
11353 SSL3HandshakeType type = ss->ssl3.hs.msg_type; | |
11354 SSL3Hashes hashes; /* computed hashes are put here. */ | |
11355 PRUint8 hdr[4]; | |
11356 PRUint8 dtlsData[8]; | |
11357 | |
11358 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
11359 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
11360 /* | |
11361 * We have to compute the hashes before we update them with the | |
11362 * current message. | |
11363 */ | |
11364 ssl_GetSpecReadLock(ss); /************************************/ | |
11365 if((type == finished) || (type == certificate_verify)) { | |
11366 SSL3Sender sender = (SSL3Sender)0; | |
11367 ssl3CipherSpec *rSpec = ss->ssl3.prSpec; | |
11368 | |
11369 if (type == finished) { | |
11370 sender = ss->sec.isServer ? sender_client : sender_server; | |
11371 rSpec = ss->ssl3.crSpec; | |
11372 } | |
11373 rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender); | |
11374 } | |
11375 ssl_ReleaseSpecReadLock(ss); /************************************/ | |
11376 if (rv != SECSuccess) { | |
11377 return rv; /* error code was set by ssl3_ComputeHandshakeHashes*/ | |
11378 } | |
11379 SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(), | |
11380 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type))); | |
11381 | |
11382 hdr[0] = (PRUint8)ss->ssl3.hs.msg_type; | |
11383 hdr[1] = (PRUint8)(length >> 16); | |
11384 hdr[2] = (PRUint8)(length >> 8); | |
11385 hdr[3] = (PRUint8)(length ); | |
11386 | |
11387 /* Start new handshake hashes when we start a new handshake */ | |
11388 if (ss->ssl3.hs.msg_type == client_hello) { | |
11389 rv = ssl3_RestartHandshakeHashes(ss); | |
11390 if (rv != SECSuccess) { | |
11391 return rv; | |
11392 } | |
11393 } | |
11394 /* We should not include hello_request and hello_verify_request messages | |
11395 * in the handshake hashes */ | |
11396 if ((ss->ssl3.hs.msg_type != hello_request) && | |
11397 (ss->ssl3.hs.msg_type != hello_verify_request)) { | |
11398 rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4); | |
11399 if (rv != SECSuccess) return rv; /* err code already set. */ | |
11400 | |
11401 /* Extra data to simulate a complete DTLS handshake fragment */ | |
11402 if (IS_DTLS(ss)) { | |
11403 /* Sequence number */ | |
11404 dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq); | |
11405 dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq); | |
11406 | |
11407 /* Fragment offset */ | |
11408 dtlsData[2] = 0; | |
11409 dtlsData[3] = 0; | |
11410 dtlsData[4] = 0; | |
11411 | |
11412 /* Fragment length */ | |
11413 dtlsData[5] = (PRUint8)(length >> 16); | |
11414 dtlsData[6] = (PRUint8)(length >> 8); | |
11415 dtlsData[7] = (PRUint8)(length ); | |
11416 | |
11417 rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) dtlsData, | |
11418 sizeof(dtlsData)); | |
11419 if (rv != SECSuccess) return rv; /* err code already set. */ | |
11420 } | |
11421 | |
11422 /* The message body */ | |
11423 rv = ssl3_UpdateHandshakeHashes(ss, b, length); | |
11424 if (rv != SECSuccess) return rv; /* err code already set. */ | |
11425 } | |
11426 | |
11427 PORT_SetError(0); /* each message starts with no error. */ | |
11428 | |
11429 if (ss->ssl3.hs.ws == wait_certificate_status && | |
11430 ss->ssl3.hs.msg_type != certificate_status) { | |
11431 /* If we negotiated the certificate_status extension then we deferred | |
11432 * certificate validation until we get the CertificateStatus messsage. | |
11433 * But the CertificateStatus message is optional. If the server did | |
11434 * not send it then we need to validate the certificate now. If the | |
11435 * server does send the CertificateStatus message then we will | |
11436 * authenticate the certificate in ssl3_HandleCertificateStatus. | |
11437 */ | |
11438 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ | |
11439 PORT_Assert(rv != SECWouldBlock); | |
11440 if (rv != SECSuccess) { | |
11441 return rv; | |
11442 } | |
11443 } | |
11444 | |
11445 switch (ss->ssl3.hs.msg_type) { | |
11446 case hello_request: | |
11447 if (length != 0) { | |
11448 (void)ssl3_DecodeError(ss); | |
11449 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST); | |
11450 return SECFailure; | |
11451 } | |
11452 if (ss->sec.isServer) { | |
11453 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11454 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); | |
11455 return SECFailure; | |
11456 } | |
11457 rv = ssl3_HandleHelloRequest(ss); | |
11458 break; | |
11459 case client_hello: | |
11460 if (!ss->sec.isServer) { | |
11461 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11462 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO); | |
11463 return SECFailure; | |
11464 } | |
11465 rv = ssl3_HandleClientHello(ss, b, length); | |
11466 break; | |
11467 case server_hello: | |
11468 if (ss->sec.isServer) { | |
11469 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11470 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO); | |
11471 return SECFailure; | |
11472 } | |
11473 rv = ssl3_HandleServerHello(ss, b, length); | |
11474 break; | |
11475 case hello_verify_request: | |
11476 if (!IS_DTLS(ss) || ss->sec.isServer) { | |
11477 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11478 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST); | |
11479 return SECFailure; | |
11480 } | |
11481 rv = dtls_HandleHelloVerifyRequest(ss, b, length); | |
11482 break; | |
11483 case certificate: | |
11484 rv = ssl3_HandleCertificate(ss, b, length); | |
11485 break; | |
11486 case certificate_status: | |
11487 rv = ssl3_HandleCertificateStatus(ss, b, length); | |
11488 break; | |
11489 case server_key_exchange: | |
11490 if (ss->sec.isServer) { | |
11491 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11492 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH); | |
11493 return SECFailure; | |
11494 } | |
11495 rv = ssl3_HandleServerKeyExchange(ss, b, length); | |
11496 break; | |
11497 case certificate_request: | |
11498 if (ss->sec.isServer) { | |
11499 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11500 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST); | |
11501 return SECFailure; | |
11502 } | |
11503 rv = ssl3_HandleCertificateRequest(ss, b, length); | |
11504 break; | |
11505 case server_hello_done: | |
11506 if (length != 0) { | |
11507 (void)ssl3_DecodeError(ss); | |
11508 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE); | |
11509 return SECFailure; | |
11510 } | |
11511 if (ss->sec.isServer) { | |
11512 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11513 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); | |
11514 return SECFailure; | |
11515 } | |
11516 rv = ssl3_HandleServerHelloDone(ss); | |
11517 break; | |
11518 case certificate_verify: | |
11519 if (!ss->sec.isServer) { | |
11520 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11521 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY); | |
11522 return SECFailure; | |
11523 } | |
11524 rv = ssl3_HandleCertificateVerify(ss, b, length, &hashes); | |
11525 break; | |
11526 case client_key_exchange: | |
11527 if (!ss->sec.isServer) { | |
11528 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11529 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); | |
11530 return SECFailure; | |
11531 } | |
11532 rv = ssl3_HandleClientKeyExchange(ss, b, length); | |
11533 break; | |
11534 case new_session_ticket: | |
11535 if (ss->sec.isServer) { | |
11536 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11537 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); | |
11538 return SECFailure; | |
11539 } | |
11540 rv = ssl3_HandleNewSessionTicket(ss, b, length); | |
11541 break; | |
11542 case finished: | |
11543 rv = ssl3_HandleFinished(ss, b, length, &hashes); | |
11544 break; | |
11545 default: | |
11546 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11547 PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE); | |
11548 rv = SECFailure; | |
11549 } | |
11550 | |
11551 if (IS_DTLS(ss) && (rv != SECFailure)) { | |
11552 /* Increment the expected sequence number */ | |
11553 ss->ssl3.hs.recvMessageSeq++; | |
11554 } | |
11555 | |
11556 return rv; | |
11557 } | |
11558 | |
11559 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record. | |
11560 * origBuf is the decrypted ssl record content. | |
11561 * Caller must hold the handshake and RecvBuf locks. | |
11562 */ | |
11563 static SECStatus | |
11564 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) | |
11565 { | |
11566 /* | |
11567 * There may be a partial handshake message already in the handshake | |
11568 * state. The incoming buffer may contain another portion, or a | |
11569 * complete message or several messages followed by another portion. | |
11570 * | |
11571 * Each message is made contiguous before being passed to the actual | |
11572 * message parser. | |
11573 */ | |
11574 sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer p
ointer */ | |
11575 SECStatus rv; | |
11576 | |
11577 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
11578 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
11579 | |
11580 if (buf->buf == NULL) { | |
11581 *buf = *origBuf; | |
11582 } | |
11583 while (buf->len > 0) { | |
11584 if (ss->ssl3.hs.header_bytes < 4) { | |
11585 PRUint8 t; | |
11586 t = *(buf->buf++); | |
11587 buf->len--; | |
11588 if (ss->ssl3.hs.header_bytes++ == 0) | |
11589 ss->ssl3.hs.msg_type = (SSL3HandshakeType)t; | |
11590 else | |
11591 ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t; | |
11592 if (ss->ssl3.hs.header_bytes < 4) | |
11593 continue; | |
11594 | |
11595 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */ | |
11596 if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) { | |
11597 (void)ssl3_DecodeError(ss); | |
11598 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); | |
11599 return SECFailure; | |
11600 } | |
11601 #undef MAX_HANDSHAKE_MSG_LEN | |
11602 | |
11603 /* If msg_len is zero, be sure we fall through, | |
11604 ** even if buf->len is zero. | |
11605 */ | |
11606 if (ss->ssl3.hs.msg_len > 0) | |
11607 continue; | |
11608 } | |
11609 | |
11610 /* | |
11611 * Header has been gathered and there is at least one byte of new | |
11612 * data available for this message. If it can be done right out | |
11613 * of the original buffer, then use it from there. | |
11614 */ | |
11615 if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) { | |
11616 /* handle it from input buffer */ | |
11617 rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len); | |
11618 if (rv == SECFailure) { | |
11619 /* This test wants to fall through on either | |
11620 * SECSuccess or SECWouldBlock. | |
11621 * ssl3_HandleHandshakeMessage MUST set the error code. | |
11622 */ | |
11623 return rv; | |
11624 } | |
11625 buf->buf += ss->ssl3.hs.msg_len; | |
11626 buf->len -= ss->ssl3.hs.msg_len; | |
11627 ss->ssl3.hs.msg_len = 0; | |
11628 ss->ssl3.hs.header_bytes = 0; | |
11629 if (rv != SECSuccess) { /* return if SECWouldBlock. */ | |
11630 return rv; | |
11631 } | |
11632 } else { | |
11633 /* must be copied to msg_body and dealt with from there */ | |
11634 unsigned int bytes; | |
11635 | |
11636 PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len); | |
11637 bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.
len); | |
11638 | |
11639 /* Grow the buffer if needed */ | |
11640 rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len); | |
11641 if (rv != SECSuccess) { | |
11642 /* sslBuffer_Grow has set a memory error code. */ | |
11643 return SECFailure; | |
11644 } | |
11645 | |
11646 PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len, | |
11647 buf->buf, bytes); | |
11648 ss->ssl3.hs.msg_body.len += bytes; | |
11649 buf->buf += bytes; | |
11650 buf->len -= bytes; | |
11651 | |
11652 PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len); | |
11653 | |
11654 /* if we have a whole message, do it */ | |
11655 if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) { | |
11656 rv = ssl3_HandleHandshakeMessage( | |
11657 ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len); | |
11658 if (rv == SECFailure) { | |
11659 /* This test wants to fall through on either | |
11660 * SECSuccess or SECWouldBlock. | |
11661 * ssl3_HandleHandshakeMessage MUST set error code. | |
11662 */ | |
11663 return rv; | |
11664 } | |
11665 ss->ssl3.hs.msg_body.len = 0; | |
11666 ss->ssl3.hs.msg_len = 0; | |
11667 ss->ssl3.hs.header_bytes = 0; | |
11668 if (rv != SECSuccess) { /* return if SECWouldBlock. */ | |
11669 return rv; | |
11670 } | |
11671 } else { | |
11672 PORT_Assert(buf->len == 0); | |
11673 break; | |
11674 } | |
11675 } | |
11676 } /* end loop */ | |
11677 | |
11678 origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */ | |
11679 buf->buf = NULL; /* not a leak. */ | |
11680 return SECSuccess; | |
11681 } | |
11682 | |
11683 /* These macros return the given value with the MSB copied to all the other | |
11684 * bits. They use the fact that arithmetic shift shifts-in the sign bit. | |
11685 * However, this is not ensured by the C standard so you may need to replace | |
11686 * them with something else for odd compilers. */ | |
11687 #define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) ) | |
11688 #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x))) | |
11689 | |
11690 /* SECStatusToMask returns, in constant time, a mask value of all ones if | |
11691 * rv == SECSuccess. Otherwise it returns zero. */ | |
11692 static unsigned int | |
11693 SECStatusToMask(SECStatus rv) | |
11694 { | |
11695 unsigned int good; | |
11696 /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results | |
11697 * in the MSB being set to one iff it was zero before. */ | |
11698 good = rv ^ SECSuccess; | |
11699 good--; | |
11700 return DUPLICATE_MSB_TO_ALL(good); | |
11701 } | |
11702 | |
11703 /* ssl_ConstantTimeGE returns 0xff if a>=b and 0x00 otherwise. */ | |
11704 static unsigned char | |
11705 ssl_ConstantTimeGE(unsigned int a, unsigned int b) | |
11706 { | |
11707 a -= b; | |
11708 return DUPLICATE_MSB_TO_ALL(~a); | |
11709 } | |
11710 | |
11711 /* ssl_ConstantTimeEQ8 returns 0xff if a==b and 0x00 otherwise. */ | |
11712 static unsigned char | |
11713 ssl_ConstantTimeEQ8(unsigned char a, unsigned char b) | |
11714 { | |
11715 unsigned int c = a ^ b; | |
11716 c--; | |
11717 return DUPLICATE_MSB_TO_ALL_8(c); | |
11718 } | |
11719 | |
11720 static SECStatus | |
11721 ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext, | |
11722 unsigned int blockSize, | |
11723 unsigned int macSize) | |
11724 { | |
11725 unsigned int paddingLength, good, t; | |
11726 const unsigned int overhead = 1 /* padding length byte */ + macSize; | |
11727 | |
11728 /* These lengths are all public so we can test them in non-constant | |
11729 * time. */ | |
11730 if (overhead > plaintext->len) { | |
11731 return SECFailure; | |
11732 } | |
11733 | |
11734 paddingLength = plaintext->buf[plaintext->len-1]; | |
11735 /* SSLv3 padding bytes are random and cannot be checked. */ | |
11736 t = plaintext->len; | |
11737 t -= paddingLength+overhead; | |
11738 /* If len >= paddingLength+overhead then the MSB of t is zero. */ | |
11739 good = DUPLICATE_MSB_TO_ALL(~t); | |
11740 /* SSLv3 requires that the padding is minimal. */ | |
11741 t = blockSize - (paddingLength+1); | |
11742 good &= DUPLICATE_MSB_TO_ALL(~t); | |
11743 plaintext->len -= good & (paddingLength+1); | |
11744 return (good & SECSuccess) | (~good & SECFailure); | |
11745 } | |
11746 | |
11747 static SECStatus | |
11748 ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) | |
11749 { | |
11750 unsigned int paddingLength, good, t, toCheck, i; | |
11751 const unsigned int overhead = 1 /* padding length byte */ + macSize; | |
11752 | |
11753 /* These lengths are all public so we can test them in non-constant | |
11754 * time. */ | |
11755 if (overhead > plaintext->len) { | |
11756 return SECFailure; | |
11757 } | |
11758 | |
11759 paddingLength = plaintext->buf[plaintext->len-1]; | |
11760 t = plaintext->len; | |
11761 t -= paddingLength+overhead; | |
11762 /* If len >= paddingLength+overhead then the MSB of t is zero. */ | |
11763 good = DUPLICATE_MSB_TO_ALL(~t); | |
11764 | |
11765 /* The padding consists of a length byte at the end of the record and then | |
11766 * that many bytes of padding, all with the same value as the length byte. | |
11767 * Thus, with the length byte included, there are paddingLength+1 bytes of | |
11768 * padding. | |
11769 * | |
11770 * We can't check just |paddingLength+1| bytes because that leaks | |
11771 * decrypted information. Therefore we always have to check the maximum | |
11772 * amount of padding possible. (Again, the length of the record is | |
11773 * public information so we can use it.) */ | |
11774 toCheck = 255; /* maximum amount of padding. */ | |
11775 if (toCheck > plaintext->len-1) { | |
11776 toCheck = plaintext->len-1; | |
11777 } | |
11778 | |
11779 for (i = 0; i < toCheck; i++) { | |
11780 unsigned int t = paddingLength - i; | |
11781 /* If i <= paddingLength then the MSB of t is zero and mask is | |
11782 * 0xff. Otherwise, mask is 0. */ | |
11783 unsigned char mask = DUPLICATE_MSB_TO_ALL(~t); | |
11784 unsigned char b = plaintext->buf[plaintext->len-1-i]; | |
11785 /* The final |paddingLength+1| bytes should all have the value | |
11786 * |paddingLength|. Therefore the XOR should be zero. */ | |
11787 good &= ~(mask&(paddingLength ^ b)); | |
11788 } | |
11789 | |
11790 /* If any of the final |paddingLength+1| bytes had the wrong value, | |
11791 * one or more of the lower eight bits of |good| will be cleared. We | |
11792 * AND the bottom 8 bits together and duplicate the result to all the | |
11793 * bits. */ | |
11794 good &= good >> 4; | |
11795 good &= good >> 2; | |
11796 good &= good >> 1; | |
11797 good <<= sizeof(good)*8-1; | |
11798 good = DUPLICATE_MSB_TO_ALL(good); | |
11799 | |
11800 plaintext->len -= good & (paddingLength+1); | |
11801 return (good & SECSuccess) | (~good & SECFailure); | |
11802 } | |
11803 | |
11804 /* On entry: | |
11805 * originalLength >= macSize | |
11806 * macSize <= MAX_MAC_LENGTH | |
11807 * plaintext->len >= macSize | |
11808 */ | |
11809 static void | |
11810 ssl_CBCExtractMAC(sslBuffer *plaintext, | |
11811 unsigned int originalLength, | |
11812 SSL3Opaque* out, | |
11813 unsigned int macSize) | |
11814 { | |
11815 unsigned char rotatedMac[MAX_MAC_LENGTH]; | |
11816 /* macEnd is the index of |plaintext->buf| just after the end of the | |
11817 * MAC. */ | |
11818 unsigned macEnd = plaintext->len; | |
11819 unsigned macStart = macEnd - macSize; | |
11820 /* scanStart contains the number of bytes that we can ignore because | |
11821 * the MAC's position can only vary by 255 bytes. */ | |
11822 unsigned scanStart = 0; | |
11823 unsigned i, j, divSpoiler; | |
11824 unsigned char rotateOffset; | |
11825 | |
11826 if (originalLength > macSize + 255 + 1) | |
11827 scanStart = originalLength - (macSize + 255 + 1); | |
11828 | |
11829 /* divSpoiler contains a multiple of macSize that is used to cause the | |
11830 * modulo operation to be constant time. Without this, the time varies | |
11831 * based on the amount of padding when running on Intel chips at least. | |
11832 * | |
11833 * The aim of right-shifting macSize is so that the compiler doesn't | |
11834 * figure out that it can remove divSpoiler as that would require it | |
11835 * to prove that macSize is always even, which I hope is beyond it. */ | |
11836 divSpoiler = macSize >> 1; | |
11837 divSpoiler <<= (sizeof(divSpoiler)-1)*8; | |
11838 rotateOffset = (divSpoiler + macStart - scanStart) % macSize; | |
11839 | |
11840 memset(rotatedMac, 0, macSize); | |
11841 for (i = scanStart; i < originalLength;) { | |
11842 for (j = 0; j < macSize && i < originalLength; i++, j++) { | |
11843 unsigned char macStarted = ssl_ConstantTimeGE(i, macStart); | |
11844 unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd); | |
11845 unsigned char b = 0; | |
11846 b = plaintext->buf[i]; | |
11847 rotatedMac[j] |= b & macStarted & ~macEnded; | |
11848 } | |
11849 } | |
11850 | |
11851 /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line | |
11852 * we could line-align |rotatedMac| and rotate in place. */ | |
11853 memset(out, 0, macSize); | |
11854 for (i = 0; i < macSize; i++) { | |
11855 unsigned char offset = | |
11856 (divSpoiler + macSize - rotateOffset + i) % macSize; | |
11857 for (j = 0; j < macSize; j++) { | |
11858 out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset); | |
11859 } | |
11860 } | |
11861 } | |
11862 | |
11863 /* if cText is non-null, then decipher, check MAC, and decompress the | |
11864 * SSL record from cText->buf (typically gs->inbuf) | |
11865 * into databuf (typically gs->buf), and any previous contents of databuf | |
11866 * is lost. Then handle databuf according to its SSL record type, | |
11867 * unless it's an application record. | |
11868 * | |
11869 * If cText is NULL, then the ciphertext has previously been deciphered and | |
11870 * checked, and is already sitting in databuf. It is processed as an SSL | |
11871 * Handshake message. | |
11872 * | |
11873 * DOES NOT process the decrypted/decompressed application data. | |
11874 * On return, databuf contains the decrypted/decompressed record. | |
11875 * | |
11876 * Called from ssl3_GatherCompleteHandshake | |
11877 * ssl3_RestartHandshakeAfterCertReq | |
11878 * | |
11879 * Caller must hold the RecvBufLock. | |
11880 * | |
11881 * This function aquires and releases the SSL3Handshake Lock, holding the | |
11882 * lock around any calls to functions that handle records other than | |
11883 * Application Data records. | |
11884 */ | |
11885 SECStatus | |
11886 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) | |
11887 { | |
11888 const ssl3BulkCipherDef *cipher_def; | |
11889 ssl3CipherSpec * crSpec; | |
11890 SECStatus rv; | |
11891 unsigned int hashBytes = MAX_MAC_LENGTH + 1; | |
11892 PRBool isTLS; | |
11893 SSL3ContentType rType; | |
11894 SSL3Opaque hash[MAX_MAC_LENGTH]; | |
11895 SSL3Opaque givenHashBuf[MAX_MAC_LENGTH]; | |
11896 SSL3Opaque *givenHash; | |
11897 sslBuffer *plaintext; | |
11898 sslBuffer temp_buf; | |
11899 PRUint64 dtls_seq_num; | |
11900 unsigned int ivLen = 0; | |
11901 unsigned int originalLen = 0; | |
11902 unsigned int good; | |
11903 unsigned int minLength; | |
11904 unsigned char header[13]; | |
11905 unsigned int headerLen; | |
11906 | |
11907 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); | |
11908 | |
11909 if (!ss->ssl3.initialized) { | |
11910 ssl_GetSSL3HandshakeLock(ss); | |
11911 rv = ssl3_InitState(ss); | |
11912 ssl_ReleaseSSL3HandshakeLock(ss); | |
11913 if (rv != SECSuccess) { | |
11914 return rv; /* ssl3_InitState has set the error code. */ | |
11915 } | |
11916 } | |
11917 | |
11918 /* check for Token Presence */ | |
11919 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { | |
11920 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); | |
11921 return SECFailure; | |
11922 } | |
11923 | |
11924 /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX(). | |
11925 * This implies that databuf holds a previously deciphered SSL Handshake | |
11926 * message. | |
11927 */ | |
11928 if (cText == NULL) { | |
11929 SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake", | |
11930 SSL_GETPID(), ss->fd)); | |
11931 rType = content_handshake; | |
11932 goto process_it; | |
11933 } | |
11934 | |
11935 ssl_GetSpecReadLock(ss); /******************************************/ | |
11936 | |
11937 crSpec = ss->ssl3.crSpec; | |
11938 cipher_def = crSpec->cipher_def; | |
11939 | |
11940 /* | |
11941 * DTLS relevance checks: | |
11942 * Note that this code currently ignores all out-of-epoch packets, | |
11943 * which means we lose some in the case of rehandshake + | |
11944 * loss/reordering. Since DTLS is explicitly unreliable, this | |
11945 * seems like a good tradeoff for implementation effort and is | |
11946 * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1 | |
11947 */ | |
11948 if (IS_DTLS(ss)) { | |
11949 DTLSEpoch epoch = (cText->seq_num.high >> 16) & 0xffff; | |
11950 | |
11951 if (crSpec->epoch != epoch) { | |
11952 ssl_ReleaseSpecReadLock(ss); | |
11953 SSL_DBG(("%d: SSL3[%d]: HandleRecord, received packet " | |
11954 "from irrelevant epoch %d", SSL_GETPID(), ss->fd, epoch)); | |
11955 /* Silently drop the packet */ | |
11956 databuf->len = 0; /* Needed to ensure data not left around */ | |
11957 return SECSuccess; | |
11958 } | |
11959 | |
11960 dtls_seq_num = (((PRUint64)(cText->seq_num.high & 0xffff)) << 32) | | |
11961 ((PRUint64)cText->seq_num.low); | |
11962 | |
11963 if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) { | |
11964 ssl_ReleaseSpecReadLock(ss); | |
11965 SSL_DBG(("%d: SSL3[%d]: HandleRecord, rejecting " | |
11966 "potentially replayed packet", SSL_GETPID(), ss->fd)); | |
11967 /* Silently drop the packet */ | |
11968 databuf->len = 0; /* Needed to ensure data not left around */ | |
11969 return SECSuccess; | |
11970 } | |
11971 } | |
11972 | |
11973 good = ~0U; | |
11974 minLength = crSpec->mac_size; | |
11975 if (cipher_def->type == type_block) { | |
11976 /* CBC records have a padding length byte at the end. */ | |
11977 minLength++; | |
11978 if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { | |
11979 /* With >= TLS 1.1, CBC records have an explicit IV. */ | |
11980 minLength += cipher_def->iv_size; | |
11981 } | |
11982 } else if (cipher_def->type == type_aead) { | |
11983 minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size; | |
11984 } | |
11985 | |
11986 /* We can perform this test in variable time because the record's total | |
11987 * length and the ciphersuite are both public knowledge. */ | |
11988 if (cText->buf->len < minLength) { | |
11989 goto decrypt_loser; | |
11990 } | |
11991 | |
11992 if (cipher_def->type == type_block && | |
11993 crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { | |
11994 /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states | |
11995 * "The receiver decrypts the entire GenericBlockCipher structure and | |
11996 * then discards the first cipher block corresponding to the IV | |
11997 * component." Instead, we decrypt the first cipher block and then | |
11998 * discard it before decrypting the rest. | |
11999 */ | |
12000 SSL3Opaque iv[MAX_IV_LENGTH]; | |
12001 int decoded; | |
12002 | |
12003 ivLen = cipher_def->iv_size; | |
12004 if (ivLen < 8 || ivLen > sizeof(iv)) { | |
12005 ssl_ReleaseSpecReadLock(ss); | |
12006 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
12007 return SECFailure; | |
12008 } | |
12009 | |
12010 PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen)); | |
12011 | |
12012 /* The decryption result is garbage, but since we just throw away | |
12013 * the block it doesn't matter. The decryption of the next block | |
12014 * depends only on the ciphertext of the IV block. | |
12015 */ | |
12016 rv = crSpec->decode(crSpec->decodeContext, iv, &decoded, | |
12017 sizeof(iv), cText->buf->buf, ivLen); | |
12018 | |
12019 good &= SECStatusToMask(rv); | |
12020 } | |
12021 | |
12022 /* If we will be decompressing the buffer we need to decrypt somewhere | |
12023 * other than into databuf */ | |
12024 if (crSpec->decompressor) { | |
12025 temp_buf.buf = NULL; | |
12026 temp_buf.space = 0; | |
12027 plaintext = &temp_buf; | |
12028 } else { | |
12029 plaintext = databuf; | |
12030 } | |
12031 | |
12032 plaintext->len = 0; /* filled in by decode call below. */ | |
12033 if (plaintext->space < MAX_FRAGMENT_LENGTH) { | |
12034 rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048); | |
12035 if (rv != SECSuccess) { | |
12036 ssl_ReleaseSpecReadLock(ss); | |
12037 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", | |
12038 SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048)); | |
12039 /* sslBuffer_Grow has set a memory error code. */ | |
12040 /* Perhaps we should send an alert. (but we have no memory!) */ | |
12041 return SECFailure; | |
12042 } | |
12043 } | |
12044 | |
12045 PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen, | |
12046 cText->buf->len - ivLen)); | |
12047 | |
12048 isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0); | |
12049 | |
12050 if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) { | |
12051 ssl_ReleaseSpecReadLock(ss); | |
12052 SSL3_SendAlert(ss, alert_fatal, record_overflow); | |
12053 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); | |
12054 return SECFailure; | |
12055 } | |
12056 | |
12057 rType = cText->type; | |
12058 if (cipher_def->type == type_aead) { | |
12059 /* XXX For many AEAD ciphers, the plaintext is shorter than the | |
12060 * ciphertext by a fixed byte count, but it is not true in general. | |
12061 * Each AEAD cipher should provide a function that returns the | |
12062 * plaintext length for a given ciphertext. */ | |
12063 unsigned int decryptedLen = | |
12064 cText->buf->len - cipher_def->explicit_nonce_size - | |
12065 cipher_def->tag_size; | |
12066 headerLen = ssl3_BuildRecordPseudoHeader( | |
12067 header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, | |
12068 rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen); | |
12069 PORT_Assert(headerLen <= sizeof(header)); | |
12070 rv = crSpec->aead( | |
12071 ss->sec.isServer ? &crSpec->client : &crSpec->server, | |
12072 PR_TRUE, /* do decrypt */ | |
12073 plaintext->buf, /* out */ | |
12074 (int*) &plaintext->len, /* outlen */ | |
12075 plaintext->space, /* maxout */ | |
12076 cText->buf->buf, /* in */ | |
12077 cText->buf->len, /* inlen */ | |
12078 header, headerLen); | |
12079 if (rv != SECSuccess) { | |
12080 good = 0; | |
12081 } | |
12082 } else { | |
12083 if (cipher_def->type == type_block && | |
12084 ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) { | |
12085 goto decrypt_loser; | |
12086 } | |
12087 | |
12088 /* decrypt from cText buf to plaintext. */ | |
12089 rv = crSpec->decode( | |
12090 crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len, | |
12091 plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen); | |
12092 if (rv != SECSuccess) { | |
12093 goto decrypt_loser; | |
12094 } | |
12095 | |
12096 PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len)); | |
12097 | |
12098 originalLen = plaintext->len; | |
12099 | |
12100 /* If it's a block cipher, check and strip the padding. */ | |
12101 if (cipher_def->type == type_block) { | |
12102 const unsigned int blockSize = cipher_def->block_size; | |
12103 const unsigned int macSize = crSpec->mac_size; | |
12104 | |
12105 if (!isTLS) { | |
12106 good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( | |
12107 plaintext, blockSize, macSize)); | |
12108 } else { | |
12109 good &= SECStatusToMask(ssl_RemoveTLSCBCPadding( | |
12110 plaintext, macSize)); | |
12111 } | |
12112 } | |
12113 | |
12114 /* compute the MAC */ | |
12115 headerLen = ssl3_BuildRecordPseudoHeader( | |
12116 header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, | |
12117 rType, isTLS, cText->version, IS_DTLS(ss), | |
12118 plaintext->len - crSpec->mac_size); | |
12119 PORT_Assert(headerLen <= sizeof(header)); | |
12120 if (cipher_def->type == type_block) { | |
12121 rv = ssl3_ComputeRecordMACConstantTime( | |
12122 crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, | |
12123 plaintext->buf, plaintext->len, originalLen, | |
12124 hash, &hashBytes); | |
12125 | |
12126 ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf, | |
12127 crSpec->mac_size); | |
12128 givenHash = givenHashBuf; | |
12129 | |
12130 /* plaintext->len will always have enough space to remove the MAC | |
12131 * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust | |
12132 * plaintext->len if the result has enough space for the MAC and we | |
12133 * tested the unadjusted size against minLength, above. */ | |
12134 plaintext->len -= crSpec->mac_size; | |
12135 } else { | |
12136 /* This is safe because we checked the minLength above. */ | |
12137 plaintext->len -= crSpec->mac_size; | |
12138 | |
12139 rv = ssl3_ComputeRecordMAC( | |
12140 crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, | |
12141 plaintext->buf, plaintext->len, hash, &hashBytes); | |
12142 | |
12143 /* We can read the MAC directly from the record because its location | |
12144 * is public when a stream cipher is used. */ | |
12145 givenHash = plaintext->buf + plaintext->len; | |
12146 } | |
12147 | |
12148 good &= SECStatusToMask(rv); | |
12149 | |
12150 if (hashBytes != (unsigned)crSpec->mac_size || | |
12151 NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) { | |
12152 /* We're allowed to leak whether or not the MAC check was correct */ | |
12153 good = 0; | |
12154 } | |
12155 } | |
12156 | |
12157 if (good == 0) { | |
12158 decrypt_loser: | |
12159 /* must not hold spec lock when calling SSL3_SendAlert. */ | |
12160 ssl_ReleaseSpecReadLock(ss); | |
12161 | |
12162 SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd)); | |
12163 | |
12164 if (!IS_DTLS(ss)) { | |
12165 SSL3_SendAlert(ss, alert_fatal, bad_record_mac); | |
12166 /* always log mac error, in case attacker can read server logs. */ | |
12167 PORT_SetError(SSL_ERROR_BAD_MAC_READ); | |
12168 return SECFailure; | |
12169 } else { | |
12170 /* Silently drop the packet */ | |
12171 databuf->len = 0; /* Needed to ensure data not left around */ | |
12172 return SECSuccess; | |
12173 } | |
12174 } | |
12175 | |
12176 if (!IS_DTLS(ss)) { | |
12177 ssl3_BumpSequenceNumber(&crSpec->read_seq_num); | |
12178 } else { | |
12179 dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num); | |
12180 } | |
12181 | |
12182 ssl_ReleaseSpecReadLock(ss); /*****************************************/ | |
12183 | |
12184 /* | |
12185 * The decrypted data is now in plaintext. | |
12186 */ | |
12187 | |
12188 /* possibly decompress the record. If we aren't using compression then | |
12189 * plaintext == databuf and so the uncompressed data is already in | |
12190 * databuf. */ | |
12191 if (crSpec->decompressor) { | |
12192 if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) { | |
12193 rv = sslBuffer_Grow( | |
12194 databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION); | |
12195 if (rv != SECSuccess) { | |
12196 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", | |
12197 SSL_GETPID(), ss->fd, | |
12198 plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION)); | |
12199 /* sslBuffer_Grow has set a memory error code. */ | |
12200 /* Perhaps we should send an alert. (but we have no memory!) */ | |
12201 PORT_Free(plaintext->buf); | |
12202 return SECFailure; | |
12203 } | |
12204 } | |
12205 | |
12206 rv = crSpec->decompressor(crSpec->decompressContext, | |
12207 databuf->buf, | |
12208 (int*) &databuf->len, | |
12209 databuf->space, | |
12210 plaintext->buf, | |
12211 plaintext->len); | |
12212 | |
12213 if (rv != SECSuccess) { | |
12214 int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE); | |
12215 SSL3_SendAlert(ss, alert_fatal, | |
12216 isTLS ? decompression_failure : bad_record_mac); | |
12217 | |
12218 /* There appears to be a bug with (at least) Apache + OpenSSL where | |
12219 * resumed SSLv3 connections don't actually use compression. See | |
12220 * comments 93-95 of | |
12221 * https://bugzilla.mozilla.org/show_bug.cgi?id=275744 | |
12222 * | |
12223 * So, if we get a decompression error, and the record appears to | |
12224 * be already uncompressed, then we return a more specific error | |
12225 * code to hopefully save somebody some debugging time in the | |
12226 * future. | |
12227 */ | |
12228 if (plaintext->len >= 4) { | |
12229 unsigned int len = ((unsigned int) plaintext->buf[1] << 16) | | |
12230 ((unsigned int) plaintext->buf[2] << 8) | | |
12231 (unsigned int) plaintext->buf[3]; | |
12232 if (len == plaintext->len - 4) { | |
12233 /* This appears to be uncompressed already */ | |
12234 err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD; | |
12235 } | |
12236 } | |
12237 | |
12238 PORT_Free(plaintext->buf); | |
12239 PORT_SetError(err); | |
12240 return SECFailure; | |
12241 } | |
12242 | |
12243 PORT_Free(plaintext->buf); | |
12244 } | |
12245 | |
12246 /* | |
12247 ** Having completed the decompression, check the length again. | |
12248 */ | |
12249 if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) { | |
12250 SSL3_SendAlert(ss, alert_fatal, record_overflow); | |
12251 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); | |
12252 return SECFailure; | |
12253 } | |
12254 | |
12255 /* Application data records are processed by the caller of this | |
12256 ** function, not by this function. | |
12257 */ | |
12258 if (rType == content_application_data) { | |
12259 if (ss->firstHsDone) | |
12260 return SECSuccess; | |
12261 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
12262 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA); | |
12263 return SECFailure; | |
12264 } | |
12265 | |
12266 /* It's a record that must be handled by ssl itself, not the application. | |
12267 */ | |
12268 process_it: | |
12269 /* XXX Get the xmit lock here. Odds are very high that we'll be xmiting | |
12270 * data ang getting the xmit lock here prevents deadlocks. | |
12271 */ | |
12272 ssl_GetSSL3HandshakeLock(ss); | |
12273 | |
12274 /* All the functions called in this switch MUST set error code if | |
12275 ** they return SECFailure or SECWouldBlock. | |
12276 */ | |
12277 switch (rType) { | |
12278 case content_change_cipher_spec: | |
12279 rv = ssl3_HandleChangeCipherSpecs(ss, databuf); | |
12280 break; | |
12281 case content_alert: | |
12282 rv = ssl3_HandleAlert(ss, databuf); | |
12283 break; | |
12284 case content_handshake: | |
12285 if (!IS_DTLS(ss)) { | |
12286 rv = ssl3_HandleHandshake(ss, databuf); | |
12287 } else { | |
12288 rv = dtls_HandleHandshake(ss, databuf); | |
12289 } | |
12290 break; | |
12291 /* | |
12292 case content_application_data is handled before this switch | |
12293 */ | |
12294 default: | |
12295 SSL_DBG(("%d: SSL3[%d]: bogus content type=%d", | |
12296 SSL_GETPID(), ss->fd, cText->type)); | |
12297 /* XXX Send an alert ??? */ | |
12298 PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE); | |
12299 rv = SECFailure; | |
12300 break; | |
12301 } | |
12302 | |
12303 ssl_ReleaseSSL3HandshakeLock(ss); | |
12304 return rv; | |
12305 } | |
12306 | |
12307 /* | |
12308 * Initialization functions | |
12309 */ | |
12310 | |
12311 /* Called from ssl3_InitState, immediately below. */ | |
12312 /* Caller must hold the SpecWriteLock. */ | |
12313 static void | |
12314 ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec) | |
12315 { | |
12316 spec->cipher_def = &bulk_cipher_defs[cipher_null]; | |
12317 PORT_Assert(spec->cipher_def->cipher == cipher_null); | |
12318 spec->mac_def = &mac_defs[mac_null]; | |
12319 PORT_Assert(spec->mac_def->mac == mac_null); | |
12320 spec->encode = Null_Cipher; | |
12321 spec->decode = Null_Cipher; | |
12322 spec->destroy = NULL; | |
12323 spec->compressor = NULL; | |
12324 spec->decompressor = NULL; | |
12325 spec->destroyCompressContext = NULL; | |
12326 spec->destroyDecompressContext = NULL; | |
12327 spec->mac_size = 0; | |
12328 spec->master_secret = NULL; | |
12329 spec->bypassCiphers = PR_FALSE; | |
12330 | |
12331 spec->msItem.data = NULL; | |
12332 spec->msItem.len = 0; | |
12333 | |
12334 spec->client.write_key = NULL; | |
12335 spec->client.write_mac_key = NULL; | |
12336 spec->client.write_mac_context = NULL; | |
12337 | |
12338 spec->server.write_key = NULL; | |
12339 spec->server.write_mac_key = NULL; | |
12340 spec->server.write_mac_context = NULL; | |
12341 | |
12342 spec->write_seq_num.high = 0; | |
12343 spec->write_seq_num.low = 0; | |
12344 | |
12345 spec->read_seq_num.high = 0; | |
12346 spec->read_seq_num.low = 0; | |
12347 | |
12348 spec->epoch = 0; | |
12349 dtls_InitRecvdRecords(&spec->recvdRecords); | |
12350 | |
12351 spec->version = ss->vrange.max; | |
12352 } | |
12353 | |
12354 /* Called from: ssl3_SendRecord | |
12355 ** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake() | |
12356 ** ssl3_SendClientHello() | |
12357 ** ssl3_HandleV2ClientHello() | |
12358 ** ssl3_HandleRecord() | |
12359 ** | |
12360 ** This function should perhaps acquire and release the SpecWriteLock. | |
12361 ** | |
12362 ** | |
12363 */ | |
12364 static SECStatus | |
12365 ssl3_InitState(sslSocket *ss) | |
12366 { | |
12367 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
12368 | |
12369 if (ss->ssl3.initialized) | |
12370 return SECSuccess; /* Function should be idempotent */ | |
12371 | |
12372 ss->ssl3.policy = SSL_ALLOWED; | |
12373 | |
12374 ssl_GetSpecWriteLock(ss); | |
12375 ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0]; | |
12376 ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1]; | |
12377 ss->ssl3.hs.sendingSCSV = PR_FALSE; | |
12378 ssl3_InitCipherSpec(ss, ss->ssl3.crSpec); | |
12379 ssl3_InitCipherSpec(ss, ss->ssl3.prSpec); | |
12380 | |
12381 ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello; | |
12382 #ifdef NSS_ENABLE_ECC | |
12383 ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss); | |
12384 #endif | |
12385 ssl_ReleaseSpecWriteLock(ss); | |
12386 | |
12387 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); | |
12388 | |
12389 if (IS_DTLS(ss)) { | |
12390 ss->ssl3.hs.sendMessageSeq = 0; | |
12391 ss->ssl3.hs.recvMessageSeq = 0; | |
12392 ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS; | |
12393 ss->ssl3.hs.rtRetries = 0; | |
12394 ss->ssl3.hs.recvdHighWater = -1; | |
12395 PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight); | |
12396 dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */ | |
12397 } | |
12398 | |
12399 PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space); | |
12400 ss->ssl3.hs.messages.buf = NULL; | |
12401 ss->ssl3.hs.messages.space = 0; | |
12402 | |
12403 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; | |
12404 PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0, | |
12405 sizeof(ss->ssl3.hs.newSessionTicket)); | |
12406 | |
12407 ss->ssl3.initialized = PR_TRUE; | |
12408 return SECSuccess; | |
12409 } | |
12410 | |
12411 /* Returns a reference counted object that contains a key pair. | |
12412 * Or NULL on failure. Initial ref count is 1. | |
12413 * Uses the keys in the pair as input. | |
12414 */ | |
12415 ssl3KeyPair * | |
12416 ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey) | |
12417 { | |
12418 ssl3KeyPair * pair; | |
12419 | |
12420 if (!privKey || !pubKey) { | |
12421 PORT_SetError(PR_INVALID_ARGUMENT_ERROR); | |
12422 return NULL; | |
12423 } | |
12424 pair = PORT_ZNew(ssl3KeyPair); | |
12425 if (!pair) | |
12426 return NULL; /* error code is set. */ | |
12427 pair->refCount = 1; | |
12428 pair->privKey = privKey; | |
12429 pair->pubKey = pubKey; | |
12430 return pair; /* success */ | |
12431 } | |
12432 | |
12433 ssl3KeyPair * | |
12434 ssl3_GetKeyPairRef(ssl3KeyPair * keyPair) | |
12435 { | |
12436 PR_ATOMIC_INCREMENT(&keyPair->refCount); | |
12437 return keyPair; | |
12438 } | |
12439 | |
12440 void | |
12441 ssl3_FreeKeyPair(ssl3KeyPair * keyPair) | |
12442 { | |
12443 PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount); | |
12444 if (!newCount) { | |
12445 if (keyPair->privKey) | |
12446 SECKEY_DestroyPrivateKey(keyPair->privKey); | |
12447 if (keyPair->pubKey) | |
12448 SECKEY_DestroyPublicKey( keyPair->pubKey); | |
12449 PORT_Free(keyPair); | |
12450 } | |
12451 } | |
12452 | |
12453 | |
12454 | |
12455 /* | |
12456 * Creates the public and private RSA keys for SSL Step down. | |
12457 * Called from SSL_ConfigSecureServer in sslsecur.c | |
12458 */ | |
12459 SECStatus | |
12460 ssl3_CreateRSAStepDownKeys(sslSocket *ss) | |
12461 { | |
12462 SECStatus rv = SECSuccess; | |
12463 SECKEYPrivateKey * privKey; /* RSA step down key */ | |
12464 SECKEYPublicKey * pubKey; /* RSA step down key */ | |
12465 | |
12466 if (ss->stepDownKeyPair) | |
12467 ssl3_FreeKeyPair(ss->stepDownKeyPair); | |
12468 ss->stepDownKeyPair = NULL; | |
12469 #ifndef HACKED_EXPORT_SERVER | |
12470 /* Sigh, should have a get key strength call for private keys */ | |
12471 if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) > | |
12472 EXPORT_RSA_KEY_LENGTH) { | |
12473 /* need to ask for the key size in bits */ | |
12474 privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB, | |
12475 &pubKey, NULL); | |
12476 if (!privKey || !pubKey || | |
12477 !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) { | |
12478 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); | |
12479 rv = SECFailure; | |
12480 } | |
12481 } | |
12482 #endif | |
12483 return rv; | |
12484 } | |
12485 | |
12486 | |
12487 /* record the export policy for this cipher suite */ | |
12488 SECStatus | |
12489 ssl3_SetPolicy(ssl3CipherSuite which, int policy) | |
12490 { | |
12491 ssl3CipherSuiteCfg *suite; | |
12492 | |
12493 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); | |
12494 if (suite == NULL) { | |
12495 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ | |
12496 } | |
12497 suite->policy = policy; | |
12498 | |
12499 return SECSuccess; | |
12500 } | |
12501 | |
12502 SECStatus | |
12503 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy) | |
12504 { | |
12505 ssl3CipherSuiteCfg *suite; | |
12506 PRInt32 policy; | |
12507 SECStatus rv; | |
12508 | |
12509 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); | |
12510 if (suite) { | |
12511 policy = suite->policy; | |
12512 rv = SECSuccess; | |
12513 } else { | |
12514 policy = SSL_NOT_ALLOWED; | |
12515 rv = SECFailure; /* err code was set by Lookup. */ | |
12516 } | |
12517 *oPolicy = policy; | |
12518 return rv; | |
12519 } | |
12520 | |
12521 /* record the user preference for this suite */ | |
12522 SECStatus | |
12523 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled) | |
12524 { | |
12525 ssl3CipherSuiteCfg *suite; | |
12526 | |
12527 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); | |
12528 if (suite == NULL) { | |
12529 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ | |
12530 } | |
12531 suite->enabled = enabled; | |
12532 return SECSuccess; | |
12533 } | |
12534 | |
12535 /* return the user preference for this suite */ | |
12536 SECStatus | |
12537 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled) | |
12538 { | |
12539 ssl3CipherSuiteCfg *suite; | |
12540 PRBool pref; | |
12541 SECStatus rv; | |
12542 | |
12543 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); | |
12544 if (suite) { | |
12545 pref = suite->enabled; | |
12546 rv = SECSuccess; | |
12547 } else { | |
12548 pref = SSL_NOT_ALLOWED; | |
12549 rv = SECFailure; /* err code was set by Lookup. */ | |
12550 } | |
12551 *enabled = pref; | |
12552 return rv; | |
12553 } | |
12554 | |
12555 SECStatus | |
12556 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled) | |
12557 { | |
12558 ssl3CipherSuiteCfg *suite; | |
12559 | |
12560 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); | |
12561 if (suite == NULL) { | |
12562 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ | |
12563 } | |
12564 suite->enabled = enabled; | |
12565 return SECSuccess; | |
12566 } | |
12567 | |
12568 SECStatus | |
12569 ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled) | |
12570 { | |
12571 ssl3CipherSuiteCfg *suite; | |
12572 PRBool pref; | |
12573 SECStatus rv; | |
12574 | |
12575 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); | |
12576 if (suite) { | |
12577 pref = suite->enabled; | |
12578 rv = SECSuccess; | |
12579 } else { | |
12580 pref = SSL_NOT_ALLOWED; | |
12581 rv = SECFailure; /* err code was set by Lookup. */ | |
12582 } | |
12583 *enabled = pref; | |
12584 return rv; | |
12585 } | |
12586 | |
12587 SECStatus | |
12588 ssl3_CipherOrderSet(sslSocket *ss, const ssl3CipherSuite *ciphers, unsigned int
len) | |
12589 { | |
12590 /* |i| iterates over |ciphers| while |done| and |j| iterate over | |
12591 * |ss->cipherSuites|. */ | |
12592 unsigned int i, done; | |
12593 | |
12594 for (i = done = 0; i < len; i++) { | |
12595 PRUint16 id = ciphers[i]; | |
12596 unsigned int existingIndex, j; | |
12597 PRBool found = PR_FALSE; | |
12598 | |
12599 for (j = done; j < ssl_V3_SUITES_IMPLEMENTED; j++) { | |
12600 if (ss->cipherSuites[j].cipher_suite == id) { | |
12601 existingIndex = j; | |
12602 found = PR_TRUE; | |
12603 break; | |
12604 } | |
12605 } | |
12606 | |
12607 if (!found) { | |
12608 continue; | |
12609 } | |
12610 | |
12611 if (existingIndex != done) { | |
12612 const ssl3CipherSuiteCfg temp = ss->cipherSuites[done]; | |
12613 ss->cipherSuites[done] = ss->cipherSuites[existingIndex]; | |
12614 ss->cipherSuites[existingIndex] = temp; | |
12615 } | |
12616 done++; | |
12617 } | |
12618 | |
12619 /* Disable all cipher suites that weren't included. */ | |
12620 for (; done < ssl_V3_SUITES_IMPLEMENTED; done++) { | |
12621 ss->cipherSuites[done].enabled = 0; | |
12622 } | |
12623 | |
12624 return SECSuccess; | |
12625 } | |
12626 | |
12627 /* copy global default policy into socket. */ | |
12628 void | |
12629 ssl3_InitSocketPolicy(sslSocket *ss) | |
12630 { | |
12631 PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites); | |
12632 } | |
12633 | |
12634 SECStatus | |
12635 ssl3_GetTLSUniqueChannelBinding(sslSocket *ss, | |
12636 unsigned char *out, | |
12637 unsigned int *outLen, | |
12638 unsigned int outLenMax) { | |
12639 PRBool isTLS; | |
12640 int index = 0; | |
12641 unsigned int len; | |
12642 SECStatus rv = SECFailure; | |
12643 | |
12644 *outLen = 0; | |
12645 | |
12646 ssl_GetSSL3HandshakeLock(ss); | |
12647 | |
12648 ssl_GetSpecReadLock(ss); | |
12649 isTLS = (PRBool)(ss->ssl3.cwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
12650 ssl_ReleaseSpecReadLock(ss); | |
12651 | |
12652 /* The tls-unique channel binding is the first Finished structure in the | |
12653 * handshake. In the case of a resumption, that's the server's Finished. | |
12654 * Otherwise, it's the client's Finished. */ | |
12655 len = ss->ssl3.hs.finishedBytes; | |
12656 | |
12657 /* Sending or receiving a Finished message will set finishedBytes to a | |
12658 * non-zero value. */ | |
12659 if (len == 0) { | |
12660 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); | |
12661 goto loser; | |
12662 } | |
12663 | |
12664 /* If we are in the middle of a renegotiation then the channel binding | |
12665 * value is poorly defined and depends on the direction that it will be | |
12666 * used on. Therefore we simply return an error in this case. */ | |
12667 if (ss->firstHsDone && ss->ssl3.hs.ws != idle_handshake) { | |
12668 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); | |
12669 goto loser; | |
12670 } | |
12671 | |
12672 /* If resuming, then we want the second Finished value in the array, which | |
12673 * is the server's */ | |
12674 if (ss->ssl3.hs.isResuming) | |
12675 index = 1; | |
12676 | |
12677 *outLen = len; | |
12678 if (outLenMax < len) { | |
12679 PORT_SetError(SEC_ERROR_OUTPUT_LEN); | |
12680 goto loser; | |
12681 } | |
12682 | |
12683 if (isTLS) { | |
12684 memcpy(out, &ss->ssl3.hs.finishedMsgs.tFinished[index], len); | |
12685 } else { | |
12686 memcpy(out, &ss->ssl3.hs.finishedMsgs.sFinished[index], len); | |
12687 } | |
12688 | |
12689 rv = SECSuccess; | |
12690 | |
12691 loser: | |
12692 ssl_ReleaseSSL3HandshakeLock(ss); | |
12693 return rv; | |
12694 } | |
12695 | |
12696 /* ssl3_config_match_init must have already been called by | |
12697 * the caller of this function. | |
12698 */ | |
12699 SECStatus | |
12700 ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size) | |
12701 { | |
12702 int i, count = 0; | |
12703 | |
12704 PORT_Assert(ss != 0); | |
12705 if (!ss) { | |
12706 PORT_SetError(PR_INVALID_ARGUMENT_ERROR); | |
12707 return SECFailure; | |
12708 } | |
12709 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { | |
12710 *size = 0; | |
12711 return SECSuccess; | |
12712 } | |
12713 if (cs == NULL) { | |
12714 *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE); | |
12715 return SECSuccess; | |
12716 } | |
12717 | |
12718 /* ssl3_config_match_init was called by the caller of this function. */ | |
12719 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { | |
12720 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; | |
12721 if (config_match(suite, SSL_ALLOWED, PR_TRUE, &ss->vrange)) { | |
12722 if (cs != NULL) { | |
12723 *cs++ = 0x00; | |
12724 *cs++ = (suite->cipher_suite >> 8) & 0xFF; | |
12725 *cs++ = suite->cipher_suite & 0xFF; | |
12726 } | |
12727 count++; | |
12728 } | |
12729 } | |
12730 *size = count; | |
12731 return SECSuccess; | |
12732 } | |
12733 | |
12734 /* | |
12735 ** If ssl3 socket has completed the first handshake, and is in idle state, | |
12736 ** then start a new handshake. | |
12737 ** If flushCache is true, the SID cache will be flushed first, forcing a | |
12738 ** "Full" handshake (not a session restart handshake), to be done. | |
12739 ** | |
12740 ** called from SSL_RedoHandshake(), which already holds the handshake locks. | |
12741 */ | |
12742 SECStatus | |
12743 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache) | |
12744 { | |
12745 sslSessionID * sid = ss->sec.ci.sid; | |
12746 SECStatus rv; | |
12747 | |
12748 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); | |
12749 | |
12750 if (!ss->firstHsDone || | |
12751 ((ss->version >= SSL_LIBRARY_VERSION_3_0) && | |
12752 ss->ssl3.initialized && | |
12753 (ss->ssl3.hs.ws != idle_handshake))) { | |
12754 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); | |
12755 return SECFailure; | |
12756 } | |
12757 | |
12758 if (IS_DTLS(ss)) { | |
12759 dtls_RehandshakeCleanup(ss); | |
12760 } | |
12761 | |
12762 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { | |
12763 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); | |
12764 return SECFailure; | |
12765 } | |
12766 if (sid && flushCache) { | |
12767 if (ss->sec.uncache) | |
12768 ss->sec.uncache(sid); /* remove it from whichever cache it's in. */ | |
12769 ssl_FreeSID(sid); /* dec ref count and free if zero. */ | |
12770 ss->sec.ci.sid = NULL; | |
12771 } | |
12772 | |
12773 ssl_GetXmitBufLock(ss); /**************************************/ | |
12774 | |
12775 /* start off a new handshake. */ | |
12776 rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss) | |
12777 : ssl3_SendClientHello(ss, PR_FALSE); | |
12778 | |
12779 ssl_ReleaseXmitBufLock(ss); /**************************************/ | |
12780 return rv; | |
12781 } | |
12782 | |
12783 /* Called from ssl_DestroySocketContents() in sslsock.c */ | |
12784 void | |
12785 ssl3_DestroySSL3Info(sslSocket *ss) | |
12786 { | |
12787 | |
12788 if (ss->ssl3.clientCertificate != NULL) | |
12789 CERT_DestroyCertificate(ss->ssl3.clientCertificate); | |
12790 | |
12791 if (ss->ssl3.clientPrivateKey != NULL) | |
12792 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); | |
12793 #ifdef NSS_PLATFORM_CLIENT_AUTH | |
12794 if (ss->ssl3.platformClientKey) | |
12795 ssl_FreePlatformKey(ss->ssl3.platformClientKey); | |
12796 #endif /* NSS_PLATFORM_CLIENT_AUTH */ | |
12797 | |
12798 if (ss->ssl3.channelID) | |
12799 SECKEY_DestroyPrivateKey(ss->ssl3.channelID); | |
12800 if (ss->ssl3.channelIDPub) | |
12801 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub); | |
12802 | |
12803 if (ss->ssl3.peerCertArena != NULL) | |
12804 ssl3_CleanupPeerCerts(ss); | |
12805 | |
12806 if (ss->ssl3.clientCertChain != NULL) { | |
12807 CERT_DestroyCertificateList(ss->ssl3.clientCertChain); | |
12808 ss->ssl3.clientCertChain = NULL; | |
12809 } | |
12810 | |
12811 /* clean up handshake */ | |
12812 #ifndef NO_PKCS11_BYPASS | |
12813 if (ss->opt.bypassPKCS11) { | |
12814 if (ss->ssl3.hs.hashType == handshake_hash_combo) { | |
12815 SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE); | |
12816 MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE); | |
12817 } else if (ss->ssl3.hs.hashType == handshake_hash_single) { | |
12818 ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE); | |
12819 } | |
12820 } | |
12821 #endif | |
12822 if (ss->ssl3.hs.md5) { | |
12823 PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE); | |
12824 } | |
12825 if (ss->ssl3.hs.sha) { | |
12826 PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE); | |
12827 } | |
12828 if (ss->ssl3.hs.clientSigAndHash) { | |
12829 PORT_Free(ss->ssl3.hs.clientSigAndHash); | |
12830 } | |
12831 if (ss->ssl3.hs.messages.buf) { | |
12832 PORT_Free(ss->ssl3.hs.messages.buf); | |
12833 ss->ssl3.hs.messages.buf = NULL; | |
12834 ss->ssl3.hs.messages.len = 0; | |
12835 ss->ssl3.hs.messages.space = 0; | |
12836 } | |
12837 | |
12838 /* free the SSL3Buffer (msg_body) */ | |
12839 PORT_Free(ss->ssl3.hs.msg_body.buf); | |
12840 | |
12841 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); | |
12842 | |
12843 /* free up the CipherSpecs */ | |
12844 ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE/*freeSrvName*/); | |
12845 ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE/*freeSrvName*/); | |
12846 | |
12847 /* Destroy the DTLS data */ | |
12848 if (IS_DTLS(ss)) { | |
12849 dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight); | |
12850 if (ss->ssl3.hs.recvdFragments.buf) { | |
12851 PORT_Free(ss->ssl3.hs.recvdFragments.buf); | |
12852 } | |
12853 } | |
12854 | |
12855 ss->ssl3.initialized = PR_FALSE; | |
12856 | |
12857 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE); | |
12858 } | |
12859 | |
12860 /* End of ssl3con.c */ | |
OLD | NEW |