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 #include "nss.h" | |
28 #include "nssoptions.h" | |
29 | |
30 #include "pk11func.h" | |
31 #include "secmod.h" | |
32 #ifndef NO_PKCS11_BYPASS | |
33 #include "blapi.h" | |
34 #endif | |
35 | |
36 #include <stdio.h> | |
37 #ifdef NSS_SSL_ENABLE_ZLIB | |
38 #include "zlib.h" | |
39 #endif | |
40 | |
41 #ifndef PK11_SETATTRS | |
42 #define PK11_SETATTRS(x, id, v, l) \ | |
43 (x)->type = (id); \ | |
44 (x)->pValue = (v); \ | |
45 (x)->ulValueLen = (l); | |
46 #endif | |
47 | |
48 static SECStatus ssl3_AuthCertificate(sslSocket *ss); | |
49 static void ssl3_CleanupPeerCerts(sslSocket *ss); | |
50 static void ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid); | |
51 static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, | |
52 PK11SlotInfo *serverKeySlot); | |
53 static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms); | |
54 static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss); | |
55 static SECStatus ssl3_HandshakeFailure(sslSocket *ss); | |
56 static SECStatus ssl3_InitState(sslSocket *ss); | |
57 | |
58 static SECStatus ssl3_SendCertificateRequest(sslSocket *ss); | |
59 static SECStatus ssl3_SendNextProto(sslSocket *ss); | |
60 static SECStatus ssl3_SendChannelIDEncryptedExtensions(sslSocket *ss); | |
61 static SECStatus ssl3_SendFinished(sslSocket *ss, PRInt32 flags); | |
62 static SECStatus ssl3_SendServerHelloDone(sslSocket *ss); | |
63 static SECStatus ssl3_SendServerKeyExchange(sslSocket *ss); | |
64 static SECStatus ssl3_UpdateHandshakeHashes(sslSocket *ss, | |
65 const unsigned char *b, | |
66 unsigned int l); | |
67 static SECStatus ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, | |
68 SSL3Opaque *b, | |
69 PRUint32 length, | |
70 SSL3Hashes *hashesPtr); | |
71 static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags); | |
72 | |
73 static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen, | |
74 int maxOutputLen, const unsigned char *input, | |
75 int inputLen); | |
76 #ifndef NO_PKCS11_BYPASS | |
77 static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt, | |
78 unsigned char *out, int *outlen, int maxout, | |
79 const unsigned char *in, int inlen, | |
80 const unsigned char *additionalData, | |
81 int additionalDataLen); | |
82 #endif | |
83 | |
84 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */ | |
85 #define MIN_SEND_BUF_LENGTH 4000 | |
86 | |
87 /* This list of SSL3 cipher suites is sorted in descending order of | |
88 * precedence (desirability). It only includes cipher suites we implement. | |
89 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites | |
90 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c) | |
91 * | |
92 * Important: See bug 946147 before enabling, reordering, or adding any cipher | |
93 * suites to this list. | |
94 */ | |
95 /* clang-format off */ | |
96 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { | |
97 /* cipher_suite policy enabled isPresent */ | |
98 | |
99 #ifndef NSS_DISABLE_ECC | |
100 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
101 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
102 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE
}, | |
103 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE
}, | |
104 /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around | |
105 * bug 946147. | |
106 */ | |
107 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
108 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
109 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
110 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
111 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
112 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
113 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
114 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
115 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
116 { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
117 #endif /* NSS_DISABLE_ECC */ | |
118 | |
119 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
120 { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,SSL_ALLOWED,PR_TRUE, PR_FALSE}, | |
121 { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
122 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
123 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
124 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
125 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
126 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
127 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
128 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
129 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
130 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
131 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
132 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
133 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
134 { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
135 { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
136 { TLS_DHE_DSS_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
137 | |
138 #ifndef NSS_DISABLE_ECC | |
139 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
140 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
141 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
142 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
143 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
144 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
145 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
146 { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
147 #endif /* NSS_DISABLE_ECC */ | |
148 | |
149 /* RSA */ | |
150 { TLS_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
151 { TLS_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
152 { TLS_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
153 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
154 { TLS_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
155 { TLS_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
156 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
157 { TLS_RSA_WITH_SEED_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
158 { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
159 { TLS_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
160 { TLS_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
161 { TLS_RSA_WITH_RC4_128_MD5, SSL_ALLOWED, PR_TRUE, PR_FALSE}, | |
162 | |
163 /* 56-bit DES "domestic" cipher suites */ | |
164 { TLS_DHE_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
165 { TLS_DHE_DSS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
166 { SSL_RSA_FIPS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
167 { TLS_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
168 | |
169 /* export ciphersuites with 1024-bit public key exchange keys */ | |
170 { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
171 { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
172 | |
173 /* export ciphersuites with 512-bit public key exchange keys */ | |
174 { TLS_RSA_EXPORT_WITH_RC4_40_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
175 { TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
176 | |
177 /* ciphersuites with no encryption */ | |
178 #ifndef NSS_DISABLE_ECC | |
179 { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
180 { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
181 { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
182 { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
183 #endif /* NSS_DISABLE_ECC */ | |
184 { TLS_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
185 { TLS_RSA_WITH_NULL_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
186 { TLS_RSA_WITH_NULL_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, | |
187 }; | |
188 /* clang-format on */ | |
189 | |
190 static const SSLSignatureAndHashAlg defaultSignatureAlgorithms[] = { | |
191 { ssl_hash_sha256, ssl_sign_rsa }, | |
192 { ssl_hash_sha384, ssl_sign_rsa }, | |
193 { ssl_hash_sha512, ssl_sign_rsa }, | |
194 { ssl_hash_sha1, ssl_sign_rsa }, | |
195 #ifndef NSS_DISABLE_ECC | |
196 { ssl_hash_sha256, ssl_sign_ecdsa }, | |
197 { ssl_hash_sha384, ssl_sign_ecdsa }, | |
198 { ssl_hash_sha512, ssl_sign_ecdsa }, | |
199 { ssl_hash_sha1, ssl_sign_ecdsa }, | |
200 #endif | |
201 { ssl_hash_sha256, ssl_sign_dsa }, | |
202 { ssl_hash_sha1, ssl_sign_dsa } | |
203 }; | |
204 PR_STATIC_ASSERT(PR_ARRAY_SIZE(defaultSignatureAlgorithms) <= | |
205 MAX_SIGNATURE_ALGORITHMS); | |
206 | |
207 /* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order. | |
208 */ | |
209 #ifdef DEBUG | |
210 void | |
211 ssl3_CheckCipherSuiteOrderConsistency() | |
212 { | |
213 unsigned int i; | |
214 | |
215 /* Note that SSL_ImplementedCiphers has more elements than cipherSuites | |
216 * because it SSL_ImplementedCiphers includes SSL 2.0 cipher suites. | |
217 */ | |
218 PORT_Assert(SSL_NumImplementedCiphers >= PR_ARRAY_SIZE(cipherSuites)); | |
219 | |
220 for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) { | |
221 PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite); | |
222 } | |
223 } | |
224 #endif | |
225 | |
226 /* This list of SSL3 compression methods is sorted in descending order of | |
227 * precedence (desirability). It only includes compression methods we | |
228 * implement. | |
229 */ | |
230 static const /*SSLCompressionMethod*/ PRUint8 compressions[] = { | |
231 #ifdef NSS_SSL_ENABLE_ZLIB | |
232 ssl_compression_deflate, | |
233 #endif | |
234 ssl_compression_null | |
235 }; | |
236 | |
237 static const int compressionMethodsCount = | |
238 sizeof(compressions) / sizeof(compressions[0]); | |
239 | |
240 /* compressionEnabled returns true iff the compression algorithm is enabled | |
241 * for the given SSL socket. */ | |
242 static PRBool | |
243 compressionEnabled(sslSocket *ss, SSLCompressionMethod compression) | |
244 { | |
245 switch (compression) { | |
246 case ssl_compression_null: | |
247 return PR_TRUE; /* Always enabled */ | |
248 #ifdef NSS_SSL_ENABLE_ZLIB | |
249 case ssl_compression_deflate: | |
250 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { | |
251 return ss->opt.enableDeflate; | |
252 } | |
253 return PR_FALSE; | |
254 #endif | |
255 default: | |
256 return PR_FALSE; | |
257 } | |
258 } | |
259 | |
260 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types[] = { | |
261 ct_RSA_sign, | |
262 #ifndef NSS_DISABLE_ECC | |
263 ct_ECDSA_sign, | |
264 #endif /* NSS_DISABLE_ECC */ | |
265 ct_DSS_sign, | |
266 }; | |
267 | |
268 #define EXPORT_RSA_KEY_LENGTH 64 /* bytes */ | |
269 | |
270 /* This global item is used only in servers. It is is initialized by | |
271 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest(). | |
272 */ | |
273 CERTDistNames *ssl3_server_ca_list = NULL; | |
274 static SSL3Statistics ssl3stats; | |
275 | |
276 /* indexed by SSL3BulkCipher */ | |
277 /* clang-format off */ | |
278 static const ssl3BulkCipherDef bulk_cipher_defs[] = { | |
279 /* |--------- Lengths --------| */ | |
280 /* cipher calg k s type i b t n o */ | |
281 /* e e v l a o i */ | |
282 /* y c | o g n d */ | |
283 /* | r | c | c | */ | |
284 /* | e | k | e | */ | |
285 /* | t | | | | | */ | |
286 {cipher_null, calg_null, 0, 0, type_stream, 0, 0, 0, 0, SEC_
OID_NULL_CIPHER}, | |
287 {cipher_rc4, calg_rc4, 16,16, type_stream, 0, 0, 0, 0, SEC_
OID_RC4}, | |
288 {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, 0, 0, SEC_
OID_RC4_40}, | |
289 {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, 0, 0, SEC_
OID_RC4_56}, | |
290 {cipher_rc2, calg_rc2, 16,16, type_block, 8, 8, 0, 0, SEC_
OID_RC2_CBC}, | |
291 {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, 0, 0, SEC_
OID_RC2_40_CBC}, | |
292 {cipher_des, calg_des, 8, 8, type_block, 8, 8, 0, 0, SEC_
OID_DES_CBC}, | |
293 {cipher_3des, calg_3des, 24,24, type_block, 8, 8, 0, 0, SEC_
OID_DES_EDE3_CBC}, | |
294 {cipher_des40, calg_des, 8, 5, type_block, 8, 8, 0, 0, SEC_
OID_DES_40_CBC}, | |
295 {cipher_idea, calg_idea, 16,16, type_block, 8, 8, 0, 0, SEC_
OID_IDEA_CBC}, | |
296 {cipher_aes_128, calg_aes, 16,16, type_block, 16,16, 0, 0, SEC_
OID_AES_128_CBC}, | |
297 {cipher_aes_256, calg_aes, 32,32, type_block, 16,16, 0, 0, SEC_
OID_AES_256_CBC}, | |
298 {cipher_camellia_128, calg_camellia, 16,16, type_block, 16,16, 0, 0, SEC_
OID_CAMELLIA_128_CBC}, | |
299 {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0, SEC_
OID_CAMELLIA_256_CBC}, | |
300 {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0, SEC_
OID_SEED_CBC}, | |
301 {cipher_aes_128_gcm, calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8, SEC_
OID_AES_128_GCM}, | |
302 {cipher_chacha20, calg_chacha20, 32,32, type_aead, 12, 0,16, 0, SEC_
OID_CHACHA20_POLY1305}, | |
303 {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0, 0}, | |
304 }; | |
305 | |
306 static const ssl3KEADef kea_defs[] = | |
307 { /* indexed by SSL3KeyExchangeAlgorithm */ | |
308 /* kea exchKeyType signKeyType is_limited limit tls_keygen epheme
ral oid */ | |
309 {kea_null, kt_null, ssl_sign_null, PR_FALSE, 0, PR_FALSE, PR_FA
LSE, 0}, | |
310 {kea_rsa, kt_rsa, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FA
LSE, SEC_OID_TLS_RSA}, | |
311 {kea_rsa_export, kt_rsa, ssl_sign_rsa, PR_TRUE, 512, PR_FALSE, PR_FA
LSE, SEC_OID_TLS_RSA_EXPORT}, | |
312 {kea_rsa_export_1024,kt_rsa, ssl_sign_rsa, PR_TRUE, 1024, PR_FALSE, PR_FA
LSE, SEC_OID_TLS_RSA_EXPORT}, | |
313 {kea_dh_dss, kt_dh, ssl_sign_dsa, PR_FALSE, 0, PR_FALSE, PR_FA
LSE, SEC_OID_TLS_DH_DSS}, | |
314 {kea_dh_dss_export, kt_dh, ssl_sign_dsa, PR_TRUE, 512, PR_FALSE, PR_FA
LSE, SEC_OID_TLS_DH_DSS_EXPORT}, | |
315 {kea_dh_rsa, kt_dh, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FA
LSE, SEC_OID_TLS_DH_RSA}, | |
316 {kea_dh_rsa_export, kt_dh, ssl_sign_rsa, PR_TRUE, 512, PR_FALSE, PR_FA
LSE, SEC_OID_TLS_DH_RSA_EXPORT}, | |
317 {kea_dhe_dss, kt_dh, ssl_sign_dsa, PR_FALSE, 0, PR_FALSE, PR_TR
UE, SEC_OID_TLS_DHE_DSS}, | |
318 {kea_dhe_dss_export, kt_dh, ssl_sign_dsa, PR_TRUE, 512, PR_FALSE, PR_TR
UE, SEC_OID_TLS_DHE_DSS_EXPORT}, | |
319 {kea_dhe_rsa, kt_dh, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_TR
UE, SEC_OID_TLS_DHE_RSA}, | |
320 {kea_dhe_rsa_export, kt_dh, ssl_sign_rsa, PR_TRUE, 512, PR_FALSE, PR_TR
UE, SEC_OID_TLS_DHE_RSA_EXPORT}, | |
321 {kea_dh_anon, kt_dh, ssl_sign_null, PR_FALSE, 0, PR_FALSE, PR_TR
UE, SEC_OID_TLS_DH_ANON}, | |
322 {kea_dh_anon_export, kt_dh, ssl_sign_null, PR_TRUE, 512, PR_FALSE, PR_TR
UE, SEC_OID_TLS_DH_ANON_EXPORT}, | |
323 {kea_rsa_fips, kt_rsa, ssl_sign_rsa, PR_FALSE, 0, PR_TRUE, PR_FA
LSE, SEC_OID_TLS_RSA}, | |
324 #ifndef NSS_DISABLE_ECC | |
325 {kea_ecdh_ecdsa, kt_ecdh, ssl_sign_ecdsa, PR_FALSE, 0, PR_FALSE, PR_FA
LSE, SEC_OID_TLS_ECDH_ECDSA}, | |
326 {kea_ecdhe_ecdsa, kt_ecdh, ssl_sign_ecdsa, PR_FALSE, 0, PR_FALSE, PR_TR
UE, SEC_OID_TLS_ECDHE_ECDSA}, | |
327 {kea_ecdh_rsa, kt_ecdh, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FA
LSE, SEC_OID_TLS_ECDH_RSA}, | |
328 {kea_ecdhe_rsa, kt_ecdh, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_TR
UE, SEC_OID_TLS_ECDHE_RSA}, | |
329 {kea_ecdh_anon, kt_ecdh, ssl_sign_null, PR_FALSE, 0, PR_FALSE, PR_TR
UE, SEC_OID_TLS_ECDH_ANON}, | |
330 #endif /* NSS_DISABLE_ECC */ | |
331 }; | |
332 | |
333 /* must use ssl_LookupCipherSuiteDef to access */ | |
334 static const ssl3CipherSuiteDef cipher_suite_defs[] = | |
335 { | |
336 /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg */ | |
337 | |
338 {TLS_NULL_WITH_NULL_NULL, cipher_null, mac_null, kea_null}, | |
339 {TLS_RSA_WITH_NULL_MD5, cipher_null, mac_md5, kea_rsa}, | |
340 {TLS_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_rsa}, | |
341 {TLS_RSA_WITH_NULL_SHA256, cipher_null, hmac_sha256, kea_rsa}, | |
342 {TLS_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export}, | |
343 {TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, mac_md5, kea_rsa}, | |
344 {TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_rsa}, | |
345 {TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, | |
346 cipher_rc2_40, mac_md5, kea_rsa_export}, | |
347 #if 0 /* not implemented */ | |
348 {TLS_RSA_WITH_IDEA_CBC_SHA, cipher_idea, mac_sha, kea_rsa}, | |
349 {TLS_RSA_EXPORT_WITH_DES40_CBC_SHA, | |
350 cipher_des40, mac_sha, kea_rsa_export}, | |
351 #endif | |
352 {TLS_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa}, | |
353 {TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa}, | |
354 {TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_dss}, | |
355 {TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, | |
356 cipher_3des, mac_sha, kea_dhe_dss}, | |
357 {TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_dhe_dss}, | |
358 #if 0 /* not implemented */ | |
359 {TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA, | |
360 cipher_des40, mac_sha, kea_dh_dss_export}, | |
361 {TLS_DH_DSS_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_dss}, | |
362 {TLS_DH_DSS_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_dss}, | |
363 {TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA, | |
364 cipher_des40, mac_sha, kea_dh_rsa_export}, | |
365 {TLS_DH_RSA_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_rsa}, | |
366 {TLS_DH_RSA_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_rsa}, | |
367 {TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, | |
368 cipher_des40, mac_sha, kea_dh_dss_export}, | |
369 {TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, | |
370 cipher_des40, mac_sha, kea_dh_rsa_export}, | |
371 #endif | |
372 {TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_rsa}, | |
373 {TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, | |
374 cipher_3des, mac_sha, kea_dhe_rsa}, | |
375 #if 0 | |
376 {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export}, | |
377 {TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA, | |
378 cipher_des40, mac_sha, kea_dh_anon_export}, | |
379 {TLS_DH_anon_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_anon}, | |
380 {TLS_DH_anon_WITH_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_anon}, | |
381 #endif | |
382 | |
383 | |
384 /* New TLS cipher suites */ | |
385 {TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_rsa}, | |
386 {TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_rsa}, | |
387 {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_dss}, | |
388 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_rsa}, | |
389 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_r
sa}, | |
390 {TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_rsa}, | |
391 {TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_rsa}, | |
392 {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_dss}, | |
393 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_rsa}, | |
394 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_r
sa}, | |
395 #if 0 | |
396 {TLS_DH_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_dss}, | |
397 {TLS_DH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_rsa}, | |
398 {TLS_DH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_anon}, | |
399 {TLS_DH_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_dss}, | |
400 {TLS_DH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_rsa}, | |
401 {TLS_DH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_anon}, | |
402 #endif | |
403 | |
404 {TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, mac_sha, kea_rsa}, | |
405 | |
406 {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa}, | |
407 {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, | |
408 cipher_camellia_128, mac_sha, kea_dhe_dss}, | |
409 {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, | |
410 cipher_camellia_128, mac_sha, kea_dhe_rsa}, | |
411 {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa}, | |
412 {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, | |
413 cipher_camellia_256, mac_sha, kea_dhe_dss}, | |
414 {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, | |
415 cipher_camellia_256, mac_sha, kea_dhe_rsa}, | |
416 | |
417 {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, | |
418 cipher_des, mac_sha,kea_rsa_export_1024}, | |
419 {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, | |
420 cipher_rc4_56, mac_sha,kea_rsa_export_1024}, | |
421 | |
422 {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips}, | |
423 {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa_fips}, | |
424 | |
425 {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_
rsa}, | |
426 {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_rsa}, | |
427 {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ec
dhe_rsa}, | |
428 {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_
ecdhe_ecdsa}, | |
429 | |
430 {TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_
dss}, | |
431 {TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_d
ss}, | |
432 {TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_d
ss}, | |
433 | |
434 {TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, mac_aead, kea_d
he_rsa}, | |
435 {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, mac_aead, kea
_ecdhe_rsa}, | |
436 {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, mac_aead, k
ea_ecdhe_ecdsa}, | |
437 | |
438 #ifndef NSS_DISABLE_ECC | |
439 {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa}, | |
440 {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa}, | |
441 {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa}
, | |
442 {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecds
a}, | |
443 {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecds
a}, | |
444 | |
445 {TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_ecdsa
}, | |
446 {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_ecdsa
}, | |
447 {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecds
a}, | |
448 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ec
dsa}, | |
449 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_e
cdhe_ecdsa}, | |
450 {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ec
dsa}, | |
451 | |
452 {TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_rsa}, | |
453 {TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_rsa}, | |
454 {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_rsa}, | |
455 {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_rsa}, | |
456 {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_rsa}, | |
457 | |
458 {TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_rsa
}, | |
459 {TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_rsa
}, | |
460 {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_rsa
}, | |
461 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_rsa
}, | |
462 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecd
he_rsa}, | |
463 {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_rsa
}, | |
464 | |
465 #if 0 | |
466 {TLS_ECDH_anon_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_anon
}, | |
467 {TLS_ECDH_anon_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_anon
}, | |
468 {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_anon
}, | |
469 {TLS_ECDH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_anon
}, | |
470 {TLS_ECDH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_anon
}, | |
471 #endif | |
472 #endif /* NSS_DISABLE_ECC */ | |
473 }; | |
474 /* clang-format on */ | |
475 | |
476 static const CK_MECHANISM_TYPE kea_alg_defs[] = { | |
477 0x80000000L, | |
478 CKM_RSA_PKCS, | |
479 CKM_DH_PKCS_DERIVE, | |
480 CKM_KEA_KEY_DERIVE, | |
481 CKM_ECDH1_DERIVE | |
482 }; | |
483 | |
484 typedef struct SSLCipher2MechStr { | |
485 SSLCipherAlgorithm calg; | |
486 CK_MECHANISM_TYPE cmech; | |
487 } SSLCipher2Mech; | |
488 | |
489 /* indexed by type SSLCipherAlgorithm */ | |
490 static const SSLCipher2Mech alg2Mech[] = { | |
491 /* calg, cmech */ | |
492 { calg_null, (CK_MECHANISM_TYPE)0x80000000L }, | |
493 { calg_rc4, CKM_RC4 }, | |
494 { calg_rc2, CKM_RC2_CBC }, | |
495 { calg_des, CKM_DES_CBC }, | |
496 { calg_3des, CKM_DES3_CBC }, | |
497 { calg_idea, CKM_IDEA_CBC }, | |
498 { calg_fortezza, CKM_SKIPJACK_CBC64 }, | |
499 { calg_aes, CKM_AES_CBC }, | |
500 { calg_camellia, CKM_CAMELLIA_CBC }, | |
501 { calg_seed, CKM_SEED_CBC }, | |
502 { calg_aes_gcm, CKM_AES_GCM }, | |
503 { calg_chacha20, CKM_NSS_CHACHA20_POLY1305 }, | |
504 /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */ | |
505 }; | |
506 | |
507 #define mmech_invalid (CK_MECHANISM_TYPE)0x80000000L | |
508 #define mmech_md5 CKM_SSL3_MD5_MAC | |
509 #define mmech_sha CKM_SSL3_SHA1_MAC | |
510 #define mmech_md5_hmac CKM_MD5_HMAC | |
511 #define mmech_sha_hmac CKM_SHA_1_HMAC | |
512 #define mmech_sha256_hmac CKM_SHA256_HMAC | |
513 | |
514 /* clang-format off */ | |
515 static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */ | |
516 /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */ | |
517 /* mac mmech pad_size mac_size */ | |
518 { mac_null, mmech_invalid, 0, 0 , 0}, | |
519 { mac_md5, mmech_md5, 48, MD5_LENGTH, SEC_OID_HMAC_MD5 }, | |
520 { mac_sha, mmech_sha, 40, SHA1_LENGTH, SEC_OID_HMAC_SHA1}, | |
521 {hmac_md5, mmech_md5_hmac, 0, MD5_LENGTH, SEC_OID_HMAC_MD5}, | |
522 {hmac_sha, mmech_sha_hmac, 0, SHA1_LENGTH, SEC_OID_HMAC_SHA1}, | |
523 {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH, SEC_OID_HMAC_SHA256}, | |
524 { mac_aead, mmech_invalid, 0, 0, 0 }, | |
525 }; | |
526 /* clang-format on */ | |
527 | |
528 /* indexed by SSL3BulkCipher */ | |
529 const char *const ssl3_cipherName[] = { | |
530 "NULL", | |
531 "RC4", | |
532 "RC4-40", | |
533 "RC4-56", | |
534 "RC2-CBC", | |
535 "RC2-CBC-40", | |
536 "DES-CBC", | |
537 "3DES-EDE-CBC", | |
538 "DES-CBC-40", | |
539 "IDEA-CBC", | |
540 "AES-128", | |
541 "AES-256", | |
542 "Camellia-128", | |
543 "Camellia-256", | |
544 "SEED-CBC", | |
545 "AES-128-GCM", | |
546 "missing" | |
547 }; | |
548 | |
549 const PRUint8 tls13_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E, | |
550 0x47, 0x52, 0x44, 0x01 }; | |
551 const PRUint8 tls12_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E, | |
552 0x47, 0x52, 0x44, 0x00 }; | |
553 | |
554 #ifndef NSS_DISABLE_ECC | |
555 /* The ECCWrappedKeyInfo structure defines how various pieces of | |
556 * information are laid out within wrappedSymmetricWrappingkey | |
557 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is | |
558 * a 512-byte buffer (see sslimpl.h), the variable length field | |
559 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes. | |
560 * | |
561 * XXX For now, NSS only supports named elliptic curves of size 571 bits | |
562 * or smaller. The public value will fit within 145 bytes and EC params | |
563 * will fit within 12 bytes. We'll need to revisit this when NSS | |
564 * supports arbitrary curves. | |
565 */ | |
566 #define MAX_EC_WRAPPED_KEY_BUFLEN 504 | |
567 | |
568 typedef struct ECCWrappedKeyInfoStr { | |
569 PRUint16 size; /* EC public key size in bits */ | |
570 PRUint16 encodedParamLen; /* length (in bytes) of DER encoded
EC params */ | |
571 PRUint16 pubValueLen; /* length (in bytes) of EC public va
lue */ | |
572 PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped
key */ | |
573 PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */ | |
574 /* EC public-key params, the EC public value and the wrapped key */ | |
575 } ECCWrappedKeyInfo; | |
576 #endif /* NSS_DISABLE_ECC */ | |
577 | |
578 CK_MECHANISM_TYPE | |
579 ssl3_Alg2Mech(SSLCipherAlgorithm calg) | |
580 { | |
581 PORT_Assert(alg2Mech[calg].calg == calg); | |
582 return alg2Mech[calg].cmech; | |
583 } | |
584 | |
585 #if defined(TRACE) | |
586 | |
587 static char * | |
588 ssl3_DecodeHandshakeType(int msgType) | |
589 { | |
590 char *rv; | |
591 static char line[40]; | |
592 | |
593 switch (msgType) { | |
594 case hello_request: | |
595 rv = "hello_request (0)"; | |
596 break; | |
597 case client_hello: | |
598 rv = "client_hello (1)"; | |
599 break; | |
600 case server_hello: | |
601 rv = "server_hello (2)"; | |
602 break; | |
603 case hello_verify_request: | |
604 rv = "hello_verify_request (3)"; | |
605 break; | |
606 case encrypted_extensions: | |
607 rv = "encrypted_extensions (8)"; | |
608 break; | |
609 case certificate: | |
610 rv = "certificate (11)"; | |
611 break; | |
612 case server_key_exchange: | |
613 rv = "server_key_exchange (12)"; | |
614 break; | |
615 case certificate_request: | |
616 rv = "certificate_request (13)"; | |
617 break; | |
618 case server_hello_done: | |
619 rv = "server_hello_done (14)"; | |
620 break; | |
621 case certificate_verify: | |
622 rv = "certificate_verify (15)"; | |
623 break; | |
624 case client_key_exchange: | |
625 rv = "client_key_exchange (16)"; | |
626 break; | |
627 case finished: | |
628 rv = "finished (20)"; | |
629 break; | |
630 default: | |
631 sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType); | |
632 rv = line; | |
633 } | |
634 return rv; | |
635 } | |
636 | |
637 static char * | |
638 ssl3_DecodeContentType(int msgType) | |
639 { | |
640 char *rv; | |
641 static char line[40]; | |
642 | |
643 switch (msgType) { | |
644 case content_change_cipher_spec: | |
645 rv = "change_cipher_spec (20)"; | |
646 break; | |
647 case content_alert: | |
648 rv = "alert (21)"; | |
649 break; | |
650 case content_handshake: | |
651 rv = "handshake (22)"; | |
652 break; | |
653 case content_application_data: | |
654 rv = "application_data (23)"; | |
655 break; | |
656 default: | |
657 sprintf(line, "*UNKNOWN* record type! (%d)", msgType); | |
658 rv = line; | |
659 } | |
660 return rv; | |
661 } | |
662 | |
663 #endif | |
664 | |
665 SSL3Statistics * | |
666 SSL_GetStatistics(void) | |
667 { | |
668 return &ssl3stats; | |
669 } | |
670 | |
671 typedef struct tooLongStr { | |
672 #if defined(IS_LITTLE_ENDIAN) | |
673 PRInt32 low; | |
674 PRInt32 high; | |
675 #else | |
676 PRInt32 high; | |
677 PRInt32 low; | |
678 #endif | |
679 } tooLong; | |
680 | |
681 void | |
682 SSL_AtomicIncrementLong(long *x) | |
683 { | |
684 if ((sizeof *x) == sizeof(PRInt32)) { | |
685 PR_ATOMIC_INCREMENT((PRInt32 *)x); | |
686 } else { | |
687 tooLong *tl = (tooLong *)x; | |
688 if (PR_ATOMIC_INCREMENT(&tl->low) == 0) | |
689 PR_ATOMIC_INCREMENT(&tl->high); | |
690 } | |
691 } | |
692 | |
693 static PRBool | |
694 ssl3_CipherSuiteAllowedForVersionRange( | |
695 ssl3CipherSuite cipherSuite, | |
696 const SSLVersionRange *vrange) | |
697 { | |
698 switch (cipherSuite) { | |
699 /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or | |
700 * later. This set of cipher suites is similar to, but different from, t
he | |
701 * set of cipher suites considered exportable by SSL_IsExportCipherSuite
. | |
702 */ | |
703 case TLS_RSA_EXPORT_WITH_RC4_40_MD5: | |
704 case TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5: | |
705 /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented | |
706 * TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented | |
707 * TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented | |
708 * TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented | |
709 * TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented | |
710 * TLS_DH_anon_EXPORT_WITH_RC4_40_MD5: never implemented | |
711 * TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA: never implemented | |
712 */ | |
713 return vrange->min <= SSL_LIBRARY_VERSION_TLS_1_0; | |
714 | |
715 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: | |
716 case TLS_RSA_WITH_AES_256_CBC_SHA256: | |
717 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: | |
718 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: | |
719 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: | |
720 case TLS_RSA_WITH_AES_128_CBC_SHA256: | |
721 case TLS_RSA_WITH_AES_128_GCM_SHA256: | |
722 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: | |
723 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: | |
724 case TLS_RSA_WITH_NULL_SHA256: | |
725 case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: | |
726 return vrange->max == SSL_LIBRARY_VERSION_TLS_1_2; | |
727 | |
728 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: | |
729 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: | |
730 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: | |
731 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2; | |
732 | |
733 /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves a
nd | |
734 * point formats.*/ | |
735 case TLS_ECDH_ECDSA_WITH_NULL_SHA: | |
736 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA: | |
737 case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: | |
738 case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: | |
739 case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: | |
740 case TLS_ECDHE_ECDSA_WITH_NULL_SHA: | |
741 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: | |
742 case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: | |
743 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: | |
744 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: | |
745 case TLS_ECDH_RSA_WITH_NULL_SHA: | |
746 case TLS_ECDH_RSA_WITH_RC4_128_SHA: | |
747 case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: | |
748 case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: | |
749 case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: | |
750 case TLS_ECDHE_RSA_WITH_NULL_SHA: | |
751 case TLS_ECDHE_RSA_WITH_RC4_128_SHA: | |
752 case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: | |
753 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: | |
754 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: | |
755 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0 && | |
756 vrange->min < SSL_LIBRARY_VERSION_TLS_1_3; | |
757 | |
758 default: | |
759 return vrange->min < SSL_LIBRARY_VERSION_TLS_1_3; | |
760 } | |
761 } | |
762 | |
763 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */ | |
764 /* XXX This does a linear search. A binary search would be better. */ | |
765 static const ssl3CipherSuiteDef * | |
766 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite) | |
767 { | |
768 int cipher_suite_def_len = | |
769 sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]); | |
770 int i; | |
771 | |
772 for (i = 0; i < cipher_suite_def_len; i++) { | |
773 if (cipher_suite_defs[i].cipher_suite == suite) | |
774 return &cipher_suite_defs[i]; | |
775 } | |
776 PORT_Assert(PR_FALSE); /* We should never get here. */ | |
777 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); | |
778 return NULL; | |
779 } | |
780 | |
781 /* Find the cipher configuration struct associate with suite */ | |
782 /* XXX This does a linear search. A binary search would be better. */ | |
783 static ssl3CipherSuiteCfg * | |
784 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites) | |
785 { | |
786 int i; | |
787 | |
788 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { | |
789 if (suites[i].cipher_suite == suite) | |
790 return &suites[i]; | |
791 } | |
792 /* return NULL and let the caller handle it. */ | |
793 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); | |
794 return NULL; | |
795 } | |
796 | |
797 /* Initialize the suite->isPresent value for config_match | |
798 * Returns count of enabled ciphers supported by extant tokens, | |
799 * regardless of policy or user preference. | |
800 * If this returns zero, the user cannot do SSL v3. | |
801 */ | |
802 int | |
803 ssl3_config_match_init(sslSocket *ss) | |
804 { | |
805 ssl3CipherSuiteCfg *suite; | |
806 const ssl3CipherSuiteDef *cipher_def; | |
807 SSLCipherAlgorithm cipher_alg; | |
808 CK_MECHANISM_TYPE cipher_mech; | |
809 SSL3KEAType exchKeyType; | |
810 int i; | |
811 int numPresent = 0; | |
812 int numEnabled = 0; | |
813 PRBool isServer; | |
814 sslServerCerts *svrAuth; | |
815 | |
816 PORT_Assert(ss); | |
817 if (!ss) { | |
818 PORT_SetError(SEC_ERROR_INVALID_ARGS); | |
819 return 0; | |
820 } | |
821 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { | |
822 return 0; | |
823 } | |
824 isServer = (PRBool)(ss->sec.isServer != 0); | |
825 | |
826 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { | |
827 suite = &ss->cipherSuites[i]; | |
828 if (suite->enabled) { | |
829 ++numEnabled; | |
830 /* We need the cipher defs to see if we have a token that can handle | |
831 * this cipher. It isn't part of the static definition. | |
832 */ | |
833 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite); | |
834 if (!cipher_def) { | |
835 suite->isPresent = PR_FALSE; | |
836 continue; | |
837 } | |
838 cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg; | |
839 cipher_mech = ssl3_Alg2Mech(cipher_alg); | |
840 exchKeyType = | |
841 kea_defs[cipher_def->key_exchange_alg].exchKeyType; | |
842 #ifdef NSS_DISABLE_ECC | |
843 svrAuth = ss->serverCerts + exchKeyType; | |
844 #else | |
845 /* XXX SSLKEAType isn't really a good choice for | |
846 * indexing certificates. It doesn't work for | |
847 * (EC)DHE-* ciphers. Here we use a hack to ensure | |
848 * that the server uses an RSA cert for (EC)DHE-RSA. | |
849 */ | |
850 switch (cipher_def->key_exchange_alg) { | |
851 case kea_dhe_dss: | |
852 svrAuth = ss->serverCerts + ssl_kea_dh; | |
853 break; | |
854 case kea_ecdhe_rsa: | |
855 case kea_dhe_rsa: | |
856 svrAuth = ss->serverCerts + kt_rsa; | |
857 break; | |
858 case kea_ecdh_ecdsa: | |
859 case kea_ecdh_rsa: | |
860 /* | |
861 * XXX We ought to have different indices for | |
862 * ECDSA- and RSA-signed EC certificates so | |
863 * we could support both key exchange mechanisms | |
864 * simultaneously. For now, both of them use | |
865 * whatever is in the certificate slot for kt_ecdh | |
866 */ | |
867 case kea_dhe_dss_export: | |
868 case kea_dhe_rsa_export: | |
869 default: | |
870 svrAuth = ss->serverCerts + exchKeyType; | |
871 break; | |
872 } | |
873 #endif /* NSS_DISABLE_ECC */ | |
874 | |
875 /* Mark the suites that are backed by real tokens, certs and keys */ | |
876 suite->isPresent = (PRBool)(((exchKeyType == kt_null) || | |
877 ((!isServer || | |
878 (svrAuth->serverKeyPair && svrAuth->S
ERVERKEY && | |
879 svrAuth->serverCertChain)) && | |
880 PK11_TokenExists(kea_alg_defs[exchKeyT
ype]))) && | |
881 ((cipher_alg == calg_null) || PK11_Token
Exists(cipher_mech))); | |
882 if (suite->isPresent) | |
883 ++numPresent; | |
884 } | |
885 } | |
886 PORT_Assert(numPresent > 0 || numEnabled == 0); | |
887 if (numPresent <= 0) { | |
888 PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED); | |
889 } | |
890 return numPresent; | |
891 } | |
892 | |
893 /* return PR_TRUE if suite matches policy, enabled state and is applicable to | |
894 * the given version range. */ | |
895 /* It would be a REALLY BAD THING (tm) if we ever permitted the use | |
896 ** of a cipher that was NOT_ALLOWED. So, if this is ever called with | |
897 ** policy == SSL_NOT_ALLOWED, report no match. | |
898 */ | |
899 /* adjust suite enabled to the availability of a token that can do the | |
900 * cipher suite. */ | |
901 static PRBool | |
902 config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled, | |
903 const SSLVersionRange *vrange, const sslSocket *ss) | |
904 { | |
905 const ssl3CipherSuiteDef *cipher_def; | |
906 | |
907 PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE); | |
908 if (policy == SSL_NOT_ALLOWED || !enabled) | |
909 return PR_FALSE; | |
910 | |
911 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite); | |
912 PORT_Assert(cipher_def != NULL); | |
913 | |
914 PORT_Assert(ss != NULL); | |
915 if (ss->sec.isServer && !ss->opt.enableServerDhe && | |
916 kea_defs[cipher_def->key_exchange_alg].exchKeyType == ssl_kea_dh) | |
917 return PR_FALSE; | |
918 | |
919 return (PRBool)(suite->enabled && | |
920 suite->isPresent && | |
921 suite->policy != SSL_NOT_ALLOWED && | |
922 suite->policy <= policy && | |
923 ssl3_CipherSuiteAllowedForVersionRange( | |
924 suite->cipher_suite, vrange)); | |
925 } | |
926 | |
927 /* return number of cipher suites that match policy, enabled state and are | |
928 * applicable for the configured protocol version range. */ | |
929 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */ | |
930 static int | |
931 count_cipher_suites(sslSocket *ss, int policy, PRBool enabled) | |
932 { | |
933 int i, count = 0; | |
934 | |
935 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { | |
936 return 0; | |
937 } | |
938 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { | |
939 if (config_match(&ss->cipherSuites[i], policy, enabled, &ss->vrange, ss)
) | |
940 count++; | |
941 } | |
942 if (count <= 0) { | |
943 PORT_SetError(SSL_ERROR_SSL_DISABLED); | |
944 } | |
945 return count; | |
946 } | |
947 | |
948 /* | |
949 * Null compression, mac and encryption functions | |
950 */ | |
951 | |
952 static SECStatus | |
953 Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen, | |
954 const unsigned char *input, int inputLen) | |
955 { | |
956 if (inputLen > maxOutputLen) { | |
957 *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */ | |
958 PORT_SetError(SEC_ERROR_OUTPUT_LEN); | |
959 return SECFailure; | |
960 } | |
961 *outputLen = inputLen; | |
962 if (input != output) | |
963 PORT_Memcpy(output, input, inputLen); | |
964 return SECSuccess; | |
965 } | |
966 | |
967 /* | |
968 * SSL3 Utility functions | |
969 */ | |
970 | |
971 /* allowLargerPeerVersion controls whether the function will select the | |
972 * highest enabled SSL version or fail when peerVersion is greater than the | |
973 * highest enabled version. | |
974 * | |
975 * If allowLargerPeerVersion is true, peerVersion is the peer's highest | |
976 * enabled version rather than the peer's selected version. | |
977 */ | |
978 SECStatus | |
979 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion, | |
980 PRBool allowLargerPeerVersion) | |
981 { | |
982 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { | |
983 PORT_SetError(SSL_ERROR_SSL_DISABLED); | |
984 return SECFailure; | |
985 } | |
986 | |
987 if (peerVersion < ss->vrange.min || | |
988 (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) { | |
989 PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); | |
990 return SECFailure; | |
991 } | |
992 | |
993 ss->version = PR_MIN(peerVersion, ss->vrange.max); | |
994 PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, ss->version)); | |
995 | |
996 return SECSuccess; | |
997 } | |
998 | |
999 static SECStatus | |
1000 ssl3_GetNewRandom(SSL3Random *random) | |
1001 { | |
1002 SECStatus rv; | |
1003 | |
1004 rv = PK11_GenerateRandom(random->rand, SSL3_RANDOM_LENGTH); | |
1005 if (rv != SECSuccess) { | |
1006 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); | |
1007 } | |
1008 return rv; | |
1009 } | |
1010 | |
1011 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */ | |
1012 SECStatus | |
1013 ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf, | |
1014 PRBool isTLS) | |
1015 { | |
1016 SECStatus rv = SECFailure; | |
1017 PRBool doDerEncode = PR_FALSE; | |
1018 int signatureLen; | |
1019 SECItem hashItem; | |
1020 | |
1021 buf->data = NULL; | |
1022 | |
1023 switch (key->keyType) { | |
1024 case rsaKey: | |
1025 hashItem.data = hash->u.raw; | |
1026 hashItem.len = hash->len; | |
1027 break; | |
1028 case dsaKey: | |
1029 doDerEncode = isTLS; | |
1030 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. | |
1031 * In that case, we use just the SHA1 part. */ | |
1032 if (hash->hashAlg == ssl_hash_none) { | |
1033 hashItem.data = hash->u.s.sha; | |
1034 hashItem.len = sizeof(hash->u.s.sha); | |
1035 } else { | |
1036 hashItem.data = hash->u.raw; | |
1037 hashItem.len = hash->len; | |
1038 } | |
1039 break; | |
1040 #ifndef NSS_DISABLE_ECC | |
1041 case ecKey: | |
1042 doDerEncode = PR_TRUE; | |
1043 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. | |
1044 * In that case, we use just the SHA1 part. */ | |
1045 if (hash->hashAlg == ssl_hash_none) { | |
1046 hashItem.data = hash->u.s.sha; | |
1047 hashItem.len = sizeof(hash->u.s.sha); | |
1048 } else { | |
1049 hashItem.data = hash->u.raw; | |
1050 hashItem.len = hash->len; | |
1051 } | |
1052 break; | |
1053 #endif /* NSS_DISABLE_ECC */ | |
1054 default: | |
1055 PORT_SetError(SEC_ERROR_INVALID_KEY); | |
1056 goto done; | |
1057 } | |
1058 PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len)); | |
1059 | |
1060 if (hash->hashAlg == ssl_hash_none) { | |
1061 signatureLen = PK11_SignatureLen(key); | |
1062 if (signatureLen <= 0) { | |
1063 PORT_SetError(SEC_ERROR_INVALID_KEY); | |
1064 goto done; | |
1065 } | |
1066 | |
1067 buf->len = (unsigned)signatureLen; | |
1068 buf->data = (unsigned char *)PORT_Alloc(signatureLen); | |
1069 if (!buf->data) | |
1070 goto done; /* error code was set. */ | |
1071 | |
1072 rv = PK11_Sign(key, buf, &hashItem); | |
1073 } else { | |
1074 SECOidTag hashOID = ssl3_TLSHashAlgorithmToOID(hash->hashAlg); | |
1075 rv = SGN_Digest(key, hashOID, buf, &hashItem); | |
1076 } | |
1077 if (rv != SECSuccess) { | |
1078 ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE); | |
1079 } else if (doDerEncode) { | |
1080 SECItem derSig = { siBuffer, NULL, 0 }; | |
1081 | |
1082 /* This also works for an ECDSA signature */ | |
1083 rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len); | |
1084 if (rv == SECSuccess) { | |
1085 PORT_Free(buf->data); /* discard unencoded signature. */ | |
1086 *buf = derSig; /* give caller encoded signature. */ | |
1087 } else if (derSig.data) { | |
1088 PORT_Free(derSig.data); | |
1089 } | |
1090 } | |
1091 | |
1092 PRINT_BUF(60, (NULL, "signed hashes", (unsigned char *)buf->data, buf->len))
; | |
1093 done: | |
1094 if (rv != SECSuccess && buf->data) { | |
1095 PORT_Free(buf->data); | |
1096 buf->data = NULL; | |
1097 } | |
1098 return rv; | |
1099 } | |
1100 | |
1101 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */ | |
1102 SECStatus | |
1103 ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert, | |
1104 SECItem *buf, PRBool isTLS, void *pwArg) | |
1105 { | |
1106 SECKEYPublicKey *key; | |
1107 SECItem *signature = NULL; | |
1108 SECStatus rv; | |
1109 SECItem hashItem; | |
1110 SECOidTag encAlg; | |
1111 SECOidTag hashAlg; | |
1112 | |
1113 PRINT_BUF(60, (NULL, "check signed hashes", | |
1114 buf->data, buf->len)); | |
1115 | |
1116 key = CERT_ExtractPublicKey(cert); | |
1117 if (key == NULL) { | |
1118 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); | |
1119 return SECFailure; | |
1120 } | |
1121 | |
1122 hashAlg = ssl3_TLSHashAlgorithmToOID(hash->hashAlg); | |
1123 switch (key->keyType) { | |
1124 case rsaKey: | |
1125 encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION; | |
1126 hashItem.data = hash->u.raw; | |
1127 hashItem.len = hash->len; | |
1128 break; | |
1129 case dsaKey: | |
1130 encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE; | |
1131 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. | |
1132 * In that case, we use just the SHA1 part. */ | |
1133 if (hash->hashAlg == ssl_hash_none) { | |
1134 hashItem.data = hash->u.s.sha; | |
1135 hashItem.len = sizeof(hash->u.s.sha); | |
1136 } else { | |
1137 hashItem.data = hash->u.raw; | |
1138 hashItem.len = hash->len; | |
1139 } | |
1140 /* Allow DER encoded DSA signatures in SSL 3.0 */ | |
1141 if (isTLS || buf->len != SECKEY_SignatureLen(key)) { | |
1142 signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key)
); | |
1143 if (!signature) { | |
1144 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); | |
1145 return SECFailure; | |
1146 } | |
1147 buf = signature; | |
1148 } | |
1149 break; | |
1150 | |
1151 #ifndef NSS_DISABLE_ECC | |
1152 case ecKey: | |
1153 encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY; | |
1154 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. | |
1155 * In that case, we use just the SHA1 part. | |
1156 * ECDSA signatures always encode the integers r and s using ASN.1 | |
1157 * (unlike DSA where ASN.1 encoding is used with TLS but not with | |
1158 * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA. | |
1159 */ | |
1160 if (hash->hashAlg == ssl_hash_none) { | |
1161 hashAlg = SEC_OID_SHA1; | |
1162 hashItem.data = hash->u.s.sha; | |
1163 hashItem.len = sizeof(hash->u.s.sha); | |
1164 } else { | |
1165 hashItem.data = hash->u.raw; | |
1166 hashItem.len = hash->len; | |
1167 } | |
1168 break; | |
1169 #endif /* NSS_DISABLE_ECC */ | |
1170 | |
1171 default: | |
1172 SECKEY_DestroyPublicKey(key); | |
1173 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); | |
1174 return SECFailure; | |
1175 } | |
1176 | |
1177 PRINT_BUF(60, (NULL, "hash(es) to be verified", | |
1178 hashItem.data, hashItem.len)); | |
1179 | |
1180 if (hashAlg == SEC_OID_UNKNOWN || key->keyType == dsaKey) { | |
1181 /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded. | |
1182 * DSA signatures are DER-encoded in TLS but not in SSL3 and the code | |
1183 * above always removes the DER encoding of DSA signatures when | |
1184 * present. Thus DSA signatures are always verified with PK11_Verify. | |
1185 */ | |
1186 rv = PK11_Verify(key, buf, &hashItem, pwArg); | |
1187 } else { | |
1188 rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg, | |
1189 pwArg); | |
1190 } | |
1191 SECKEY_DestroyPublicKey(key); | |
1192 if (signature) { | |
1193 SECITEM_FreeItem(signature, PR_TRUE); | |
1194 } | |
1195 if (rv != SECSuccess) { | |
1196 ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); | |
1197 } | |
1198 return rv; | |
1199 } | |
1200 | |
1201 /* Caller must set hiLevel error code. */ | |
1202 /* Called from ssl3_ComputeExportRSAKeyHash | |
1203 * ssl3_ComputeDHKeyHash | |
1204 * which are called from ssl3_HandleServerKeyExchange. | |
1205 * | |
1206 * hashAlg: ssl_hash_none indicates the pre-1.2, MD5/SHA1 combination hash. | |
1207 */ | |
1208 SECStatus | |
1209 ssl3_ComputeCommonKeyHash(SSLHashType hashAlg, | |
1210 PRUint8 *hashBuf, unsigned int bufLen, | |
1211 SSL3Hashes *hashes, PRBool bypassPKCS11) | |
1212 { | |
1213 SECStatus rv; | |
1214 SECOidTag hashOID; | |
1215 | |
1216 #ifndef NO_PKCS11_BYPASS | |
1217 if (bypassPKCS11) { | |
1218 if (hashAlg == ssl_hash_none) { | |
1219 MD5_HashBuf(hashes->u.s.md5, hashBuf, bufLen); | |
1220 SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen); | |
1221 hashes->len = MD5_LENGTH + SHA1_LENGTH; | |
1222 } else if (hashAlg == ssl_hash_sha1) { | |
1223 SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen); | |
1224 hashes->len = SHA1_LENGTH; | |
1225 } else if (hashAlg == ssl_hash_sha256) { | |
1226 SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen); | |
1227 hashes->len = SHA256_LENGTH; | |
1228 } else if (hashAlg == ssl_hash_sha384) { | |
1229 SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen); | |
1230 hashes->len = SHA384_LENGTH; | |
1231 } else if (hashAlg == ssl_hash_sha512) { | |
1232 SHA512_HashBuf(hashes->u.raw, hashBuf, bufLen); | |
1233 hashes->len = SHA512_LENGTH; | |
1234 } else { | |
1235 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); | |
1236 return SECFailure; | |
1237 } | |
1238 } else | |
1239 #endif | |
1240 { | |
1241 if (hashAlg == ssl_hash_none) { | |
1242 rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen); | |
1243 if (rv != SECSuccess) { | |
1244 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
1245 return rv; | |
1246 } | |
1247 rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen); | |
1248 if (rv != SECSuccess) { | |
1249 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
1250 return rv; | |
1251 } | |
1252 hashes->len = MD5_LENGTH + SHA1_LENGTH; | |
1253 } else { | |
1254 hashOID = ssl3_TLSHashAlgorithmToOID(hashAlg); | |
1255 hashes->len = HASH_ResultLenByOidTag(hashOID); | |
1256 if (hashes->len == 0 || hashes->len > sizeof(hashes->u.raw)) { | |
1257 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); | |
1258 return SECFailure; | |
1259 } | |
1260 rv = PK11_HashBuf(hashOID, hashes->u.raw, hashBuf, bufLen); | |
1261 if (rv != SECSuccess) { | |
1262 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
1263 return rv; | |
1264 } | |
1265 } | |
1266 } | |
1267 hashes->hashAlg = hashAlg; | |
1268 return SECSuccess; | |
1269 } | |
1270 | |
1271 /* Caller must set hiLevel error code. | |
1272 ** Called from ssl3_SendServerKeyExchange and | |
1273 ** ssl3_HandleServerKeyExchange. | |
1274 */ | |
1275 static SECStatus | |
1276 ssl3_ComputeExportRSAKeyHash(SSLHashType hashAlg, | |
1277 SECItem modulus, SECItem publicExponent, | |
1278 SSL3Random *client_rand, SSL3Random *server_rand, | |
1279 SSL3Hashes *hashes, PRBool bypassPKCS11) | |
1280 { | |
1281 PRUint8 *hashBuf; | |
1282 PRUint8 *pBuf; | |
1283 SECStatus rv = SECSuccess; | |
1284 unsigned int bufLen; | |
1285 PRUint8 buf[2 * SSL3_RANDOM_LENGTH + 2 + 4096 / 8 + 2 + 4096 / 8]; | |
1286 | |
1287 bufLen = 2 * SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len; | |
1288 if (bufLen <= sizeof buf) { | |
1289 hashBuf = buf; | |
1290 } else { | |
1291 hashBuf = PORT_Alloc(bufLen); | |
1292 if (!hashBuf) { | |
1293 return SECFailure; | |
1294 } | |
1295 } | |
1296 | |
1297 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); | |
1298 pBuf = hashBuf + SSL3_RANDOM_LENGTH; | |
1299 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); | |
1300 pBuf += SSL3_RANDOM_LENGTH; | |
1301 pBuf[0] = (PRUint8)(modulus.len >> 8); | |
1302 pBuf[1] = (PRUint8)(modulus.len); | |
1303 pBuf += 2; | |
1304 memcpy(pBuf, modulus.data, modulus.len); | |
1305 pBuf += modulus.len; | |
1306 pBuf[0] = (PRUint8)(publicExponent.len >> 8); | |
1307 pBuf[1] = (PRUint8)(publicExponent.len); | |
1308 pBuf += 2; | |
1309 memcpy(pBuf, publicExponent.data, publicExponent.len); | |
1310 pBuf += publicExponent.len; | |
1311 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); | |
1312 | |
1313 rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, | |
1314 bypassPKCS11); | |
1315 | |
1316 PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen)); | |
1317 if (hashAlg == ssl_hash_none) { | |
1318 PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result", | |
1319 hashes->u.s.md5, MD5_LENGTH)); | |
1320 PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result", | |
1321 hashes->u.s.sha, SHA1_LENGTH)); | |
1322 } else { | |
1323 PRINT_BUF(95, (NULL, "RSAkey hash: result", | |
1324 hashes->u.raw, hashes->len)); | |
1325 } | |
1326 | |
1327 if (hashBuf != buf && hashBuf != NULL) | |
1328 PORT_Free(hashBuf); | |
1329 return rv; | |
1330 } | |
1331 | |
1332 /* Caller must set hiLevel error code. */ | |
1333 /* Called from ssl3_HandleServerKeyExchange. */ | |
1334 static SECStatus | |
1335 ssl3_ComputeDHKeyHash(SSLHashType hashAlg, | |
1336 SECItem dh_p, SECItem dh_g, SECItem dh_Ys, | |
1337 SSL3Random *client_rand, SSL3Random *server_rand, | |
1338 SSL3Hashes *hashes, PRBool bypassPKCS11) | |
1339 { | |
1340 PRUint8 *hashBuf; | |
1341 PRUint8 *pBuf; | |
1342 SECStatus rv = SECSuccess; | |
1343 unsigned int bufLen; | |
1344 PRUint8 buf[2 * SSL3_RANDOM_LENGTH + 2 + 4096 / 8 + 2 + 4096 / 8]; | |
1345 | |
1346 bufLen = 2 * SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.le
n; | |
1347 if (bufLen <= sizeof buf) { | |
1348 hashBuf = buf; | |
1349 } else { | |
1350 hashBuf = PORT_Alloc(bufLen); | |
1351 if (!hashBuf) { | |
1352 return SECFailure; | |
1353 } | |
1354 } | |
1355 | |
1356 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); | |
1357 pBuf = hashBuf + SSL3_RANDOM_LENGTH; | |
1358 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); | |
1359 pBuf += SSL3_RANDOM_LENGTH; | |
1360 pBuf[0] = (PRUint8)(dh_p.len >> 8); | |
1361 pBuf[1] = (PRUint8)(dh_p.len); | |
1362 pBuf += 2; | |
1363 memcpy(pBuf, dh_p.data, dh_p.len); | |
1364 pBuf += dh_p.len; | |
1365 pBuf[0] = (PRUint8)(dh_g.len >> 8); | |
1366 pBuf[1] = (PRUint8)(dh_g.len); | |
1367 pBuf += 2; | |
1368 memcpy(pBuf, dh_g.data, dh_g.len); | |
1369 pBuf += dh_g.len; | |
1370 pBuf[0] = (PRUint8)(dh_Ys.len >> 8); | |
1371 pBuf[1] = (PRUint8)(dh_Ys.len); | |
1372 pBuf += 2; | |
1373 memcpy(pBuf, dh_Ys.data, dh_Ys.len); | |
1374 pBuf += dh_Ys.len; | |
1375 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); | |
1376 | |
1377 rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, | |
1378 bypassPKCS11); | |
1379 | |
1380 PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen)); | |
1381 if (hashAlg == ssl_hash_none) { | |
1382 PRINT_BUF(95, (NULL, "DHkey hash: MD5 result", | |
1383 hashes->u.s.md5, MD5_LENGTH)); | |
1384 PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result", | |
1385 hashes->u.s.sha, SHA1_LENGTH)); | |
1386 } else { | |
1387 PRINT_BUF(95, (NULL, "DHkey hash: result", | |
1388 hashes->u.raw, hashes->len)); | |
1389 } | |
1390 | |
1391 if (hashBuf != buf && hashBuf != NULL) | |
1392 PORT_Free(hashBuf); | |
1393 return rv; | |
1394 } | |
1395 | |
1396 void | |
1397 ssl3_BumpSequenceNumber(SSL3SequenceNumber *num) | |
1398 { | |
1399 num->low++; | |
1400 if (num->low == 0) | |
1401 num->high++; | |
1402 } | |
1403 | |
1404 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */ | |
1405 static void | |
1406 ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat) | |
1407 { | |
1408 if (mat->write_key != NULL) { | |
1409 PK11_FreeSymKey(mat->write_key); | |
1410 mat->write_key = NULL; | |
1411 } | |
1412 if (mat->write_mac_key != NULL) { | |
1413 PK11_FreeSymKey(mat->write_mac_key); | |
1414 mat->write_mac_key = NULL; | |
1415 } | |
1416 if (mat->write_mac_context != NULL) { | |
1417 PK11_DestroyContext(mat->write_mac_context, PR_TRUE); | |
1418 mat->write_mac_context = NULL; | |
1419 } | |
1420 } | |
1421 | |
1422 /* Called from ssl3_SendChangeCipherSpecs() and | |
1423 ** ssl3_HandleChangeCipherSpecs() | |
1424 ** ssl3_DestroySSL3Info | |
1425 ** Caller must hold SpecWriteLock. | |
1426 */ | |
1427 void | |
1428 ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName) | |
1429 { | |
1430 PRBool freeit = (PRBool)(!spec->bypassCiphers); | |
1431 /* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have s
s! */ | |
1432 if (spec->destroy) { | |
1433 spec->destroy(spec->encodeContext, freeit); | |
1434 spec->destroy(spec->decodeContext, freeit); | |
1435 spec->encodeContext = NULL; /* paranoia */ | |
1436 spec->decodeContext = NULL; | |
1437 } | |
1438 if (spec->destroyCompressContext && spec->compressContext) { | |
1439 spec->destroyCompressContext(spec->compressContext, 1); | |
1440 spec->compressContext = NULL; | |
1441 } | |
1442 if (spec->destroyDecompressContext && spec->decompressContext) { | |
1443 spec->destroyDecompressContext(spec->decompressContext, 1); | |
1444 spec->decompressContext = NULL; | |
1445 } | |
1446 if (freeSrvName && spec->srvVirtName.data) { | |
1447 SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE); | |
1448 } | |
1449 if (spec->master_secret != NULL) { | |
1450 PK11_FreeSymKey(spec->master_secret); | |
1451 spec->master_secret = NULL; | |
1452 } | |
1453 spec->msItem.data = NULL; | |
1454 spec->msItem.len = 0; | |
1455 ssl3_CleanupKeyMaterial(&spec->client); | |
1456 ssl3_CleanupKeyMaterial(&spec->server); | |
1457 spec->bypassCiphers = PR_FALSE; | |
1458 spec->destroy = NULL; | |
1459 spec->destroyCompressContext = NULL; | |
1460 spec->destroyDecompressContext = NULL; | |
1461 } | |
1462 | |
1463 /* Fill in the pending cipher spec with info from the selected ciphersuite. | |
1464 ** This is as much initialization as we can do without having key material. | |
1465 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello() | |
1466 ** Caller must hold the ssl3 handshake lock. | |
1467 ** Acquires & releases SpecWriteLock. | |
1468 */ | |
1469 SECStatus | |
1470 ssl3_SetupPendingCipherSpec(sslSocket *ss) | |
1471 { | |
1472 ssl3CipherSpec *pwSpec; | |
1473 ssl3CipherSpec *cwSpec; | |
1474 ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite; | |
1475 SSL3MACAlgorithm mac; | |
1476 SSL3BulkCipher cipher; | |
1477 SSL3KeyExchangeAlgorithm kea; | |
1478 const ssl3CipherSuiteDef *suite_def; | |
1479 PRBool isTLS; | |
1480 | |
1481 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
1482 | |
1483 ssl_GetSpecWriteLock(ss); /*******************************/ | |
1484 | |
1485 pwSpec = ss->ssl3.pwSpec; | |
1486 PORT_Assert(pwSpec == ss->ssl3.prSpec); | |
1487 | |
1488 /* This hack provides maximal interoperability with SSL 3 servers. */ | |
1489 cwSpec = ss->ssl3.cwSpec; | |
1490 if (cwSpec->mac_def->mac == mac_null) { | |
1491 /* SSL records are not being MACed. */ | |
1492 cwSpec->version = ss->version; | |
1493 } | |
1494 | |
1495 pwSpec->version = ss->version; | |
1496 isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
1497 | |
1498 SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x", | |
1499 SSL_GETPID(), ss->fd, suite)); | |
1500 | |
1501 suite_def = ssl_LookupCipherSuiteDef(suite); | |
1502 if (suite_def == NULL) { | |
1503 ssl_ReleaseSpecWriteLock(ss); | |
1504 return SECFailure; /* error code set by ssl_LookupCipherSuiteDef */ | |
1505 } | |
1506 | |
1507 if (IS_DTLS(ss)) { | |
1508 /* Double-check that we did not pick an RC4 suite */ | |
1509 PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) && | |
1510 (suite_def->bulk_cipher_alg != cipher_rc4_40) && | |
1511 (suite_def->bulk_cipher_alg != cipher_rc4_56)); | |
1512 } | |
1513 | |
1514 cipher = suite_def->bulk_cipher_alg; | |
1515 kea = suite_def->key_exchange_alg; | |
1516 mac = suite_def->mac_alg; | |
1517 if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS) | |
1518 mac += 2; | |
1519 | |
1520 ss->ssl3.hs.suite_def = suite_def; | |
1521 ss->ssl3.hs.kea_def = &kea_defs[kea]; | |
1522 PORT_Assert(ss->ssl3.hs.kea_def->kea == kea); | |
1523 | |
1524 pwSpec->cipher_def = &bulk_cipher_defs[cipher]; | |
1525 PORT_Assert(pwSpec->cipher_def->cipher == cipher); | |
1526 | |
1527 pwSpec->mac_def = &mac_defs[mac]; | |
1528 PORT_Assert(pwSpec->mac_def->mac == mac); | |
1529 | |
1530 ss->sec.keyBits = pwSpec->cipher_def->key_size * BPB; | |
1531 ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB; | |
1532 ss->sec.cipherType = cipher; | |
1533 | |
1534 pwSpec->encodeContext = NULL; | |
1535 pwSpec->decodeContext = NULL; | |
1536 | |
1537 pwSpec->mac_size = pwSpec->mac_def->mac_size; | |
1538 | |
1539 pwSpec->compression_method = ss->ssl3.hs.compression; | |
1540 pwSpec->compressContext = NULL; | |
1541 pwSpec->decompressContext = NULL; | |
1542 | |
1543 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { | |
1544 PORT_Assert(ss->ssl3.hs.kea_def->ephemeral); | |
1545 PORT_Assert(pwSpec->cipher_def->type == type_aead); | |
1546 } | |
1547 ssl_ReleaseSpecWriteLock(ss); /*******************************/ | |
1548 return SECSuccess; | |
1549 } | |
1550 | |
1551 #ifdef NSS_SSL_ENABLE_ZLIB | |
1552 #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream) | |
1553 | |
1554 static SECStatus | |
1555 ssl3_MapZlibError(int zlib_error) | |
1556 { | |
1557 switch (zlib_error) { | |
1558 case Z_OK: | |
1559 return SECSuccess; | |
1560 default: | |
1561 return SECFailure; | |
1562 } | |
1563 } | |
1564 | |
1565 static SECStatus | |
1566 ssl3_DeflateInit(void *void_context) | |
1567 { | |
1568 z_stream *context = void_context; | |
1569 context->zalloc = NULL; | |
1570 context->zfree = NULL; | |
1571 context->opaque = NULL; | |
1572 | |
1573 return ssl3_MapZlibError(deflateInit(context, Z_DEFAULT_COMPRESSION)); | |
1574 } | |
1575 | |
1576 static SECStatus | |
1577 ssl3_InflateInit(void *void_context) | |
1578 { | |
1579 z_stream *context = void_context; | |
1580 context->zalloc = NULL; | |
1581 context->zfree = NULL; | |
1582 context->opaque = NULL; | |
1583 context->next_in = NULL; | |
1584 context->avail_in = 0; | |
1585 | |
1586 return ssl3_MapZlibError(inflateInit(context)); | |
1587 } | |
1588 | |
1589 static SECStatus | |
1590 ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len, | |
1591 int maxout, const unsigned char *in, int inlen) | |
1592 { | |
1593 z_stream *context = void_context; | |
1594 | |
1595 if (!inlen) { | |
1596 *out_len = 0; | |
1597 return SECSuccess; | |
1598 } | |
1599 | |
1600 context->next_in = (unsigned char *)in; | |
1601 context->avail_in = inlen; | |
1602 context->next_out = out; | |
1603 context->avail_out = maxout; | |
1604 if (deflate(context, Z_SYNC_FLUSH) != Z_OK) { | |
1605 return SECFailure; | |
1606 } | |
1607 if (context->avail_out == 0) { | |
1608 /* We ran out of space! */ | |
1609 SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing", | |
1610 SSL_GETPID())); | |
1611 return SECFailure; | |
1612 } | |
1613 | |
1614 *out_len = maxout - context->avail_out; | |
1615 return SECSuccess; | |
1616 } | |
1617 | |
1618 static SECStatus | |
1619 ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len, | |
1620 int maxout, const unsigned char *in, int inlen) | |
1621 { | |
1622 z_stream *context = void_context; | |
1623 | |
1624 if (!inlen) { | |
1625 *out_len = 0; | |
1626 return SECSuccess; | |
1627 } | |
1628 | |
1629 context->next_in = (unsigned char *)in; | |
1630 context->avail_in = inlen; | |
1631 context->next_out = out; | |
1632 context->avail_out = maxout; | |
1633 if (inflate(context, Z_SYNC_FLUSH) != Z_OK) { | |
1634 PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE); | |
1635 return SECFailure; | |
1636 } | |
1637 | |
1638 *out_len = maxout - context->avail_out; | |
1639 return SECSuccess; | |
1640 } | |
1641 | |
1642 static SECStatus | |
1643 ssl3_DestroyCompressContext(void *void_context, PRBool unused) | |
1644 { | |
1645 deflateEnd(void_context); | |
1646 PORT_Free(void_context); | |
1647 return SECSuccess; | |
1648 } | |
1649 | |
1650 static SECStatus | |
1651 ssl3_DestroyDecompressContext(void *void_context, PRBool unused) | |
1652 { | |
1653 inflateEnd(void_context); | |
1654 PORT_Free(void_context); | |
1655 return SECSuccess; | |
1656 } | |
1657 | |
1658 #endif /* NSS_SSL_ENABLE_ZLIB */ | |
1659 | |
1660 /* Initialize the compression functions and contexts for the given | |
1661 * CipherSpec. */ | |
1662 static SECStatus | |
1663 ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec) | |
1664 { | |
1665 /* Setup the compression functions */ | |
1666 switch (pwSpec->compression_method) { | |
1667 case ssl_compression_null: | |
1668 pwSpec->compressor = NULL; | |
1669 pwSpec->decompressor = NULL; | |
1670 pwSpec->compressContext = NULL; | |
1671 pwSpec->decompressContext = NULL; | |
1672 pwSpec->destroyCompressContext = NULL; | |
1673 pwSpec->destroyDecompressContext = NULL; | |
1674 break; | |
1675 #ifdef NSS_SSL_ENABLE_ZLIB | |
1676 case ssl_compression_deflate: | |
1677 pwSpec->compressor = ssl3_DeflateCompress; | |
1678 pwSpec->decompressor = ssl3_DeflateDecompress; | |
1679 pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); | |
1680 pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); | |
1681 pwSpec->destroyCompressContext = ssl3_DestroyCompressContext; | |
1682 pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext; | |
1683 ssl3_DeflateInit(pwSpec->compressContext); | |
1684 ssl3_InflateInit(pwSpec->decompressContext); | |
1685 break; | |
1686 #endif /* NSS_SSL_ENABLE_ZLIB */ | |
1687 default: | |
1688 PORT_Assert(0); | |
1689 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
1690 return SECFailure; | |
1691 } | |
1692 | |
1693 return SECSuccess; | |
1694 } | |
1695 | |
1696 #ifndef NO_PKCS11_BYPASS | |
1697 /* Initialize encryption contexts for pending spec. | |
1698 * MAC contexts are set up when computing the mac, not here. | |
1699 * Master Secret already is derived in spec->msItem | |
1700 * Caller holds Spec write lock. | |
1701 */ | |
1702 static SECStatus | |
1703 ssl3_InitPendingContextsBypass(sslSocket *ss) | |
1704 { | |
1705 ssl3CipherSpec *pwSpec; | |
1706 const ssl3BulkCipherDef *cipher_def; | |
1707 void *serverContext = NULL; | |
1708 void *clientContext = NULL; | |
1709 BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL; | |
1710 int mode = 0; | |
1711 unsigned int optArg1 = 0; | |
1712 unsigned int optArg2 = 0; | |
1713 PRBool server_encrypts = ss->sec.isServer; | |
1714 SSLCipherAlgorithm calg; | |
1715 SECStatus rv; | |
1716 | |
1717 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
1718 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); | |
1719 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
1720 | |
1721 pwSpec = ss->ssl3.pwSpec; | |
1722 cipher_def = pwSpec->cipher_def; | |
1723 | |
1724 calg = cipher_def->calg; | |
1725 | |
1726 if (calg == ssl_calg_aes_gcm) { | |
1727 pwSpec->encode = NULL; | |
1728 pwSpec->decode = NULL; | |
1729 pwSpec->destroy = NULL; | |
1730 pwSpec->encodeContext = NULL; | |
1731 pwSpec->decodeContext = NULL; | |
1732 pwSpec->aead = ssl3_AESGCMBypass; | |
1733 ssl3_InitCompressionContext(pwSpec); | |
1734 return SECSuccess; | |
1735 } | |
1736 | |
1737 serverContext = pwSpec->server.cipher_context; | |
1738 clientContext = pwSpec->client.cipher_context; | |
1739 | |
1740 switch (calg) { | |
1741 case ssl_calg_null: | |
1742 pwSpec->encode = Null_Cipher; | |
1743 pwSpec->decode = Null_Cipher; | |
1744 pwSpec->destroy = NULL; | |
1745 goto success; | |
1746 | |
1747 case ssl_calg_rc4: | |
1748 initFn = (BLapiInitContextFunc)RC4_InitContext; | |
1749 pwSpec->encode = (SSLCipher)RC4_Encrypt; | |
1750 pwSpec->decode = (SSLCipher)RC4_Decrypt; | |
1751 pwSpec->destroy = (SSLDestroy)RC4_DestroyContext; | |
1752 break; | |
1753 case ssl_calg_rc2: | |
1754 initFn = (BLapiInitContextFunc)RC2_InitContext; | |
1755 mode = NSS_RC2_CBC; | |
1756 optArg1 = cipher_def->key_size; | |
1757 pwSpec->encode = (SSLCipher)RC2_Encrypt; | |
1758 pwSpec->decode = (SSLCipher)RC2_Decrypt; | |
1759 pwSpec->destroy = (SSLDestroy)RC2_DestroyContext; | |
1760 break; | |
1761 case ssl_calg_des: | |
1762 initFn = (BLapiInitContextFunc)DES_InitContext; | |
1763 mode = NSS_DES_CBC; | |
1764 optArg1 = server_encrypts; | |
1765 pwSpec->encode = (SSLCipher)DES_Encrypt; | |
1766 pwSpec->decode = (SSLCipher)DES_Decrypt; | |
1767 pwSpec->destroy = (SSLDestroy)DES_DestroyContext; | |
1768 break; | |
1769 case ssl_calg_3des: | |
1770 initFn = (BLapiInitContextFunc)DES_InitContext; | |
1771 mode = NSS_DES_EDE3_CBC; | |
1772 optArg1 = server_encrypts; | |
1773 pwSpec->encode = (SSLCipher)DES_Encrypt; | |
1774 pwSpec->decode = (SSLCipher)DES_Decrypt; | |
1775 pwSpec->destroy = (SSLDestroy)DES_DestroyContext; | |
1776 break; | |
1777 case ssl_calg_aes: | |
1778 initFn = (BLapiInitContextFunc)AES_InitContext; | |
1779 mode = NSS_AES_CBC; | |
1780 optArg1 = server_encrypts; | |
1781 optArg2 = AES_BLOCK_SIZE; | |
1782 pwSpec->encode = (SSLCipher)AES_Encrypt; | |
1783 pwSpec->decode = (SSLCipher)AES_Decrypt; | |
1784 pwSpec->destroy = (SSLDestroy)AES_DestroyContext; | |
1785 break; | |
1786 | |
1787 case ssl_calg_camellia: | |
1788 initFn = (BLapiInitContextFunc)Camellia_InitContext; | |
1789 mode = NSS_CAMELLIA_CBC; | |
1790 optArg1 = server_encrypts; | |
1791 optArg2 = CAMELLIA_BLOCK_SIZE; | |
1792 pwSpec->encode = (SSLCipher)Camellia_Encrypt; | |
1793 pwSpec->decode = (SSLCipher)Camellia_Decrypt; | |
1794 pwSpec->destroy = (SSLDestroy)Camellia_DestroyContext; | |
1795 break; | |
1796 | |
1797 case ssl_calg_seed: | |
1798 initFn = (BLapiInitContextFunc)SEED_InitContext; | |
1799 mode = NSS_SEED_CBC; | |
1800 optArg1 = server_encrypts; | |
1801 optArg2 = SEED_BLOCK_SIZE; | |
1802 pwSpec->encode = (SSLCipher)SEED_Encrypt; | |
1803 pwSpec->decode = (SSLCipher)SEED_Decrypt; | |
1804 pwSpec->destroy = (SSLDestroy)SEED_DestroyContext; | |
1805 break; | |
1806 | |
1807 case ssl_calg_idea: | |
1808 case ssl_calg_fortezza: | |
1809 default: | |
1810 PORT_Assert(0); | |
1811 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
1812 goto bail_out; | |
1813 } | |
1814 rv = (*initFn)(serverContext, | |
1815 pwSpec->server.write_key_item.data, | |
1816 pwSpec->server.write_key_item.len, | |
1817 pwSpec->server.write_iv_item.data, | |
1818 mode, optArg1, optArg2); | |
1819 if (rv != SECSuccess) { | |
1820 PORT_Assert(0); | |
1821 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
1822 goto bail_out; | |
1823 } | |
1824 | |
1825 switch (calg) { | |
1826 case ssl_calg_des: | |
1827 case ssl_calg_3des: | |
1828 case ssl_calg_aes: | |
1829 case ssl_calg_camellia: | |
1830 case ssl_calg_seed: | |
1831 /* For block ciphers, if the server is encrypting, then the client | |
1832 * is decrypting, and vice versa. | |
1833 */ | |
1834 optArg1 = !optArg1; | |
1835 break; | |
1836 /* kill warnings. */ | |
1837 case ssl_calg_null: | |
1838 case ssl_calg_rc4: | |
1839 case ssl_calg_rc2: | |
1840 case ssl_calg_idea: | |
1841 case ssl_calg_fortezza: | |
1842 case ssl_calg_aes_gcm: | |
1843 case ssl_calg_chacha20: | |
1844 break; | |
1845 } | |
1846 | |
1847 rv = (*initFn)(clientContext, | |
1848 pwSpec->client.write_key_item.data, | |
1849 pwSpec->client.write_key_item.len, | |
1850 pwSpec->client.write_iv_item.data, | |
1851 mode, optArg1, optArg2); | |
1852 if (rv != SECSuccess) { | |
1853 PORT_Assert(0); | |
1854 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
1855 goto bail_out; | |
1856 } | |
1857 | |
1858 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; | |
1859 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext; | |
1860 | |
1861 ssl3_InitCompressionContext(pwSpec); | |
1862 | |
1863 success: | |
1864 return SECSuccess; | |
1865 | |
1866 bail_out: | |
1867 return SECFailure; | |
1868 } | |
1869 #endif | |
1870 | |
1871 /* This function should probably be moved to pk11wrap and be named | |
1872 * PK11_ParamFromIVAndEffectiveKeyBits | |
1873 */ | |
1874 static SECItem * | |
1875 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits) | |
1876 { | |
1877 SECItem *param = PK11_ParamFromIV(mtype, iv); | |
1878 if (param && param->data && param->len >= sizeof(CK_RC2_PARAMS)) { | |
1879 switch (mtype) { | |
1880 case CKM_RC2_KEY_GEN: | |
1881 case CKM_RC2_ECB: | |
1882 case CKM_RC2_CBC: | |
1883 case CKM_RC2_MAC: | |
1884 case CKM_RC2_MAC_GENERAL: | |
1885 case CKM_RC2_CBC_PAD: | |
1886 *(CK_RC2_PARAMS *)param->data = ulEffectiveBits; | |
1887 default: | |
1888 break; | |
1889 } | |
1890 } | |
1891 return param; | |
1892 } | |
1893 | |
1894 /* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data | |
1895 * which is included in the MAC or AEAD additional data) to |out| and returns | |
1896 * its length. See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the | |
1897 * definition of the AEAD additional data. | |
1898 * | |
1899 * TLS pseudo-header includes the record's version field, SSL's doesn't. Which | |
1900 * pseudo-header defintiion to use should be decided based on the version of | |
1901 * the protocol that was negotiated when the cipher spec became current, NOT | |
1902 * based on the version value in the record itself, and the decision is passed | |
1903 * to this function as the |includesVersion| argument. But, the |version| | |
1904 * argument should be the record's version value. | |
1905 */ | |
1906 static unsigned int | |
1907 ssl3_BuildRecordPseudoHeader(unsigned char *out, | |
1908 SSL3SequenceNumber seq_num, | |
1909 SSL3ContentType type, | |
1910 PRBool includesVersion, | |
1911 SSL3ProtocolVersion version, | |
1912 PRBool isDTLS, | |
1913 int length) | |
1914 { | |
1915 out[0] = (unsigned char)(seq_num.high >> 24); | |
1916 out[1] = (unsigned char)(seq_num.high >> 16); | |
1917 out[2] = (unsigned char)(seq_num.high >> 8); | |
1918 out[3] = (unsigned char)(seq_num.high >> 0); | |
1919 out[4] = (unsigned char)(seq_num.low >> 24); | |
1920 out[5] = (unsigned char)(seq_num.low >> 16); | |
1921 out[6] = (unsigned char)(seq_num.low >> 8); | |
1922 out[7] = (unsigned char)(seq_num.low >> 0); | |
1923 out[8] = type; | |
1924 | |
1925 /* SSL3 MAC doesn't include the record's version field. */ | |
1926 if (!includesVersion) { | |
1927 out[9] = MSB(length); | |
1928 out[10] = LSB(length); | |
1929 return 11; | |
1930 } | |
1931 | |
1932 /* TLS MAC and AEAD additional data include version. */ | |
1933 if (isDTLS) { | |
1934 SSL3ProtocolVersion dtls_version; | |
1935 | |
1936 dtls_version = dtls_TLSVersionToDTLSVersion(version); | |
1937 out[9] = MSB(dtls_version); | |
1938 out[10] = LSB(dtls_version); | |
1939 } else { | |
1940 out[9] = MSB(version); | |
1941 out[10] = LSB(version); | |
1942 } | |
1943 out[11] = MSB(length); | |
1944 out[12] = LSB(length); | |
1945 return 13; | |
1946 } | |
1947 | |
1948 static SECStatus | |
1949 ssl3_AESGCM(ssl3KeyMaterial *keys, | |
1950 PRBool doDecrypt, | |
1951 unsigned char *out, | |
1952 int *outlen, | |
1953 int maxout, | |
1954 const unsigned char *in, | |
1955 int inlen, | |
1956 const unsigned char *additionalData, | |
1957 int additionalDataLen) | |
1958 { | |
1959 SECItem param; | |
1960 SECStatus rv = SECFailure; | |
1961 unsigned char nonce[12]; | |
1962 unsigned int uOutLen; | |
1963 CK_GCM_PARAMS gcmParams; | |
1964 | |
1965 const int tagSize = bulk_cipher_defs[cipher_aes_128_gcm].tag_size; | |
1966 const int explicitNonceLen = | |
1967 bulk_cipher_defs[cipher_aes_128_gcm].explicit_nonce_size; | |
1968 | |
1969 /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the | |
1970 * nonce is formed. */ | |
1971 memcpy(nonce, keys->write_iv, 4); | |
1972 if (doDecrypt) { | |
1973 memcpy(nonce + 4, in, explicitNonceLen); | |
1974 in += explicitNonceLen; | |
1975 inlen -= explicitNonceLen; | |
1976 *outlen = 0; | |
1977 } else { | |
1978 if (maxout < explicitNonceLen) { | |
1979 PORT_SetError(SEC_ERROR_INPUT_LEN); | |
1980 return SECFailure; | |
1981 } | |
1982 /* Use the 64-bit sequence number as the explicit nonce. */ | |
1983 memcpy(nonce + 4, additionalData, explicitNonceLen); | |
1984 memcpy(out, additionalData, explicitNonceLen); | |
1985 out += explicitNonceLen; | |
1986 maxout -= explicitNonceLen; | |
1987 *outlen = explicitNonceLen; | |
1988 } | |
1989 | |
1990 param.type = siBuffer; | |
1991 param.data = (unsigned char *)&gcmParams; | |
1992 param.len = sizeof(gcmParams); | |
1993 gcmParams.pIv = nonce; | |
1994 gcmParams.ulIvLen = sizeof(nonce); | |
1995 gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ | |
1996 gcmParams.ulAADLen = additionalDataLen; | |
1997 gcmParams.ulTagBits = tagSize * 8; | |
1998 | |
1999 if (doDecrypt) { | |
2000 rv = PK11_Decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, | |
2001 maxout, in, inlen); | |
2002 } else { | |
2003 rv = PK11_Encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, | |
2004 maxout, in, inlen); | |
2005 } | |
2006 *outlen += (int)uOutLen; | |
2007 | |
2008 return rv; | |
2009 } | |
2010 | |
2011 #ifndef NO_PKCS11_BYPASS | |
2012 static SECStatus | |
2013 ssl3_AESGCMBypass(ssl3KeyMaterial *keys, | |
2014 PRBool doDecrypt, | |
2015 unsigned char *out, | |
2016 int *outlen, | |
2017 int maxout, | |
2018 const unsigned char *in, | |
2019 int inlen, | |
2020 const unsigned char *additionalData, | |
2021 int additionalDataLen) | |
2022 { | |
2023 SECStatus rv = SECFailure; | |
2024 unsigned char nonce[12]; | |
2025 unsigned int uOutLen; | |
2026 AESContext *cx; | |
2027 CK_GCM_PARAMS gcmParams; | |
2028 | |
2029 const int tagSize = bulk_cipher_defs[cipher_aes_128_gcm].tag_size; | |
2030 const int explicitNonceLen = | |
2031 bulk_cipher_defs[cipher_aes_128_gcm].explicit_nonce_size; | |
2032 | |
2033 /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the | |
2034 * nonce is formed. */ | |
2035 PORT_Assert(keys->write_iv_item.len == 4); | |
2036 if (keys->write_iv_item.len != 4) { | |
2037 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
2038 return SECFailure; | |
2039 } | |
2040 memcpy(nonce, keys->write_iv_item.data, 4); | |
2041 if (doDecrypt) { | |
2042 memcpy(nonce + 4, in, explicitNonceLen); | |
2043 in += explicitNonceLen; | |
2044 inlen -= explicitNonceLen; | |
2045 *outlen = 0; | |
2046 } else { | |
2047 if (maxout < explicitNonceLen) { | |
2048 PORT_SetError(SEC_ERROR_INPUT_LEN); | |
2049 return SECFailure; | |
2050 } | |
2051 /* Use the 64-bit sequence number as the explicit nonce. */ | |
2052 memcpy(nonce + 4, additionalData, explicitNonceLen); | |
2053 memcpy(out, additionalData, explicitNonceLen); | |
2054 out += explicitNonceLen; | |
2055 maxout -= explicitNonceLen; | |
2056 *outlen = explicitNonceLen; | |
2057 } | |
2058 | |
2059 gcmParams.pIv = nonce; | |
2060 gcmParams.ulIvLen = sizeof(nonce); | |
2061 gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ | |
2062 gcmParams.ulAADLen = additionalDataLen; | |
2063 gcmParams.ulTagBits = tagSize * 8; | |
2064 | |
2065 cx = (AESContext *)keys->cipher_context; | |
2066 rv = AES_InitContext(cx, keys->write_key_item.data, | |
2067 keys->write_key_item.len, | |
2068 (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt, | |
2069 AES_BLOCK_SIZE); | |
2070 if (rv != SECSuccess) { | |
2071 return rv; | |
2072 } | |
2073 if (doDecrypt) { | |
2074 rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen); | |
2075 } else { | |
2076 rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen); | |
2077 } | |
2078 AES_DestroyContext(cx, PR_FALSE); | |
2079 *outlen += (int)uOutLen; | |
2080 | |
2081 return rv; | |
2082 } | |
2083 #endif | |
2084 | |
2085 static SECStatus | |
2086 ssl3_ChaCha20Poly1305(ssl3KeyMaterial *keys, PRBool doDecrypt, | |
2087 unsigned char *out, int *outlen, int maxout, | |
2088 const unsigned char *in, int inlen, | |
2089 const unsigned char *additionalData, | |
2090 int additionalDataLen) | |
2091 { | |
2092 size_t i; | |
2093 SECItem param; | |
2094 SECStatus rv = SECFailure; | |
2095 unsigned int uOutLen; | |
2096 unsigned char nonce[12]; | |
2097 CK_NSS_AEAD_PARAMS aeadParams; | |
2098 | |
2099 const int tagSize = bulk_cipher_defs[cipher_chacha20].tag_size; | |
2100 | |
2101 /* See | |
2102 * https://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305-04#section-2 | |
2103 * for details of how the nonce is formed. */ | |
2104 PORT_Memcpy(nonce, keys->write_iv, 12); | |
2105 | |
2106 /* XOR the last 8 bytes of the IV with the sequence number. */ | |
2107 PORT_Assert(additionalDataLen >= 8); | |
2108 for (i = 0; i < 8; ++i) { | |
2109 nonce[4 + i] ^= additionalData[i]; | |
2110 } | |
2111 | |
2112 param.type = siBuffer; | |
2113 param.len = sizeof(aeadParams); | |
2114 param.data = (unsigned char *)&aeadParams; | |
2115 memset(&aeadParams, 0, sizeof(aeadParams)); | |
2116 aeadParams.pNonce = nonce; | |
2117 aeadParams.ulNonceLen = sizeof(nonce); | |
2118 aeadParams.pAAD = (unsigned char *)additionalData; | |
2119 aeadParams.ulAADLen = additionalDataLen; | |
2120 aeadParams.ulTagLen = tagSize; | |
2121 | |
2122 if (doDecrypt) { | |
2123 rv = PK11_Decrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, ¶m, | |
2124 out, &uOutLen, maxout, in, inlen); | |
2125 } else { | |
2126 rv = PK11_Encrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, ¶m, | |
2127 out, &uOutLen, maxout, in, inlen); | |
2128 } | |
2129 *outlen = (int)uOutLen; | |
2130 | |
2131 return rv; | |
2132 } | |
2133 | |
2134 /* Initialize encryption and MAC contexts for pending spec. | |
2135 * Master Secret already is derived. | |
2136 * Caller holds Spec write lock. | |
2137 */ | |
2138 static SECStatus | |
2139 ssl3_InitPendingContextsPKCS11(sslSocket *ss) | |
2140 { | |
2141 ssl3CipherSpec *pwSpec; | |
2142 const ssl3BulkCipherDef *cipher_def; | |
2143 PK11Context *serverContext = NULL; | |
2144 PK11Context *clientContext = NULL; | |
2145 SECItem *param; | |
2146 CK_MECHANISM_TYPE mechanism; | |
2147 CK_MECHANISM_TYPE mac_mech; | |
2148 CK_ULONG macLength; | |
2149 CK_ULONG effKeyBits; | |
2150 SECItem iv; | |
2151 SECItem mac_param; | |
2152 SSLCipherAlgorithm calg; | |
2153 | |
2154 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
2155 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); | |
2156 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
2157 | |
2158 pwSpec = ss->ssl3.pwSpec; | |
2159 cipher_def = pwSpec->cipher_def; | |
2160 macLength = pwSpec->mac_size; | |
2161 calg = cipher_def->calg; | |
2162 PORT_Assert(alg2Mech[calg].calg == calg); | |
2163 | |
2164 pwSpec->client.write_mac_context = NULL; | |
2165 pwSpec->server.write_mac_context = NULL; | |
2166 | |
2167 if (cipher_def->type == type_aead) { | |
2168 pwSpec->encode = NULL; | |
2169 pwSpec->decode = NULL; | |
2170 pwSpec->destroy = NULL; | |
2171 pwSpec->encodeContext = NULL; | |
2172 pwSpec->decodeContext = NULL; | |
2173 switch (calg) { | |
2174 case calg_aes_gcm: | |
2175 pwSpec->aead = ssl3_AESGCM; | |
2176 break; | |
2177 case calg_chacha20: | |
2178 pwSpec->aead = ssl3_ChaCha20Poly1305; | |
2179 break; | |
2180 default: | |
2181 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
2182 return SECFailure; | |
2183 } | |
2184 return SECSuccess; | |
2185 } | |
2186 | |
2187 /* | |
2188 ** Now setup the MAC contexts, | |
2189 ** crypto contexts are setup below. | |
2190 */ | |
2191 | |
2192 mac_mech = pwSpec->mac_def->mmech; | |
2193 mac_param.data = (unsigned char *)&macLength; | |
2194 mac_param.len = sizeof(macLength); | |
2195 mac_param.type = 0; | |
2196 | |
2197 pwSpec->client.write_mac_context = PK11_CreateContextBySymKey( | |
2198 mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param); | |
2199 if (pwSpec->client.write_mac_context == NULL) { | |
2200 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); | |
2201 goto fail; | |
2202 } | |
2203 pwSpec->server.write_mac_context = PK11_CreateContextBySymKey( | |
2204 mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param); | |
2205 if (pwSpec->server.write_mac_context == NULL) { | |
2206 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); | |
2207 goto fail; | |
2208 } | |
2209 | |
2210 /* | |
2211 ** Now setup the crypto contexts. | |
2212 */ | |
2213 | |
2214 if (calg == calg_null) { | |
2215 pwSpec->encode = Null_Cipher; | |
2216 pwSpec->decode = Null_Cipher; | |
2217 pwSpec->destroy = NULL; | |
2218 return SECSuccess; | |
2219 } | |
2220 mechanism = ssl3_Alg2Mech(calg); | |
2221 effKeyBits = cipher_def->key_size * BPB; | |
2222 | |
2223 /* | |
2224 * build the server context | |
2225 */ | |
2226 iv.data = pwSpec->server.write_iv; | |
2227 iv.len = cipher_def->iv_size; | |
2228 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); | |
2229 if (param == NULL) { | |
2230 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); | |
2231 goto fail; | |
2232 } | |
2233 serverContext = PK11_CreateContextBySymKey(mechanism, | |
2234 (ss->sec.isServer ? CKA_ENCRYPT | |
2235 : CKA_DECRYPT), | |
2236 pwSpec->server.write_key, param); | |
2237 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); | |
2238 if (iv.data) | |
2239 PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len); | |
2240 SECITEM_FreeItem(param, PR_TRUE); | |
2241 if (serverContext == NULL) { | |
2242 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); | |
2243 goto fail; | |
2244 } | |
2245 | |
2246 /* | |
2247 * build the client context | |
2248 */ | |
2249 iv.data = pwSpec->client.write_iv; | |
2250 iv.len = cipher_def->iv_size; | |
2251 | |
2252 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); | |
2253 if (param == NULL) { | |
2254 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); | |
2255 goto fail; | |
2256 } | |
2257 clientContext = PK11_CreateContextBySymKey(mechanism, | |
2258 (ss->sec.isServer ? CKA_DECRYPT | |
2259 : CKA_ENCRYPT), | |
2260 pwSpec->client.write_key, param); | |
2261 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); | |
2262 if (iv.data) | |
2263 PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len); | |
2264 SECITEM_FreeItem(param, PR_TRUE); | |
2265 if (clientContext == NULL) { | |
2266 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); | |
2267 goto fail; | |
2268 } | |
2269 pwSpec->encode = (SSLCipher)PK11_CipherOp; | |
2270 pwSpec->decode = (SSLCipher)PK11_CipherOp; | |
2271 pwSpec->destroy = (SSLDestroy)PK11_DestroyContext; | |
2272 | |
2273 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; | |
2274 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext; | |
2275 | |
2276 serverContext = NULL; | |
2277 clientContext = NULL; | |
2278 | |
2279 ssl3_InitCompressionContext(pwSpec); | |
2280 | |
2281 return SECSuccess; | |
2282 | |
2283 fail: | |
2284 if (serverContext != NULL) | |
2285 PK11_DestroyContext(serverContext, PR_TRUE); | |
2286 if (clientContext != NULL) | |
2287 PK11_DestroyContext(clientContext, PR_TRUE); | |
2288 if (pwSpec->client.write_mac_context != NULL) { | |
2289 PK11_DestroyContext(pwSpec->client.write_mac_context, PR_TRUE); | |
2290 pwSpec->client.write_mac_context = NULL; | |
2291 } | |
2292 if (pwSpec->server.write_mac_context != NULL) { | |
2293 PK11_DestroyContext(pwSpec->server.write_mac_context, PR_TRUE); | |
2294 pwSpec->server.write_mac_context = NULL; | |
2295 } | |
2296 | |
2297 return SECFailure; | |
2298 } | |
2299 | |
2300 #ifndef NO_PKCS11_BYPASS | |
2301 /* Returns whether we can bypass PKCS#11 for a given cipher algorithm. | |
2302 * | |
2303 * We do not support PKCS#11 bypass for ChaCha20/Poly1305. | |
2304 */ | |
2305 static PRBool | |
2306 ssl3_CanBypassCipher(SSLCipherAlgorithm calg) | |
2307 { | |
2308 switch (calg) { | |
2309 case calg_chacha20: | |
2310 return PR_FALSE; | |
2311 default: | |
2312 return PR_TRUE; | |
2313 } | |
2314 } | |
2315 #endif | |
2316 | |
2317 /* Complete the initialization of all keys, ciphers, MACs and their contexts | |
2318 * for the pending Cipher Spec. | |
2319 * Called from: ssl3_SendClientKeyExchange (for Full handshake) | |
2320 * ssl3_HandleRSAClientKeyExchange (for Full handshake) | |
2321 * ssl3_HandleServerHello (for session restart) | |
2322 * ssl3_HandleClientHello (for session restart) | |
2323 * Sets error code, but caller probably should override to disambiguate. | |
2324 * NULL pms means re-use old master_secret. | |
2325 * | |
2326 * This code is common to the bypass and PKCS11 execution paths. For | |
2327 * the bypass case, pms is NULL. If the old master secret is reused, | |
2328 * pms is NULL and the master secret is already in either | |
2329 * pwSpec->msItem.len (the bypass case) or pwSpec->master_secret. | |
2330 * | |
2331 * For the bypass case, pms is NULL. | |
2332 */ | |
2333 SECStatus | |
2334 ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms) | |
2335 { | |
2336 ssl3CipherSpec *pwSpec; | |
2337 ssl3CipherSpec *cwSpec; | |
2338 SECStatus rv; | |
2339 | |
2340 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
2341 | |
2342 ssl_GetSpecWriteLock(ss); /**************************************/ | |
2343 | |
2344 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
2345 | |
2346 pwSpec = ss->ssl3.pwSpec; | |
2347 cwSpec = ss->ssl3.cwSpec; | |
2348 | |
2349 if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) { | |
2350 rv = ssl3_DeriveMasterSecret(ss, pms); | |
2351 if (rv != SECSuccess) { | |
2352 goto done; /* err code set by ssl3_DeriveMasterSecret */ | |
2353 } | |
2354 } | |
2355 #ifndef NO_PKCS11_BYPASS | |
2356 if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data && | |
2357 ssl3_CanBypassCipher(ss->ssl3.pwSpec->cipher_def->calg)) { | |
2358 /* Double Bypass succeeded in extracting the master_secret */ | |
2359 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; | |
2360 PRBool isTLS = (PRBool)(kea_def->tls_keygen || | |
2361 (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); | |
2362 pwSpec->bypassCiphers = PR_TRUE; | |
2363 rv = ssl3_KeyAndMacDeriveBypass(pwSpec, | |
2364 (const unsigned char *)&ss->ssl3.hs.clie
nt_random, | |
2365 (const unsigned char *)&ss->ssl3.hs.serv
er_random, | |
2366 isTLS, | |
2367 (PRBool)(kea_def->is_limited)); | |
2368 if (rv == SECSuccess) { | |
2369 rv = ssl3_InitPendingContextsBypass(ss); | |
2370 } | |
2371 } else | |
2372 #endif | |
2373 if (pwSpec->master_secret) { | |
2374 rv = ssl3_DeriveConnectionKeysPKCS11(ss); | |
2375 if (rv == SECSuccess) { | |
2376 rv = ssl3_InitPendingContextsPKCS11(ss); | |
2377 } | |
2378 } else { | |
2379 PORT_Assert(pwSpec->master_secret); | |
2380 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
2381 rv = SECFailure; | |
2382 } | |
2383 if (rv != SECSuccess) { | |
2384 goto done; | |
2385 } | |
2386 | |
2387 /* Generic behaviors -- common to all crypto methods */ | |
2388 if (!IS_DTLS(ss)) { | |
2389 pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0; | |
2390 } else { | |
2391 if (cwSpec->epoch == PR_UINT16_MAX) { | |
2392 /* The problem here is that we have rehandshaked too many | |
2393 * times (you are not allowed to wrap the epoch). The | |
2394 * spec says you should be discarding the connection | |
2395 * and start over, so not much we can do here. */ | |
2396 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
2397 rv = SECFailure; | |
2398 goto done; | |
2399 } | |
2400 /* The sequence number has the high 16 bits as the epoch. */ | |
2401 pwSpec->epoch = cwSpec->epoch + 1; | |
2402 pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = | |
2403 pwSpec->epoch << 16; | |
2404 | |
2405 dtls_InitRecvdRecords(&pwSpec->recvdRecords); | |
2406 } | |
2407 pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0; | |
2408 | |
2409 done: | |
2410 ssl_ReleaseSpecWriteLock(ss); /******************************/ | |
2411 if (rv != SECSuccess) | |
2412 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); | |
2413 return rv; | |
2414 } | |
2415 | |
2416 /* | |
2417 * 60 bytes is 3 times the maximum length MAC size that is supported. | |
2418 */ | |
2419 static const unsigned char mac_pad_1[60] = { | |
2420 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2421 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2422 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2423 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2424 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2425 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2426 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, | |
2427 0x36, 0x36, 0x36, 0x36 | |
2428 }; | |
2429 static const unsigned char mac_pad_2[60] = { | |
2430 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2431 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2432 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2433 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2434 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2435 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2436 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, | |
2437 0x5c, 0x5c, 0x5c, 0x5c | |
2438 }; | |
2439 | |
2440 /* Called from: ssl3_SendRecord() | |
2441 ** Caller must already hold the SpecReadLock. (wish we could assert that!) | |
2442 */ | |
2443 static SECStatus | |
2444 ssl3_ComputeRecordMAC( | |
2445 ssl3CipherSpec *spec, | |
2446 PRBool useServerMacKey, | |
2447 const unsigned char *header, | |
2448 unsigned int headerLen, | |
2449 const SSL3Opaque *input, | |
2450 int inputLength, | |
2451 unsigned char *outbuf, | |
2452 unsigned int *outLength) | |
2453 { | |
2454 const ssl3MACDef *mac_def; | |
2455 SECStatus rv; | |
2456 | |
2457 PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen)); | |
2458 PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength)); | |
2459 | |
2460 mac_def = spec->mac_def; | |
2461 if (mac_def->mac == mac_null) { | |
2462 *outLength = 0; | |
2463 return SECSuccess; | |
2464 } | |
2465 #ifndef NO_PKCS11_BYPASS | |
2466 if (spec->bypassCiphers) { | |
2467 /* bypass version */ | |
2468 const SECHashObject *hashObj = NULL; | |
2469 unsigned int pad_bytes = 0; | |
2470 PRUint64 write_mac_context[MAX_MAC_CONTEXT_LLONGS]; | |
2471 | |
2472 switch (mac_def->mac) { | |
2473 case ssl_mac_null: | |
2474 *outLength = 0; | |
2475 return SECSuccess; | |
2476 case ssl_mac_md5: | |
2477 pad_bytes = 48; | |
2478 hashObj = HASH_GetRawHashObject(HASH_AlgMD5); | |
2479 break; | |
2480 case ssl_mac_sha: | |
2481 pad_bytes = 40; | |
2482 hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); | |
2483 break; | |
2484 case ssl_hmac_md5: /* used with TLS */ | |
2485 hashObj = HASH_GetRawHashObject(HASH_AlgMD5); | |
2486 break; | |
2487 case ssl_hmac_sha: /* used with TLS */ | |
2488 hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); | |
2489 break; | |
2490 case ssl_hmac_sha256: /* used with TLS */ | |
2491 hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); | |
2492 break; | |
2493 default: | |
2494 break; | |
2495 } | |
2496 if (!hashObj) { | |
2497 PORT_Assert(0); | |
2498 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
2499 return SECFailure; | |
2500 } | |
2501 | |
2502 if (spec->version <= SSL_LIBRARY_VERSION_3_0) { | |
2503 unsigned int tempLen; | |
2504 unsigned char temp[MAX_MAC_LENGTH]; | |
2505 | |
2506 /* compute "inner" part of SSL3 MAC */ | |
2507 hashObj->begin(write_mac_context); | |
2508 if (useServerMacKey) | |
2509 hashObj->update(write_mac_context, | |
2510 spec->server.write_mac_key_item.data, | |
2511 spec->server.write_mac_key_item.len); | |
2512 else | |
2513 hashObj->update(write_mac_context, | |
2514 spec->client.write_mac_key_item.data, | |
2515 spec->client.write_mac_key_item.len); | |
2516 hashObj->update(write_mac_context, mac_pad_1, pad_bytes); | |
2517 hashObj->update(write_mac_context, header, headerLen); | |
2518 hashObj->update(write_mac_context, input, inputLength); | |
2519 hashObj->end(write_mac_context, temp, &tempLen, sizeof temp); | |
2520 | |
2521 /* compute "outer" part of SSL3 MAC */ | |
2522 hashObj->begin(write_mac_context); | |
2523 if (useServerMacKey) | |
2524 hashObj->update(write_mac_context, | |
2525 spec->server.write_mac_key_item.data, | |
2526 spec->server.write_mac_key_item.len); | |
2527 else | |
2528 hashObj->update(write_mac_context, | |
2529 spec->client.write_mac_key_item.data, | |
2530 spec->client.write_mac_key_item.len); | |
2531 hashObj->update(write_mac_context, mac_pad_2, pad_bytes); | |
2532 hashObj->update(write_mac_context, temp, tempLen); | |
2533 hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size); | |
2534 rv = SECSuccess; | |
2535 } else { /* is TLS */ | |
2536 #define cx ((HMACContext *)write_mac_context) | |
2537 if (useServerMacKey) { | |
2538 rv = HMAC_Init(cx, hashObj, | |
2539 spec->server.write_mac_key_item.data, | |
2540 spec->server.write_mac_key_item.len, PR_FALSE); | |
2541 } else { | |
2542 rv = HMAC_Init(cx, hashObj, | |
2543 spec->client.write_mac_key_item.data, | |
2544 spec->client.write_mac_key_item.len, PR_FALSE); | |
2545 } | |
2546 if (rv == SECSuccess) { | |
2547 HMAC_Begin(cx); | |
2548 HMAC_Update(cx, header, headerLen); | |
2549 HMAC_Update(cx, input, inputLength); | |
2550 rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size); | |
2551 HMAC_Destroy(cx, PR_FALSE); | |
2552 } | |
2553 #undef cx | |
2554 } | |
2555 } else | |
2556 #endif | |
2557 { | |
2558 PK11Context *mac_context = | |
2559 (useServerMacKey ? spec->server.write_mac_context | |
2560 : spec->client.write_mac_context); | |
2561 rv = PK11_DigestBegin(mac_context); | |
2562 rv |= PK11_DigestOp(mac_context, header, headerLen); | |
2563 rv |= PK11_DigestOp(mac_context, input, inputLength); | |
2564 rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size); | |
2565 } | |
2566 | |
2567 PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size); | |
2568 | |
2569 PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength)); | |
2570 | |
2571 if (rv != SECSuccess) { | |
2572 rv = SECFailure; | |
2573 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); | |
2574 } | |
2575 return rv; | |
2576 } | |
2577 | |
2578 /* Called from: ssl3_HandleRecord() | |
2579 * Caller must already hold the SpecReadLock. (wish we could assert that!) | |
2580 * | |
2581 * On entry: | |
2582 * originalLen >= inputLen >= MAC size | |
2583 */ | |
2584 static SECStatus | |
2585 ssl3_ComputeRecordMACConstantTime( | |
2586 ssl3CipherSpec *spec, | |
2587 PRBool useServerMacKey, | |
2588 const unsigned char *header, | |
2589 unsigned int headerLen, | |
2590 const SSL3Opaque *input, | |
2591 int inputLen, | |
2592 int originalLen, | |
2593 unsigned char *outbuf, | |
2594 unsigned int *outLen) | |
2595 { | |
2596 CK_MECHANISM_TYPE macType; | |
2597 CK_NSS_MAC_CONSTANT_TIME_PARAMS params; | |
2598 SECItem param, inputItem, outputItem; | |
2599 SECStatus rv; | |
2600 PK11SymKey *key; | |
2601 | |
2602 PORT_Assert(inputLen >= spec->mac_size); | |
2603 PORT_Assert(originalLen >= inputLen); | |
2604 | |
2605 if (spec->bypassCiphers) { | |
2606 /* This function doesn't support PKCS#11 bypass. We fallback on the | |
2607 * non-constant time version. */ | |
2608 goto fallback; | |
2609 } | |
2610 | |
2611 if (spec->mac_def->mac == mac_null) { | |
2612 *outLen = 0; | |
2613 return SECSuccess; | |
2614 } | |
2615 | |
2616 macType = CKM_NSS_HMAC_CONSTANT_TIME; | |
2617 if (spec->version <= SSL_LIBRARY_VERSION_3_0) { | |
2618 macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME; | |
2619 } | |
2620 | |
2621 params.macAlg = spec->mac_def->mmech; | |
2622 params.ulBodyTotalLen = originalLen; | |
2623 params.pHeader = (unsigned char *)header; /* const cast */ | |
2624 params.ulHeaderLen = headerLen; | |
2625 | |
2626 param.data = (unsigned char *)¶ms; | |
2627 param.len = sizeof(params); | |
2628 param.type = 0; | |
2629 | |
2630 inputItem.data = (unsigned char *)input; | |
2631 inputItem.len = inputLen; | |
2632 inputItem.type = 0; | |
2633 | |
2634 outputItem.data = outbuf; | |
2635 outputItem.len = *outLen; | |
2636 outputItem.type = 0; | |
2637 | |
2638 key = spec->server.write_mac_key; | |
2639 if (!useServerMacKey) { | |
2640 key = spec->client.write_mac_key; | |
2641 } | |
2642 | |
2643 rv = PK11_SignWithSymKey(key, macType, ¶m, &outputItem, &inputItem); | |
2644 if (rv != SECSuccess) { | |
2645 if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) { | |
2646 goto fallback; | |
2647 } | |
2648 | |
2649 *outLen = 0; | |
2650 rv = SECFailure; | |
2651 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); | |
2652 return rv; | |
2653 } | |
2654 | |
2655 PORT_Assert(outputItem.len == (unsigned)spec->mac_size); | |
2656 *outLen = outputItem.len; | |
2657 | |
2658 return rv; | |
2659 | |
2660 fallback: | |
2661 /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the | |
2662 * length already. */ | |
2663 inputLen -= spec->mac_size; | |
2664 return ssl3_ComputeRecordMAC(spec, useServerMacKey, header, headerLen, | |
2665 input, inputLen, outbuf, outLen); | |
2666 } | |
2667 | |
2668 static PRBool | |
2669 ssl3_ClientAuthTokenPresent(sslSessionID *sid) | |
2670 { | |
2671 PK11SlotInfo *slot = NULL; | |
2672 PRBool isPresent = PR_TRUE; | |
2673 | |
2674 /* we only care if we are doing client auth */ | |
2675 if (!sid || !sid->u.ssl3.clAuthValid) { | |
2676 return PR_TRUE; | |
2677 } | |
2678 | |
2679 /* get the slot */ | |
2680 slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID, | |
2681 sid->u.ssl3.clAuthSlotID); | |
2682 if (slot == NULL || | |
2683 !PK11_IsPresent(slot) || | |
2684 sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) || | |
2685 sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) || | |
2686 sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) || | |
2687 (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) { | |
2688 isPresent = PR_FALSE; | |
2689 } | |
2690 if (slot) { | |
2691 PK11_FreeSlot(slot); | |
2692 } | |
2693 return isPresent; | |
2694 } | |
2695 | |
2696 /* Caller must hold the spec read lock. */ | |
2697 SECStatus | |
2698 ssl3_CompressMACEncryptRecord(ssl3CipherSpec *cwSpec, | |
2699 PRBool isServer, | |
2700 PRBool isDTLS, | |
2701 PRBool capRecordVersion, | |
2702 SSL3ContentType type, | |
2703 const SSL3Opaque *pIn, | |
2704 PRUint32 contentLen, | |
2705 sslBuffer *wrBuf) | |
2706 { | |
2707 const ssl3BulkCipherDef *cipher_def; | |
2708 SECStatus rv; | |
2709 PRUint32 macLen = 0; | |
2710 PRUint32 fragLen; | |
2711 PRUint32 p1Len, p2Len, oddLen = 0; | |
2712 PRUint16 headerLen; | |
2713 unsigned int ivLen = 0; | |
2714 int cipherBytes = 0; | |
2715 unsigned char pseudoHeader[13]; | |
2716 unsigned int pseudoHeaderLen; | |
2717 | |
2718 cipher_def = cwSpec->cipher_def; | |
2719 headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH; | |
2720 | |
2721 if (cipher_def->type == type_block && | |
2722 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { | |
2723 /* Prepend the per-record explicit IV using technique 2b from | |
2724 * RFC 4346 section 6.2.3.2: The IV is a cryptographically | |
2725 * strong random number XORed with the CBC residue from the previous | |
2726 * record. | |
2727 */ | |
2728 ivLen = cipher_def->iv_size; | |
2729 if (ivLen > wrBuf->space - headerLen) { | |
2730 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
2731 return SECFailure; | |
2732 } | |
2733 rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen); | |
2734 if (rv != SECSuccess) { | |
2735 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); | |
2736 return rv; | |
2737 } | |
2738 rv = cwSpec->encode(cwSpec->encodeContext, | |
2739 wrBuf->buf + headerLen, | |
2740 &cipherBytes, /* output and actual outLen */ | |
2741 ivLen, /* max outlen */ | |
2742 wrBuf->buf + headerLen, | |
2743 ivLen); /* input and inputLen*/ | |
2744 if (rv != SECSuccess || cipherBytes != ivLen) { | |
2745 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); | |
2746 return SECFailure; | |
2747 } | |
2748 } | |
2749 | |
2750 if (cwSpec->compressor) { | |
2751 int outlen; | |
2752 rv = cwSpec->compressor( | |
2753 cwSpec->compressContext, | |
2754 wrBuf->buf + headerLen + ivLen, &outlen, | |
2755 wrBuf->space - headerLen - ivLen, pIn, contentLen); | |
2756 if (rv != SECSuccess) | |
2757 return rv; | |
2758 pIn = wrBuf->buf + headerLen + ivLen; | |
2759 contentLen = outlen; | |
2760 } | |
2761 | |
2762 pseudoHeaderLen = ssl3_BuildRecordPseudoHeader( | |
2763 pseudoHeader, cwSpec->write_seq_num, type, | |
2764 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version, | |
2765 isDTLS, contentLen); | |
2766 PORT_Assert(pseudoHeaderLen <= sizeof(pseudoHeader)); | |
2767 if (cipher_def->type == type_aead) { | |
2768 const int nonceLen = cipher_def->explicit_nonce_size; | |
2769 const int tagLen = cipher_def->tag_size; | |
2770 | |
2771 if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) { | |
2772 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
2773 return SECFailure; | |
2774 } | |
2775 | |
2776 cipherBytes = contentLen; | |
2777 rv = cwSpec->aead( | |
2778 isServer ? &cwSpec->server : &cwSpec->client, | |
2779 PR_FALSE, /* do encrypt */ | |
2780 wrBuf->buf + headerLen, /* output */ | |
2781 &cipherBytes, /* out len */ | |
2782 wrBuf->space - headerLen, /* max out */ | |
2783 pIn, contentLen, /* input */ | |
2784 pseudoHeader, pseudoHeaderLen); | |
2785 if (rv != SECSuccess) { | |
2786 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); | |
2787 return SECFailure; | |
2788 } | |
2789 } else { | |
2790 /* | |
2791 * Add the MAC | |
2792 */ | |
2793 rv = ssl3_ComputeRecordMAC(cwSpec, isServer, | |
2794 pseudoHeader, pseudoHeaderLen, pIn, contentLe
n, | |
2795 wrBuf->buf + headerLen + ivLen + contentLen, | |
2796 &macLen); | |
2797 if (rv != SECSuccess) { | |
2798 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); | |
2799 return SECFailure; | |
2800 } | |
2801 p1Len = contentLen; | |
2802 p2Len = macLen; | |
2803 fragLen = contentLen + macLen; /* needs to be encrypted */ | |
2804 PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024); | |
2805 | |
2806 /* | |
2807 * Pad the text (if we're doing a block cipher) | |
2808 * then Encrypt it | |
2809 */ | |
2810 if (cipher_def->type == type_block) { | |
2811 unsigned char *pBuf; | |
2812 int padding_length; | |
2813 int i; | |
2814 | |
2815 oddLen = contentLen % cipher_def->block_size; | |
2816 /* Assume blockSize is a power of two */ | |
2817 padding_length = cipher_def->block_size - 1 - ((fragLen) & (cipher_d
ef->block_size - 1)); | |
2818 fragLen += padding_length + 1; | |
2819 PORT_Assert((fragLen % cipher_def->block_size) == 0); | |
2820 | |
2821 /* Pad according to TLS rules (also acceptable to SSL3). */ | |
2822 pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1]; | |
2823 for (i = padding_length + 1; i > 0; --i) { | |
2824 *pBuf-- = padding_length; | |
2825 } | |
2826 /* now, if contentLen is not a multiple of block size, fix it */ | |
2827 p2Len = fragLen - p1Len; | |
2828 } | |
2829 if (p1Len < 256) { | |
2830 oddLen = p1Len; | |
2831 p1Len = 0; | |
2832 } else { | |
2833 p1Len -= oddLen; | |
2834 } | |
2835 if (oddLen) { | |
2836 p2Len += oddLen; | |
2837 PORT_Assert((cipher_def->block_size < 2) || | |
2838 (p2Len % cipher_def->block_size) == 0); | |
2839 memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, | |
2840 oddLen); | |
2841 } | |
2842 if (p1Len > 0) { | |
2843 int cipherBytesPart1 = -1; | |
2844 rv = cwSpec->encode(cwSpec->encodeContext, | |
2845 wrBuf->buf + headerLen + ivLen, /* output */ | |
2846 &cipherBytesPart1, /* actual outlen
*/ | |
2847 p1Len, /* max outlen */ | |
2848 pIn, | |
2849 p1Len); /* input, and inputlen */ | |
2850 PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int)p1Len); | |
2851 if (rv != SECSuccess || cipherBytesPart1 != (int)p1Len) { | |
2852 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); | |
2853 return SECFailure; | |
2854 } | |
2855 cipherBytes += cipherBytesPart1; | |
2856 } | |
2857 if (p2Len > 0) { | |
2858 int cipherBytesPart2 = -1; | |
2859 rv = cwSpec->encode(cwSpec->encodeContext, | |
2860 wrBuf->buf + headerLen + ivLen + p1Len, | |
2861 &cipherBytesPart2, /* output and actual outLen *
/ | |
2862 p2Len, /* max outlen */ | |
2863 wrBuf->buf + headerLen + ivLen + p1Len, | |
2864 p2Len); /* input and inputLen*/ | |
2865 PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int)p2Len); | |
2866 if (rv != SECSuccess || cipherBytesPart2 != (int)p2Len) { | |
2867 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); | |
2868 return SECFailure; | |
2869 } | |
2870 cipherBytes += cipherBytesPart2; | |
2871 } | |
2872 } | |
2873 | |
2874 PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024); | |
2875 | |
2876 wrBuf->len = cipherBytes + headerLen; | |
2877 wrBuf->buf[0] = type; | |
2878 if (isDTLS) { | |
2879 SSL3ProtocolVersion version; | |
2880 | |
2881 version = dtls_TLSVersionToDTLSVersion(cwSpec->version); | |
2882 wrBuf->buf[1] = MSB(version); | |
2883 wrBuf->buf[2] = LSB(version); | |
2884 wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24); | |
2885 wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16); | |
2886 wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >> 8); | |
2887 wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >> 0); | |
2888 wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low >> 24); | |
2889 wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low >> 16); | |
2890 wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low >> 8); | |
2891 wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >> 0); | |
2892 wrBuf->buf[11] = MSB(cipherBytes); | |
2893 wrBuf->buf[12] = LSB(cipherBytes); | |
2894 } else { | |
2895 SSL3ProtocolVersion version = cwSpec->version; | |
2896 | |
2897 if (capRecordVersion || version >= SSL_LIBRARY_VERSION_TLS_1_3) { | |
2898 version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version); | |
2899 } | |
2900 | |
2901 wrBuf->buf[1] = MSB(version); | |
2902 wrBuf->buf[2] = LSB(version); | |
2903 wrBuf->buf[3] = MSB(cipherBytes); | |
2904 wrBuf->buf[4] = LSB(cipherBytes); | |
2905 } | |
2906 | |
2907 ssl3_BumpSequenceNumber(&cwSpec->write_seq_num); | |
2908 | |
2909 return SECSuccess; | |
2910 } | |
2911 | |
2912 /* Process the plain text before sending it. | |
2913 * Returns the number of bytes of plaintext that were successfully sent | |
2914 * plus the number of bytes of plaintext that were copied into the | |
2915 * output (write) buffer. | |
2916 * Returns SECFailure on a hard IO error, memory error, or crypto error. | |
2917 * Does NOT return SECWouldBlock. | |
2918 * | |
2919 * Notes on the use of the private ssl flags: | |
2920 * (no private SSL flags) | |
2921 * Attempt to make and send SSL records for all plaintext | |
2922 * If non-blocking and a send gets WOULD_BLOCK, | |
2923 * or if the pending (ciphertext) buffer is not empty, | |
2924 * then buffer remaining bytes of ciphertext into pending buf, | |
2925 * and continue to do that for all succssive records until all | |
2926 * bytes are used. | |
2927 * ssl_SEND_FLAG_FORCE_INTO_BUFFER | |
2928 * As above, except this suppresses all write attempts, and forces | |
2929 * all ciphertext into the pending ciphertext buffer. | |
2930 * ssl_SEND_FLAG_USE_EPOCH (for DTLS) | |
2931 * Forces the use of the provided epoch | |
2932 * ssl_SEND_FLAG_CAP_RECORD_VERSION | |
2933 * Caps the record layer version number of TLS ClientHello to { 3, 1 } | |
2934 * (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore | |
2935 * ClientHello.client_version and use the record layer version number | |
2936 * (TLSPlaintext.version) instead when negotiating protocol versions. In | |
2937 * addition, if the record layer version number of ClientHello is { 3, 2 } | |
2938 * (TLS 1.1) or higher, these servers reset the TCP connections. Lastly, | |
2939 * some F5 BIG-IP servers hang if a record containing a ClientHello has a | |
2940 * version greater than { 3, 1 } and a length greater than 255. Set this | |
2941 * flag to work around such servers. | |
2942 */ | |
2943 PRInt32 | |
2944 ssl3_SendRecord(sslSocket *ss, | |
2945 DTLSEpoch epoch, /* DTLS only */ | |
2946 SSL3ContentType type, | |
2947 const SSL3Opaque *pIn, /* input buffer */ | |
2948 PRInt32 nIn, /* bytes of input */ | |
2949 PRInt32 flags) | |
2950 { | |
2951 sslBuffer *wrBuf = &ss->sec.writeBuf; | |
2952 SECStatus rv; | |
2953 PRInt32 totalSent = 0; | |
2954 PRBool capRecordVersion; | |
2955 | |
2956 SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d", | |
2957 SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type), | |
2958 nIn)); | |
2959 PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn)); | |
2960 | |
2961 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
2962 | |
2963 if (ss->ssl3.fatalAlertSent) { | |
2964 SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent", | |
2965 SSL_GETPID(), ss->fd)); | |
2966 return SECFailure; | |
2967 } | |
2968 | |
2969 capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0); | |
2970 | |
2971 if (capRecordVersion) { | |
2972 /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the | |
2973 * TLS initial ClientHello. */ | |
2974 PORT_Assert(!IS_DTLS(ss)); | |
2975 PORT_Assert(!ss->firstHsDone); | |
2976 PORT_Assert(type == content_handshake); | |
2977 PORT_Assert(ss->ssl3.hs.ws == wait_server_hello); | |
2978 } | |
2979 | |
2980 if (ss->ssl3.initialized == PR_FALSE) { | |
2981 /* This can happen on a server if the very first incoming record | |
2982 ** looks like a defective ssl3 record (e.g. too long), and we're | |
2983 ** trying to send an alert. | |
2984 */ | |
2985 PR_ASSERT(type == content_alert); | |
2986 rv = ssl3_InitState(ss); | |
2987 if (rv != SECSuccess) { | |
2988 return SECFailure; /* ssl3_InitState has set the error code. */ | |
2989 } | |
2990 } | |
2991 | |
2992 /* check for Token Presence */ | |
2993 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { | |
2994 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); | |
2995 return SECFailure; | |
2996 } | |
2997 | |
2998 while (nIn > 0) { | |
2999 PRUint32 contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH); | |
3000 unsigned int spaceNeeded; | |
3001 unsigned int numRecords; | |
3002 | |
3003 ssl_GetSpecReadLock(ss); /********************************/ | |
3004 | |
3005 if (nIn > 1 && ss->opt.cbcRandomIV && | |
3006 ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 && | |
3007 type == content_application_data && | |
3008 ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) { | |
3009 /* We will split the first byte of the record into its own record, | |
3010 * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h | |
3011 */ | |
3012 numRecords = 2; | |
3013 } else { | |
3014 numRecords = 1; | |
3015 } | |
3016 | |
3017 spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE); | |
3018 if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 && | |
3019 ss->ssl3.cwSpec->cipher_def->type == type_block) { | |
3020 spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size; | |
3021 } | |
3022 if (spaceNeeded > wrBuf->space) { | |
3023 rv = sslBuffer_Grow(wrBuf, spaceNeeded); | |
3024 if (rv != SECSuccess) { | |
3025 SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes", | |
3026 SSL_GETPID(), ss->fd, spaceNeeded)); | |
3027 goto spec_locked_loser; /* sslBuffer_Grow set error code. */ | |
3028 } | |
3029 } | |
3030 | |
3031 if (numRecords == 2) { | |
3032 sslBuffer secondRecord; | |
3033 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, | |
3034 ss->sec.isServer, IS_DTLS(ss), | |
3035 capRecordVersion, type, pIn, | |
3036 1, wrBuf); | |
3037 if (rv != SECSuccess) | |
3038 goto spec_locked_loser; | |
3039 | |
3040 PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:", | |
3041 wrBuf->buf, wrBuf->len)); | |
3042 | |
3043 secondRecord.buf = wrBuf->buf + wrBuf->len; | |
3044 secondRecord.len = 0; | |
3045 secondRecord.space = wrBuf->space - wrBuf->len; | |
3046 | |
3047 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, | |
3048 ss->sec.isServer, IS_DTLS(ss), | |
3049 capRecordVersion, type, | |
3050 pIn + 1, | |
3051 contentLen - 1, | |
3052 &secondRecord); | |
3053 if (rv == SECSuccess) { | |
3054 PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:", | |
3055 secondRecord.buf, secondRecord.len)); | |
3056 wrBuf->len += secondRecord.len; | |
3057 } | |
3058 } else { | |
3059 if (!IS_DTLS(ss)) { | |
3060 if (ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_3) { | |
3061 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, | |
3062 ss->sec.isServer, | |
3063 PR_FALSE, | |
3064 capRecordVersion, | |
3065 type, pIn, | |
3066 contentLen, wrBuf); | |
3067 } else { | |
3068 rv = tls13_ProtectRecord(ss, type, pIn, | |
3069 contentLen, wrBuf); | |
3070 } | |
3071 } else { | |
3072 /* TLS <= 1.2 and TLS 1.3 cases are both handled in | |
3073 * dtls_CompressMACEncryptRecord. */ | |
3074 rv = dtls_CompressMACEncryptRecord(ss, epoch, | |
3075 !!(flags & ssl_SEND_FLAG_USE_
EPOCH), | |
3076 type, pIn, | |
3077 contentLen, wrBuf); | |
3078 } | |
3079 | |
3080 if (rv == SECSuccess) { | |
3081 PRINT_BUF(50, (ss, "send (encrypted) record data:", | |
3082 wrBuf->buf, wrBuf->len)); | |
3083 } | |
3084 } | |
3085 | |
3086 spec_locked_loser: | |
3087 ssl_ReleaseSpecReadLock(ss); /************************************/ | |
3088 | |
3089 if (rv != SECSuccess) | |
3090 return SECFailure; | |
3091 | |
3092 pIn += contentLen; | |
3093 nIn -= contentLen; | |
3094 PORT_Assert(nIn >= 0); | |
3095 | |
3096 /* If there's still some previously saved ciphertext, | |
3097 * or the caller doesn't want us to send the data yet, | |
3098 * then add all our new ciphertext to the amount previously saved. | |
3099 */ | |
3100 if ((ss->pendingBuf.len > 0) || | |
3101 (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { | |
3102 | |
3103 rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len); | |
3104 if (rv != SECSuccess) { | |
3105 /* presumably a memory error, SEC_ERROR_NO_MEMORY */ | |
3106 return SECFailure; | |
3107 } | |
3108 wrBuf->len = 0; /* All cipher text is saved away. */ | |
3109 | |
3110 if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { | |
3111 PRInt32 sent; | |
3112 ss->handshakeBegun = 1; | |
3113 sent = ssl_SendSavedWriteData(ss); | |
3114 if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) { | |
3115 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); | |
3116 return SECFailure; | |
3117 } | |
3118 if (ss->pendingBuf.len) { | |
3119 flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER; | |
3120 } | |
3121 } | |
3122 } else if (wrBuf->len > 0) { | |
3123 PRInt32 sent; | |
3124 ss->handshakeBegun = 1; | |
3125 sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len, | |
3126 flags & ~ssl_SEND_FLAG_MASK); | |
3127 if (sent < 0) { | |
3128 if (PR_GetError() != PR_WOULD_BLOCK_ERROR) { | |
3129 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); | |
3130 return SECFailure; | |
3131 } | |
3132 /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */ | |
3133 sent = 0; | |
3134 } | |
3135 wrBuf->len -= sent; | |
3136 if (wrBuf->len) { | |
3137 if (IS_DTLS(ss)) { | |
3138 /* DTLS just says no in this case. No buffering */ | |
3139 PR_SetError(PR_WOULD_BLOCK_ERROR, 0); | |
3140 return SECFailure; | |
3141 } | |
3142 /* now take all the remaining unsent new ciphertext and | |
3143 * append it to the buffer of previously unsent ciphertext. | |
3144 */ | |
3145 rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len); | |
3146 if (rv != SECSuccess) { | |
3147 /* presumably a memory error, SEC_ERROR_NO_MEMORY */ | |
3148 return SECFailure; | |
3149 } | |
3150 } | |
3151 } | |
3152 totalSent += contentLen; | |
3153 } | |
3154 return totalSent; | |
3155 } | |
3156 | |
3157 #define SSL3_PENDING_HIGH_WATER 1024 | |
3158 | |
3159 /* Attempt to send the content of "in" in an SSL application_data record. | |
3160 * Returns "len" or SECFailure, never SECWouldBlock, nor SECSuccess. | |
3161 */ | |
3162 int | |
3163 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in, | |
3164 PRInt32 len, PRInt32 flags) | |
3165 { | |
3166 PRInt32 totalSent = 0; | |
3167 PRInt32 discarded = 0; | |
3168 | |
3169 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
3170 /* These flags for internal use only */ | |
3171 PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH | | |
3172 ssl_SEND_FLAG_NO_RETRANSMIT))); | |
3173 if (len < 0 || !in) { | |
3174 PORT_SetError(PR_INVALID_ARGUMENT_ERROR); | |
3175 return SECFailure; | |
3176 } | |
3177 | |
3178 if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER && | |
3179 !ssl_SocketIsBlocking(ss)) { | |
3180 PORT_Assert(!ssl_SocketIsBlocking(ss)); | |
3181 PORT_SetError(PR_WOULD_BLOCK_ERROR); | |
3182 return SECFailure; | |
3183 } | |
3184 | |
3185 if (ss->appDataBuffered && len) { | |
3186 PORT_Assert(in[0] == (unsigned char)(ss->appDataBuffered)); | |
3187 if (in[0] != (unsigned char)(ss->appDataBuffered)) { | |
3188 PORT_SetError(PR_INVALID_ARGUMENT_ERROR); | |
3189 return SECFailure; | |
3190 } | |
3191 in++; | |
3192 len--; | |
3193 discarded = 1; | |
3194 } | |
3195 while (len > totalSent) { | |
3196 PRInt32 sent, toSend; | |
3197 | |
3198 if (totalSent > 0) { | |
3199 /* | |
3200 * The thread yield is intended to give the reader thread a | |
3201 * chance to get some cycles while the writer thread is in | |
3202 * the middle of a large application data write. (See | |
3203 * Bugzilla bug 127740, comment #1.) | |
3204 */ | |
3205 ssl_ReleaseXmitBufLock(ss); | |
3206 PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */ | |
3207 ssl_GetXmitBufLock(ss); | |
3208 } | |
3209 toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH); | |
3210 /* | |
3211 * Note that the 0 epoch is OK because flags will never require | |
3212 * its use, as guaranteed by the PORT_Assert above. | |
3213 */ | |
3214 sent = ssl3_SendRecord(ss, 0, content_application_data, | |
3215 in + totalSent, toSend, flags); | |
3216 if (sent < 0) { | |
3217 if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) { | |
3218 PORT_Assert(ss->lastWriteBlocked); | |
3219 break; | |
3220 } | |
3221 return SECFailure; /* error code set by ssl3_SendRecord */ | |
3222 } | |
3223 totalSent += sent; | |
3224 if (ss->pendingBuf.len) { | |
3225 /* must be a non-blocking socket */ | |
3226 PORT_Assert(!ssl_SocketIsBlocking(ss)); | |
3227 PORT_Assert(ss->lastWriteBlocked); | |
3228 break; | |
3229 } | |
3230 } | |
3231 if (ss->pendingBuf.len) { | |
3232 /* Must be non-blocking. */ | |
3233 PORT_Assert(!ssl_SocketIsBlocking(ss)); | |
3234 if (totalSent > 0) { | |
3235 ss->appDataBuffered = 0x100 | in[totalSent - 1]; | |
3236 } | |
3237 | |
3238 totalSent = totalSent + discarded - 1; | |
3239 if (totalSent <= 0) { | |
3240 PORT_SetError(PR_WOULD_BLOCK_ERROR); | |
3241 totalSent = SECFailure; | |
3242 } | |
3243 return totalSent; | |
3244 } | |
3245 ss->appDataBuffered = 0; | |
3246 return totalSent + discarded; | |
3247 } | |
3248 | |
3249 /* Attempt to send buffered handshake messages. | |
3250 * This function returns SECSuccess or SECFailure, never SECWouldBlock. | |
3251 * Always set sendBuf.len to 0, even when returning SECFailure. | |
3252 * | |
3253 * Depending on whether we are doing DTLS or not, this either calls | |
3254 * | |
3255 * - ssl3_FlushHandshakeMessages if non-DTLS | |
3256 * - dtls_FlushHandshakeMessages if DTLS | |
3257 * | |
3258 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(), | |
3259 * ssl3_AppendHandshake(), ssl3_SendClientHello(), | |
3260 * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(), | |
3261 * ssl3_SendFinished(), | |
3262 */ | |
3263 SECStatus | |
3264 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags) | |
3265 { | |
3266 if (IS_DTLS(ss)) { | |
3267 return dtls_FlushHandshakeMessages(ss, flags); | |
3268 } else { | |
3269 return ssl3_FlushHandshakeMessages(ss, flags); | |
3270 } | |
3271 } | |
3272 | |
3273 /* Attempt to send the content of sendBuf buffer in an SSL handshake record. | |
3274 * This function returns SECSuccess or SECFailure, never SECWouldBlock. | |
3275 * Always set sendBuf.len to 0, even when returning SECFailure. | |
3276 * | |
3277 * Called from ssl3_FlushHandshake | |
3278 */ | |
3279 static SECStatus | |
3280 ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags) | |
3281 { | |
3282 static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER | | |
3283 ssl_SEND_FLAG_CAP_RECORD_VERSION; | |
3284 PRInt32 count = -1; | |
3285 SECStatus rv = SECSuccess; | |
3286 | |
3287 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
3288 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
3289 | |
3290 if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len) | |
3291 return rv; | |
3292 | |
3293 /* only these flags are allowed */ | |
3294 PORT_Assert(!(flags & ~allowedFlags)); | |
3295 if ((flags & ~allowedFlags) != 0) { | |
3296 PORT_SetError(SEC_ERROR_INVALID_ARGS); | |
3297 rv = SECFailure; | |
3298 } else { | |
3299 count = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf
, | |
3300 ss->sec.ci.sendBuf.len, flags); | |
3301 } | |
3302 if (count < 0) { | |
3303 int err = PORT_GetError(); | |
3304 PORT_Assert(err != PR_WOULD_BLOCK_ERROR); | |
3305 if (err == PR_WOULD_BLOCK_ERROR) { | |
3306 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
3307 } | |
3308 rv = SECFailure; | |
3309 } else if ((unsigned int)count < ss->sec.ci.sendBuf.len) { | |
3310 /* short write should never happen */ | |
3311 PORT_Assert((unsigned int)count >= ss->sec.ci.sendBuf.len); | |
3312 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
3313 rv = SECFailure; | |
3314 } else { | |
3315 rv = SECSuccess; | |
3316 } | |
3317 | |
3318 /* Whether we succeeded or failed, toss the old handshake data. */ | |
3319 ss->sec.ci.sendBuf.len = 0; | |
3320 return rv; | |
3321 } | |
3322 | |
3323 /* | |
3324 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when | |
3325 * the remote client sends a negative response to our certificate request. | |
3326 * Returns SECFailure if the application has required client auth. | |
3327 * SECSuccess otherwise. | |
3328 */ | |
3329 static SECStatus | |
3330 ssl3_HandleNoCertificate(sslSocket *ss) | |
3331 { | |
3332 if (ss->sec.peerCert != NULL) { | |
3333 if (ss->sec.peerKey != NULL) { | |
3334 SECKEY_DestroyPublicKey(ss->sec.peerKey); | |
3335 ss->sec.peerKey = NULL; | |
3336 } | |
3337 CERT_DestroyCertificate(ss->sec.peerCert); | |
3338 ss->sec.peerCert = NULL; | |
3339 } | |
3340 ssl3_CleanupPeerCerts(ss); | |
3341 | |
3342 /* If the server has required client-auth blindly but doesn't | |
3343 * actually look at the certificate it won't know that no | |
3344 * certificate was presented so we shutdown the socket to ensure | |
3345 * an error. We only do this if we haven't already completed the | |
3346 * first handshake because if we're redoing the handshake we | |
3347 * know the server is paying attention to the certificate. | |
3348 */ | |
3349 if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || | |
3350 (!ss->firstHsDone && | |
3351 (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) { | |
3352 PRFileDesc *lower; | |
3353 | |
3354 if (ss->sec.uncache) | |
3355 ss->sec.uncache(ss->sec.ci.sid); | |
3356 SSL3_SendAlert(ss, alert_fatal, bad_certificate); | |
3357 | |
3358 lower = ss->fd->lower; | |
3359 #ifdef _WIN32 | |
3360 lower->methods->shutdown(lower, PR_SHUTDOWN_SEND); | |
3361 #else | |
3362 lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH); | |
3363 #endif | |
3364 PORT_SetError(SSL_ERROR_NO_CERTIFICATE); | |
3365 return SECFailure; | |
3366 } | |
3367 return SECSuccess; | |
3368 } | |
3369 | |
3370 /************************************************************************ | |
3371 * Alerts | |
3372 */ | |
3373 | |
3374 /* | |
3375 ** Acquires both handshake and XmitBuf locks. | |
3376 ** Called from: ssl3_IllegalParameter <- | |
3377 ** ssl3_HandshakeFailure <- | |
3378 ** ssl3_HandleAlert <- ssl3_HandleRecord. | |
3379 ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord | |
3380 ** ssl3_ConsumeHandshakeVariable <- | |
3381 ** ssl3_HandleHelloRequest <- | |
3382 ** ssl3_HandleServerHello <- | |
3383 ** ssl3_HandleServerKeyExchange <- | |
3384 ** ssl3_HandleCertificateRequest <- | |
3385 ** ssl3_HandleServerHelloDone <- | |
3386 ** ssl3_HandleClientHello <- | |
3387 ** ssl3_HandleV2ClientHello <- | |
3388 ** ssl3_HandleCertificateVerify <- | |
3389 ** ssl3_HandleClientKeyExchange <- | |
3390 ** ssl3_HandleCertificate <- | |
3391 ** ssl3_HandleFinished <- | |
3392 ** ssl3_HandleHandshakeMessage <- | |
3393 ** ssl3_HandlePostHelloHandshakeMessage <- | |
3394 ** ssl3_HandleRecord <- | |
3395 ** | |
3396 */ | |
3397 SECStatus | |
3398 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc) | |
3399 { | |
3400 PRUint8 bytes[2]; | |
3401 SECStatus rv; | |
3402 | |
3403 SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d", | |
3404 SSL_GETPID(), ss->fd, level, desc)); | |
3405 | |
3406 bytes[0] = level; | |
3407 bytes[1] = desc; | |
3408 | |
3409 ssl_GetSSL3HandshakeLock(ss); | |
3410 if (level == alert_fatal) { | |
3411 if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) { | |
3412 ss->sec.uncache(ss->sec.ci.sid); | |
3413 } | |
3414 } | |
3415 ssl_GetXmitBufLock(ss); | |
3416 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); | |
3417 if (rv == SECSuccess) { | |
3418 PRInt32 sent; | |
3419 sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2, | |
3420 desc == no_certificate ? ssl_SEND_FLAG_FORCE_INTO
_BUFFER : 0); | |
3421 rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; | |
3422 } | |
3423 if (level == alert_fatal) { | |
3424 ss->ssl3.fatalAlertSent = PR_TRUE; | |
3425 } | |
3426 ssl_ReleaseXmitBufLock(ss); | |
3427 ssl_ReleaseSSL3HandshakeLock(ss); | |
3428 return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */ | |
3429 } | |
3430 | |
3431 /* | |
3432 * Send illegal_parameter alert. Set generic error number. | |
3433 */ | |
3434 static SECStatus | |
3435 ssl3_IllegalParameter(sslSocket *ss) | |
3436 { | |
3437 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); | |
3438 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT | |
3439 : SSL_ERROR_BAD_SERVER); | |
3440 return SECFailure; | |
3441 } | |
3442 | |
3443 /* | |
3444 * Send handshake_Failure alert. Set generic error number. | |
3445 */ | |
3446 static SECStatus | |
3447 ssl3_HandshakeFailure(sslSocket *ss) | |
3448 { | |
3449 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure); | |
3450 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT | |
3451 : SSL_ERROR_BAD_SERVER); | |
3452 return SECFailure; | |
3453 } | |
3454 | |
3455 static void | |
3456 ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode) | |
3457 { | |
3458 SSL3AlertDescription desc = bad_certificate; | |
3459 PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS; | |
3460 | |
3461 switch (errCode) { | |
3462 case SEC_ERROR_LIBRARY_FAILURE: | |
3463 desc = unsupported_certificate; | |
3464 break; | |
3465 case SEC_ERROR_EXPIRED_CERTIFICATE: | |
3466 desc = certificate_expired; | |
3467 break; | |
3468 case SEC_ERROR_REVOKED_CERTIFICATE: | |
3469 desc = certificate_revoked; | |
3470 break; | |
3471 case SEC_ERROR_INADEQUATE_KEY_USAGE: | |
3472 case SEC_ERROR_INADEQUATE_CERT_TYPE: | |
3473 desc = certificate_unknown; | |
3474 break; | |
3475 case SEC_ERROR_UNTRUSTED_CERT: | |
3476 desc = isTLS ? access_denied : certificate_unknown; | |
3477 break; | |
3478 case SEC_ERROR_UNKNOWN_ISSUER: | |
3479 case SEC_ERROR_UNTRUSTED_ISSUER: | |
3480 desc = isTLS ? unknown_ca : certificate_unknown; | |
3481 break; | |
3482 case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE: | |
3483 desc = isTLS ? unknown_ca : certificate_expired; | |
3484 break; | |
3485 | |
3486 case SEC_ERROR_CERT_NOT_IN_NAME_SPACE: | |
3487 case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID: | |
3488 case SEC_ERROR_CA_CERT_INVALID: | |
3489 case SEC_ERROR_BAD_SIGNATURE: | |
3490 default: | |
3491 desc = bad_certificate; | |
3492 break; | |
3493 } | |
3494 SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d", | |
3495 SSL_GETPID(), ss->fd, errCode)); | |
3496 | |
3497 (void)SSL3_SendAlert(ss, alert_fatal, desc); | |
3498 } | |
3499 | |
3500 /* | |
3501 * Send decode_error alert. Set generic error number. | |
3502 */ | |
3503 SECStatus | |
3504 ssl3_DecodeError(sslSocket *ss) | |
3505 { | |
3506 (void)SSL3_SendAlert(ss, alert_fatal, | |
3507 ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error | |
3508 : illegal_paramet
er); | |
3509 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT | |
3510 : SSL_ERROR_BAD_SERVER); | |
3511 return SECFailure; | |
3512 } | |
3513 | |
3514 /* Called from ssl3_HandleRecord. | |
3515 ** Caller must hold both RecvBuf and Handshake locks. | |
3516 */ | |
3517 static SECStatus | |
3518 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf) | |
3519 { | |
3520 SSL3AlertLevel level; | |
3521 SSL3AlertDescription desc; | |
3522 int error; | |
3523 | |
3524 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
3525 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
3526 | |
3527 SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd)); | |
3528 | |
3529 if (buf->len != 2) { | |
3530 (void)ssl3_DecodeError(ss); | |
3531 PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT); | |
3532 return SECFailure; | |
3533 } | |
3534 level = (SSL3AlertLevel)buf->buf[0]; | |
3535 desc = (SSL3AlertDescription)buf->buf[1]; | |
3536 buf->len = 0; | |
3537 SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d", | |
3538 SSL_GETPID(), ss->fd, level, desc)); | |
3539 | |
3540 switch (desc) { | |
3541 case close_notify: | |
3542 ss->recvdCloseNotify = 1; | |
3543 error = SSL_ERROR_CLOSE_NOTIFY_ALERT; | |
3544 break; | |
3545 case unexpected_message: | |
3546 error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT; | |
3547 break; | |
3548 case bad_record_mac: | |
3549 error = SSL_ERROR_BAD_MAC_ALERT; | |
3550 break; | |
3551 case decryption_failed_RESERVED: | |
3552 error = SSL_ERROR_DECRYPTION_FAILED_ALERT; | |
3553 break; | |
3554 case record_overflow: | |
3555 error = SSL_ERROR_RECORD_OVERFLOW_ALERT; | |
3556 break; | |
3557 case decompression_failure: | |
3558 error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT; | |
3559 break; | |
3560 case handshake_failure: | |
3561 error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT; | |
3562 break; | |
3563 case no_certificate: | |
3564 error = SSL_ERROR_NO_CERTIFICATE; | |
3565 break; | |
3566 case bad_certificate: | |
3567 error = SSL_ERROR_BAD_CERT_ALERT; | |
3568 break; | |
3569 case unsupported_certificate: | |
3570 error = SSL_ERROR_UNSUPPORTED_CERT_ALERT; | |
3571 break; | |
3572 case certificate_revoked: | |
3573 error = SSL_ERROR_REVOKED_CERT_ALERT; | |
3574 break; | |
3575 case certificate_expired: | |
3576 error = SSL_ERROR_EXPIRED_CERT_ALERT; | |
3577 break; | |
3578 case certificate_unknown: | |
3579 error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT; | |
3580 break; | |
3581 case illegal_parameter: | |
3582 error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT; | |
3583 break; | |
3584 case inappropriate_fallback: | |
3585 error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; | |
3586 break; | |
3587 | |
3588 /* All alerts below are TLS only. */ | |
3589 case unknown_ca: | |
3590 error = SSL_ERROR_UNKNOWN_CA_ALERT; | |
3591 break; | |
3592 case access_denied: | |
3593 error = SSL_ERROR_ACCESS_DENIED_ALERT; | |
3594 break; | |
3595 case decode_error: | |
3596 error = SSL_ERROR_DECODE_ERROR_ALERT; | |
3597 break; | |
3598 case decrypt_error: | |
3599 error = SSL_ERROR_DECRYPT_ERROR_ALERT; | |
3600 break; | |
3601 case export_restriction: | |
3602 error = SSL_ERROR_EXPORT_RESTRICTION_ALERT; | |
3603 break; | |
3604 case protocol_version: | |
3605 error = SSL_ERROR_PROTOCOL_VERSION_ALERT; | |
3606 break; | |
3607 case insufficient_security: | |
3608 error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT; | |
3609 break; | |
3610 case internal_error: | |
3611 error = SSL_ERROR_INTERNAL_ERROR_ALERT; | |
3612 break; | |
3613 case user_canceled: | |
3614 error = SSL_ERROR_USER_CANCELED_ALERT; | |
3615 break; | |
3616 case no_renegotiation: | |
3617 error = SSL_ERROR_NO_RENEGOTIATION_ALERT; | |
3618 break; | |
3619 | |
3620 /* Alerts for TLS client hello extensions */ | |
3621 case missing_extension: | |
3622 error = SSL_ERROR_MISSING_EXTENSION_ALERT; | |
3623 break; | |
3624 case unsupported_extension: | |
3625 error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT; | |
3626 break; | |
3627 case certificate_unobtainable: | |
3628 error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; | |
3629 break; | |
3630 case unrecognized_name: | |
3631 error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; | |
3632 break; | |
3633 case bad_certificate_status_response: | |
3634 error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; | |
3635 break; | |
3636 case bad_certificate_hash_value: | |
3637 error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT; | |
3638 break; | |
3639 default: | |
3640 error = SSL_ERROR_RX_UNKNOWN_ALERT; | |
3641 break; | |
3642 } | |
3643 if (level == alert_fatal) { | |
3644 if (!ss->opt.noCache) { | |
3645 if (ss->sec.uncache) | |
3646 ss->sec.uncache(ss->sec.ci.sid); | |
3647 } | |
3648 if ((ss->ssl3.hs.ws == wait_server_hello) && | |
3649 (desc == handshake_failure)) { | |
3650 /* XXX This is a hack. We're assuming that any handshake failure | |
3651 * XXX on the client hello is a failure to match ciphers. | |
3652 */ | |
3653 error = SSL_ERROR_NO_CYPHER_OVERLAP; | |
3654 } | |
3655 PORT_SetError(error); | |
3656 return SECFailure; | |
3657 } | |
3658 if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) { | |
3659 /* I'm a server. I've requested a client cert. He hasn't got one. */ | |
3660 SECStatus rv; | |
3661 | |
3662 PORT_Assert(ss->sec.isServer); | |
3663 ss->ssl3.hs.ws = wait_client_key; | |
3664 rv = ssl3_HandleNoCertificate(ss); | |
3665 return rv; | |
3666 } | |
3667 return SECSuccess; | |
3668 } | |
3669 | |
3670 /* | |
3671 * Change Cipher Specs | |
3672 * Called from ssl3_HandleServerHelloDone, | |
3673 * ssl3_HandleClientHello, | |
3674 * and ssl3_HandleFinished | |
3675 * | |
3676 * Acquires and releases spec write lock, to protect switching the current | |
3677 * and pending write spec pointers. | |
3678 */ | |
3679 | |
3680 static SECStatus | |
3681 ssl3_SendChangeCipherSpecs(sslSocket *ss) | |
3682 { | |
3683 PRUint8 change = change_cipher_spec_choice; | |
3684 ssl3CipherSpec *pwSpec; | |
3685 SECStatus rv; | |
3686 PRInt32 sent; | |
3687 | |
3688 SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record", | |
3689 SSL_GETPID(), ss->fd)); | |
3690 | |
3691 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
3692 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
3693 | |
3694 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); | |
3695 if (rv != SECSuccess) { | |
3696 return rv; /* error code set by ssl3_FlushHandshake */ | |
3697 } | |
3698 if (!IS_DTLS(ss)) { | |
3699 sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1, | |
3700 ssl_SEND_FLAG_FORCE_INTO_BUFFER); | |
3701 if (sent < 0) { | |
3702 return (SECStatus)sent; /* error code set by ssl3_SendRecord */ | |
3703 } | |
3704 } else { | |
3705 rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1); | |
3706 if (rv != SECSuccess) { | |
3707 return rv; | |
3708 } | |
3709 } | |
3710 | |
3711 /* swap the pending and current write specs. */ | |
3712 ssl_GetSpecWriteLock(ss); /**************************************/ | |
3713 pwSpec = ss->ssl3.pwSpec; | |
3714 | |
3715 ss->ssl3.pwSpec = ss->ssl3.cwSpec; | |
3716 ss->ssl3.cwSpec = pwSpec; | |
3717 | |
3718 SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending", | |
3719 SSL_GETPID(), ss->fd)); | |
3720 | |
3721 /* We need to free up the contexts, keys and certs ! */ | |
3722 /* If we are really through with the old cipher spec | |
3723 * (Both the read and write sides have changed) destroy it. | |
3724 */ | |
3725 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { | |
3726 if (!IS_DTLS(ss)) { | |
3727 ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE /*freeSrvName*/); | |
3728 } else { | |
3729 /* With DTLS, we need to set a holddown timer in case the final | |
3730 * message got lost */ | |
3731 ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS; | |
3732 dtls_StartTimer(ss, dtls_FinishedTimerCb); | |
3733 } | |
3734 } | |
3735 ssl_ReleaseSpecWriteLock(ss); /**************************************/ | |
3736 | |
3737 return SECSuccess; | |
3738 } | |
3739 | |
3740 /* Called from ssl3_HandleRecord. | |
3741 ** Caller must hold both RecvBuf and Handshake locks. | |
3742 * | |
3743 * Acquires and releases spec write lock, to protect switching the current | |
3744 * and pending write spec pointers. | |
3745 */ | |
3746 static SECStatus | |
3747 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf) | |
3748 { | |
3749 ssl3CipherSpec *prSpec; | |
3750 SSL3WaitState ws = ss->ssl3.hs.ws; | |
3751 SSL3ChangeCipherSpecChoice change; | |
3752 | |
3753 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
3754 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
3755 | |
3756 SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record", | |
3757 SSL_GETPID(), ss->fd)); | |
3758 | |
3759 if (ws != wait_change_cipher) { | |
3760 if (IS_DTLS(ss)) { | |
3761 /* Ignore this because it's out of order. */ | |
3762 SSL_TRC(3, ("%d: SSL3[%d]: discard out of order " | |
3763 "DTLS change_cipher_spec", | |
3764 SSL_GETPID(), ss->fd)); | |
3765 buf->len = 0; | |
3766 return SECSuccess; | |
3767 } | |
3768 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
3769 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER); | |
3770 return SECFailure; | |
3771 } | |
3772 | |
3773 if (buf->len != 1) { | |
3774 (void)ssl3_DecodeError(ss); | |
3775 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); | |
3776 return SECFailure; | |
3777 } | |
3778 change = (SSL3ChangeCipherSpecChoice)buf->buf[0]; | |
3779 if (change != change_cipher_spec_choice) { | |
3780 /* illegal_parameter is correct here for both SSL3 and TLS. */ | |
3781 (void)ssl3_IllegalParameter(ss); | |
3782 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); | |
3783 return SECFailure; | |
3784 } | |
3785 buf->len = 0; | |
3786 | |
3787 /* Swap the pending and current read specs. */ | |
3788 ssl_GetSpecWriteLock(ss); /*************************************/ | |
3789 prSpec = ss->ssl3.prSpec; | |
3790 | |
3791 ss->ssl3.prSpec = ss->ssl3.crSpec; | |
3792 ss->ssl3.crSpec = prSpec; | |
3793 ss->ssl3.hs.ws = wait_finished; | |
3794 | |
3795 SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending", | |
3796 SSL_GETPID(), ss->fd)); | |
3797 | |
3798 /* If we are really through with the old cipher prSpec | |
3799 * (Both the read and write sides have changed) destroy it. | |
3800 */ | |
3801 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { | |
3802 ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE /*freeSrvName*/); | |
3803 } | |
3804 ssl_ReleaseSpecWriteLock(ss); /*************************************/ | |
3805 return SECSuccess; | |
3806 } | |
3807 | |
3808 /* This method completes the derivation of the MS from the PMS. | |
3809 ** | |
3810 ** 1. Derive the MS, if possible, else return an error. | |
3811 ** | |
3812 ** 2. Check the version if |pms_version| is non-zero and if wrong, | |
3813 ** return an error. | |
3814 ** | |
3815 ** 3. If |msp| is nonzero, return MS in |*msp|. | |
3816 | |
3817 ** Called from: | |
3818 ** ssl3_ComputeMasterSecretInt | |
3819 ** tls_ComputeExtendedMasterSecretInt | |
3820 */ | |
3821 static SECStatus | |
3822 ssl3_ComputeMasterSecretFinish(sslSocket *ss, | |
3823 CK_MECHANISM_TYPE master_derive, | |
3824 CK_MECHANISM_TYPE key_derive, | |
3825 CK_VERSION *pms_version, | |
3826 SECItem *params, CK_FLAGS keyFlags, | |
3827 PK11SymKey *pms, PK11SymKey **msp) | |
3828 { | |
3829 PK11SymKey *ms = NULL; | |
3830 | |
3831 ms = PK11_DeriveWithFlags(pms, master_derive, | |
3832 params, key_derive, | |
3833 CKA_DERIVE, 0, keyFlags); | |
3834 if (!ms) { | |
3835 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); | |
3836 return SECFailure; | |
3837 } | |
3838 | |
3839 if (pms_version && ss->opt.detectRollBack) { | |
3840 SSL3ProtocolVersion client_version; | |
3841 client_version = pms_version->major << 8 | pms_version->minor; | |
3842 | |
3843 if (IS_DTLS(ss)) { | |
3844 client_version = dtls_DTLSVersionToTLSVersion(client_version); | |
3845 } | |
3846 | |
3847 if (client_version != ss->clientHelloVersion) { | |
3848 /* Destroy MS. Version roll-back detected. */ | |
3849 PK11_FreeSymKey(ms); | |
3850 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); | |
3851 return SECFailure; | |
3852 } | |
3853 } | |
3854 | |
3855 if (msp) { | |
3856 *msp = ms; | |
3857 } else { | |
3858 PK11_FreeSymKey(ms); | |
3859 } | |
3860 | |
3861 return SECSuccess; | |
3862 } | |
3863 | |
3864 /* Compute the ordinary (pre draft-ietf-tls-session-hash) master | |
3865 ** secret and return it in |*msp|. | |
3866 ** | |
3867 ** Called from: ssl3_ComputeMasterSecret | |
3868 */ | |
3869 static SECStatus | |
3870 ssl3_ComputeMasterSecretInt(sslSocket *ss, PK11SymKey *pms, | |
3871 PK11SymKey **msp) | |
3872 { | |
3873 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; | |
3874 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; | |
3875 unsigned char *cr = (unsigned char *)&ss->ssl3.hs.client_random; | |
3876 unsigned char *sr = (unsigned char *)&ss->ssl3.hs.server_random; | |
3877 PRBool isTLS = (PRBool)(kea_def->tls_keygen || | |
3878 (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); | |
3879 PRBool isTLS12 = | |
3880 (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
3881 /* | |
3882 * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH | |
3883 * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size | |
3884 * data into a 48-byte value, and does not expect to return the version. | |
3885 */ | |
3886 PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) || | |
3887 (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh)); | |
3888 CK_MECHANISM_TYPE master_derive; | |
3889 CK_MECHANISM_TYPE key_derive; | |
3890 SECItem params; | |
3891 CK_FLAGS keyFlags; | |
3892 CK_VERSION pms_version; | |
3893 CK_VERSION *pms_version_ptr = NULL; | |
3894 /* master_params may be used as a CK_SSL3_MASTER_KEY_DERIVE_PARAMS */ | |
3895 CK_TLS12_MASTER_KEY_DERIVE_PARAMS master_params; | |
3896 unsigned int master_params_len; | |
3897 | |
3898 if (isTLS12) { | |
3899 if (isDH) | |
3900 master_derive = CKM_TLS12_MASTER_KEY_DERIVE_DH; | |
3901 else | |
3902 master_derive = CKM_TLS12_MASTER_KEY_DERIVE; | |
3903 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; | |
3904 keyFlags = CKF_SIGN | CKF_VERIFY; | |
3905 } else if (isTLS) { | |
3906 if (isDH) | |
3907 master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH; | |
3908 else | |
3909 master_derive = CKM_TLS_MASTER_KEY_DERIVE; | |
3910 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; | |
3911 keyFlags = CKF_SIGN | CKF_VERIFY; | |
3912 } else { | |
3913 if (isDH) | |
3914 master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH; | |
3915 else | |
3916 master_derive = CKM_SSL3_MASTER_KEY_DERIVE; | |
3917 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; | |
3918 keyFlags = 0; | |
3919 } | |
3920 | |
3921 if (!isDH) { | |
3922 pms_version_ptr = &pms_version; | |
3923 } | |
3924 | |
3925 master_params.pVersion = pms_version_ptr; | |
3926 master_params.RandomInfo.pClientRandom = cr; | |
3927 master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; | |
3928 master_params.RandomInfo.pServerRandom = sr; | |
3929 master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; | |
3930 if (isTLS12) { | |
3931 master_params.prfHashMechanism = CKM_SHA256; | |
3932 master_params_len = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS); | |
3933 } else { | |
3934 /* prfHashMechanism is not relevant with this PRF */ | |
3935 master_params_len = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS); | |
3936 } | |
3937 | |
3938 params.data = (unsigned char *)&master_params; | |
3939 params.len = master_params_len; | |
3940 | |
3941 return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive, | |
3942 pms_version_ptr, ¶ms, | |
3943 keyFlags, pms, msp); | |
3944 } | |
3945 | |
3946 /* Compute the draft-ietf-tls-session-hash master | |
3947 ** secret and return it in |*msp|. | |
3948 ** | |
3949 ** Called from: ssl3_ComputeMasterSecret | |
3950 */ | |
3951 static SECStatus | |
3952 tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms, | |
3953 PK11SymKey **msp) | |
3954 { | |
3955 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; | |
3956 CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS extended_master_params; | |
3957 SSL3Hashes hashes; | |
3958 /* | |
3959 * Determine whether to use the DH/ECDH or RSA derivation modes. | |
3960 */ | |
3961 /* | |
3962 * TODO(ekr@rtfm.com): Verify that the slot can handle this key expansion | |
3963 * mode. Bug 1198298 */ | |
3964 PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) || | |
3965 (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh)); | |
3966 CK_MECHANISM_TYPE master_derive; | |
3967 CK_MECHANISM_TYPE key_derive; | |
3968 SECItem params; | |
3969 const CK_FLAGS keyFlags = CKF_SIGN | CKF_VERIFY; | |
3970 CK_VERSION pms_version; | |
3971 CK_VERSION *pms_version_ptr = NULL; | |
3972 SECStatus rv; | |
3973 | |
3974 rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0); | |
3975 if (rv != SECSuccess) { | |
3976 PORT_Assert(0); /* Should never fail */ | |
3977 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); | |
3978 return SECFailure; | |
3979 } | |
3980 | |
3981 if (isDH) { | |
3982 master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH; | |
3983 } else { | |
3984 master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE; | |
3985 pms_version_ptr = &pms_version; | |
3986 } | |
3987 | |
3988 if (pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
3989 /* TLS 1.2 */ | |
3990 extended_master_params.prfHashMechanism = CKM_SHA256; | |
3991 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; | |
3992 } else { | |
3993 /* TLS < 1.2 */ | |
3994 extended_master_params.prfHashMechanism = CKM_TLS_PRF; | |
3995 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; | |
3996 } | |
3997 | |
3998 extended_master_params.pVersion = pms_version_ptr; | |
3999 extended_master_params.pSessionHash = hashes.u.raw; | |
4000 extended_master_params.ulSessionHashLen = hashes.len; | |
4001 | |
4002 params.data = (unsigned char *)&extended_master_params; | |
4003 params.len = sizeof extended_master_params; | |
4004 | |
4005 return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive, | |
4006 pms_version_ptr, ¶ms, | |
4007 keyFlags, pms, msp); | |
4008 } | |
4009 | |
4010 /* Wrapper method to compute the master secret and return it in |*msp|. | |
4011 ** | |
4012 ** Called from ssl3_ComputeMasterSecret | |
4013 */ | |
4014 static SECStatus | |
4015 ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms, | |
4016 PK11SymKey **msp) | |
4017 { | |
4018 PORT_Assert(pms != NULL); | |
4019 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
4020 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
4021 | |
4022 if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { | |
4023 return tls_ComputeExtendedMasterSecretInt(ss, pms, msp); | |
4024 } else { | |
4025 return ssl3_ComputeMasterSecretInt(ss, pms, msp); | |
4026 } | |
4027 } | |
4028 | |
4029 /* This method uses PKCS11 to derive the MS from the PMS, where PMS | |
4030 ** is a PKCS11 symkey. We call ssl3_ComputeMasterSecret to do the | |
4031 ** computations and then modify the pwSpec->state as a side effect. | |
4032 ** | |
4033 ** This is used in all cases except the "triple bypass" with RSA key | |
4034 ** exchange. | |
4035 ** | |
4036 ** Called from ssl3_InitPendingCipherSpec. prSpec is pwSpec. | |
4037 */ | |
4038 static SECStatus | |
4039 ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms) | |
4040 { | |
4041 SECStatus rv; | |
4042 PK11SymKey *ms = NULL; | |
4043 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; | |
4044 | |
4045 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
4046 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); | |
4047 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
4048 | |
4049 if (pms) { | |
4050 rv = ssl3_ComputeMasterSecret(ss, pms, &ms); | |
4051 pwSpec->master_secret = ms; | |
4052 if (rv != SECSuccess) | |
4053 return rv; | |
4054 } | |
4055 | |
4056 #ifndef NO_PKCS11_BYPASS | |
4057 if (ss->opt.bypassPKCS11) { | |
4058 SECItem *keydata; | |
4059 /* In hope of doing a "double bypass", | |
4060 * need to extract the master secret's value from the key object | |
4061 * and store it raw in the sslSocket struct. | |
4062 */ | |
4063 rv = PK11_ExtractKeyValue(pwSpec->master_secret); | |
4064 if (rv != SECSuccess) { | |
4065 return rv; | |
4066 } | |
4067 /* This returns the address of the secItem inside the key struct, | |
4068 * not a copy or a reference. So, there's no need to free it. | |
4069 */ | |
4070 keydata = PK11_GetKeyData(pwSpec->master_secret); | |
4071 if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) { | |
4072 memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len); | |
4073 pwSpec->msItem.data = pwSpec->raw_master_secret; | |
4074 pwSpec->msItem.len = keydata->len; | |
4075 } else { | |
4076 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
4077 return SECFailure; | |
4078 } | |
4079 } | |
4080 #endif | |
4081 | |
4082 return SECSuccess; | |
4083 } | |
4084 | |
4085 /* | |
4086 * Derive encryption and MAC Keys (and IVs) from master secret | |
4087 * Sets a useful error code when returning SECFailure. | |
4088 * | |
4089 * Called only from ssl3_InitPendingCipherSpec(), | |
4090 * which in turn is called from | |
4091 * sendRSAClientKeyExchange (for Full handshake) | |
4092 * sendDHClientKeyExchange (for Full handshake) | |
4093 * ssl3_HandleClientKeyExchange (for Full handshake) | |
4094 * ssl3_HandleServerHello (for session restart) | |
4095 * ssl3_HandleClientHello (for session restart) | |
4096 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock. | |
4097 * ssl3_InitPendingCipherSpec does that. | |
4098 * | |
4099 */ | |
4100 static SECStatus | |
4101 ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss) | |
4102 { | |
4103 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; | |
4104 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; | |
4105 unsigned char *cr = (unsigned char *)&ss->ssl3.hs.client_random; | |
4106 unsigned char *sr = (unsigned char *)&ss->ssl3.hs.server_random; | |
4107 PRBool isTLS = (PRBool)(kea_def->tls_keygen || | |
4108 (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); | |
4109 PRBool isTLS12 = | |
4110 (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
4111 /* following variables used in PKCS11 path */ | |
4112 const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def; | |
4113 PK11SlotInfo *slot = NULL; | |
4114 PK11SymKey *symKey = NULL; | |
4115 void *pwArg = ss->pkcs11PinArg; | |
4116 int keySize; | |
4117 CK_TLS12_KEY_MAT_PARAMS key_material_params; /* may be used as a | |
4118 * CK_SSL3_KEY_MAT_PARAMS */ | |
4119 unsigned int key_material_params_len; | |
4120 CK_SSL3_KEY_MAT_OUT returnedKeys; | |
4121 CK_MECHANISM_TYPE key_derive; | |
4122 CK_MECHANISM_TYPE bulk_mechanism; | |
4123 SSLCipherAlgorithm calg; | |
4124 SECItem params; | |
4125 PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null); | |
4126 | |
4127 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
4128 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); | |
4129 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
4130 | |
4131 if (!pwSpec->master_secret) { | |
4132 PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); | |
4133 return SECFailure; | |
4134 } | |
4135 /* | |
4136 * generate the key material | |
4137 */ | |
4138 key_material_params.ulMacSizeInBits = pwSpec->mac_size * BPB; | |
4139 key_material_params.ulKeySizeInBits = cipher_def->secret_key_size * BPB; | |
4140 key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB; | |
4141 if (cipher_def->type == type_block && | |
4142 pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { | |
4143 /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */ | |
4144 key_material_params.ulIVSizeInBits = 0; | |
4145 memset(pwSpec->client.write_iv, 0, cipher_def->iv_size); | |
4146 memset(pwSpec->server.write_iv, 0, cipher_def->iv_size); | |
4147 } | |
4148 | |
4149 key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited); | |
4150 | |
4151 key_material_params.RandomInfo.pClientRandom = cr; | |
4152 key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; | |
4153 key_material_params.RandomInfo.pServerRandom = sr; | |
4154 key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; | |
4155 key_material_params.pReturnedKeyMaterial = &returnedKeys; | |
4156 | |
4157 returnedKeys.pIVClient = pwSpec->client.write_iv; | |
4158 returnedKeys.pIVServer = pwSpec->server.write_iv; | |
4159 keySize = cipher_def->key_size; | |
4160 | |
4161 if (skipKeysAndIVs) { | |
4162 keySize = 0; | |
4163 key_material_params.ulKeySizeInBits = 0; | |
4164 key_material_params.ulIVSizeInBits = 0; | |
4165 returnedKeys.pIVClient = NULL; | |
4166 returnedKeys.pIVServer = NULL; | |
4167 } | |
4168 | |
4169 calg = cipher_def->calg; | |
4170 bulk_mechanism = ssl3_Alg2Mech(calg); | |
4171 | |
4172 if (isTLS12) { | |
4173 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; | |
4174 key_material_params.prfHashMechanism = CKM_SHA256; | |
4175 key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS); | |
4176 } else if (isTLS) { | |
4177 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; | |
4178 key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS); | |
4179 } else { | |
4180 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; | |
4181 key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS); | |
4182 } | |
4183 | |
4184 params.data = (unsigned char *)&key_material_params; | |
4185 params.len = key_material_params_len; | |
4186 | |
4187 /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and | |
4188 * DERIVE by DEFAULT */ | |
4189 symKey = PK11_Derive(pwSpec->master_secret, key_derive, ¶ms, | |
4190 bulk_mechanism, CKA_ENCRYPT, keySize); | |
4191 if (!symKey) { | |
4192 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); | |
4193 return SECFailure; | |
4194 } | |
4195 /* we really should use the actual mac'ing mechanism here, but we | |
4196 * don't because these types are used to map keytype anyway and both | |
4197 * mac's map to the same keytype. | |
4198 */ | |
4199 slot = PK11_GetSlotFromKey(symKey); | |
4200 | |
4201 PK11_FreeSlot(slot); /* slot is held until the key is freed */ | |
4202 pwSpec->client.write_mac_key = | |
4203 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, | |
4204 CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret,
PR_TRUE, pwArg); | |
4205 if (pwSpec->client.write_mac_key == NULL) { | |
4206 goto loser; /* loser sets err */ | |
4207 } | |
4208 pwSpec->server.write_mac_key = | |
4209 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, | |
4210 CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret,
PR_TRUE, pwArg); | |
4211 if (pwSpec->server.write_mac_key == NULL) { | |
4212 goto loser; /* loser sets err */ | |
4213 } | |
4214 if (!skipKeysAndIVs) { | |
4215 pwSpec->client.write_key = | |
4216 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, | |
4217 bulk_mechanism, returnedKeys.hClientKey, PR_TR
UE, pwArg); | |
4218 if (pwSpec->client.write_key == NULL) { | |
4219 goto loser; /* loser sets err */ | |
4220 } | |
4221 pwSpec->server.write_key = | |
4222 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, | |
4223 bulk_mechanism, returnedKeys.hServerKey, PR_TR
UE, pwArg); | |
4224 if (pwSpec->server.write_key == NULL) { | |
4225 goto loser; /* loser sets err */ | |
4226 } | |
4227 } | |
4228 PK11_FreeSymKey(symKey); | |
4229 return SECSuccess; | |
4230 | |
4231 loser: | |
4232 if (symKey) | |
4233 PK11_FreeSymKey(symKey); | |
4234 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); | |
4235 return SECFailure; | |
4236 } | |
4237 | |
4238 /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in | |
4239 * buffered messages in ss->ssl3.hs.messages. */ | |
4240 static SECStatus | |
4241 ssl3_InitHandshakeHashes(sslSocket *ss) | |
4242 { | |
4243 SSL_TRC(30, ("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd)); | |
4244 | |
4245 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown); | |
4246 #ifndef NO_PKCS11_BYPASS | |
4247 if (ss->opt.bypassPKCS11) { | |
4248 PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone); | |
4249 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
4250 /* If we ever support ciphersuites where the PRF hash isn't SHA-256 | |
4251 * then this will need to be updated. */ | |
4252 ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256); | |
4253 if (!ss->ssl3.hs.sha_obj) { | |
4254 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
4255 return SECFailure; | |
4256 } | |
4257 ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone; | |
4258 ss->ssl3.hs.hashType = handshake_hash_single; | |
4259 ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx); | |
4260 } else { | |
4261 ss->ssl3.hs.hashType = handshake_hash_combo; | |
4262 MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx); | |
4263 SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx); | |
4264 } | |
4265 } else | |
4266 #endif | |
4267 { | |
4268 PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha); | |
4269 /* | |
4270 * note: We should probably lookup an SSL3 slot for these | |
4271 * handshake hashes in hopes that we wind up with the same slots | |
4272 * that the master secret will wind up in ... | |
4273 */ | |
4274 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
4275 /* If we ever support ciphersuites where the PRF hash isn't SHA-256 | |
4276 * then this will need to be updated. */ | |
4277 ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256); | |
4278 if (ss->ssl3.hs.sha == NULL) { | |
4279 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4280 return SECFailure; | |
4281 } | |
4282 ss->ssl3.hs.hashType = handshake_hash_single; | |
4283 | |
4284 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { | |
4285 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
4286 return SECFailure; | |
4287 } | |
4288 | |
4289 /* Create a backup SHA-1 hash for a potential client auth | |
4290 * signature. | |
4291 * | |
4292 * In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the | |
4293 * handshake hash function (SHA-256). If the server or the client | |
4294 * does not support SHA-256 as a signature hash, we can either | |
4295 * maintain a backup SHA-1 handshake hash or buffer all handshake | |
4296 * messages. | |
4297 */ | |
4298 if (!ss->sec.isServer) { | |
4299 ss->ssl3.hs.backupHash = PK11_CreateDigestContext(SEC_OID_SHA1); | |
4300 if (ss->ssl3.hs.backupHash == NULL) { | |
4301 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4302 return SECFailure; | |
4303 } | |
4304 | |
4305 if (PK11_DigestBegin(ss->ssl3.hs.backupHash) != SECSuccess) { | |
4306 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4307 return SECFailure; | |
4308 } | |
4309 } | |
4310 } else { | |
4311 /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or | |
4312 * created successfully. */ | |
4313 ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5); | |
4314 if (ss->ssl3.hs.md5 == NULL) { | |
4315 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
4316 return SECFailure; | |
4317 } | |
4318 ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1); | |
4319 if (ss->ssl3.hs.sha == NULL) { | |
4320 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); | |
4321 ss->ssl3.hs.md5 = NULL; | |
4322 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4323 return SECFailure; | |
4324 } | |
4325 ss->ssl3.hs.hashType = handshake_hash_combo; | |
4326 | |
4327 if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) { | |
4328 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
4329 return SECFailure; | |
4330 } | |
4331 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { | |
4332 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4333 return SECFailure; | |
4334 } | |
4335 } | |
4336 } | |
4337 | |
4338 if (ss->ssl3.hs.messages.len > 0) { | |
4339 if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf, | |
4340 ss->ssl3.hs.messages.len) != | |
4341 SECSuccess) { | |
4342 return SECFailure; | |
4343 } | |
4344 PORT_Free(ss->ssl3.hs.messages.buf); | |
4345 ss->ssl3.hs.messages.buf = NULL; | |
4346 ss->ssl3.hs.messages.len = 0; | |
4347 ss->ssl3.hs.messages.space = 0; | |
4348 } | |
4349 | |
4350 return SECSuccess; | |
4351 } | |
4352 | |
4353 static SECStatus | |
4354 ssl3_RestartHandshakeHashes(sslSocket *ss) | |
4355 { | |
4356 SECStatus rv = SECSuccess; | |
4357 | |
4358 SSL_TRC(30, ("%d: SSL3[%d]: reset handshake hashes", | |
4359 SSL_GETPID(), ss->fd)); | |
4360 ss->ssl3.hs.hashType = handshake_hash_unknown; | |
4361 ss->ssl3.hs.messages.len = 0; | |
4362 #ifndef NO_PKCS11_BYPASS | |
4363 ss->ssl3.hs.sha_obj = NULL; | |
4364 ss->ssl3.hs.sha_clone = NULL; | |
4365 #endif | |
4366 if (ss->ssl3.hs.md5) { | |
4367 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); | |
4368 ss->ssl3.hs.md5 = NULL; | |
4369 } | |
4370 if (ss->ssl3.hs.sha) { | |
4371 PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE); | |
4372 ss->ssl3.hs.sha = NULL; | |
4373 } | |
4374 return rv; | |
4375 } | |
4376 | |
4377 /* | |
4378 * Handshake messages | |
4379 */ | |
4380 /* Called from ssl3_InitHandshakeHashes() | |
4381 ** ssl3_AppendHandshake() | |
4382 ** ssl3_StartHandshakeHash() | |
4383 ** ssl3_HandleV2ClientHello() | |
4384 ** ssl3_HandleHandshakeMessage() | |
4385 ** Caller must hold the ssl3Handshake lock. | |
4386 */ | |
4387 static SECStatus | |
4388 ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, | |
4389 unsigned int l) | |
4390 { | |
4391 SECStatus rv = SECSuccess; | |
4392 | |
4393 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
4394 | |
4395 /* We need to buffer the handshake messages until we have established | |
4396 * which handshake hash function to use. */ | |
4397 if (ss->ssl3.hs.hashType == handshake_hash_unknown) { | |
4398 return sslBuffer_Append(&ss->ssl3.hs.messages, b, l); | |
4399 } | |
4400 | |
4401 PRINT_BUF(90, (NULL, "handshake hash input:", b, l)); | |
4402 | |
4403 #ifndef NO_PKCS11_BYPASS | |
4404 if (ss->opt.bypassPKCS11) { | |
4405 if (ss->ssl3.hs.hashType == handshake_hash_single) { | |
4406 ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l); | |
4407 } else { | |
4408 MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l); | |
4409 SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l); | |
4410 } | |
4411 return rv; | |
4412 } | |
4413 #endif | |
4414 if (ss->ssl3.hs.hashType == handshake_hash_single) { | |
4415 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); | |
4416 if (rv != SECSuccess) { | |
4417 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
4418 return rv; | |
4419 } | |
4420 if (ss->ssl3.hs.backupHash) { | |
4421 rv = PK11_DigestOp(ss->ssl3.hs.backupHash, b, l); | |
4422 if (rv != SECSuccess) { | |
4423 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4424 return rv; | |
4425 } | |
4426 } | |
4427 } else { | |
4428 rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l); | |
4429 if (rv != SECSuccess) { | |
4430 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
4431 return rv; | |
4432 } | |
4433 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); | |
4434 if (rv != SECSuccess) { | |
4435 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
4436 return rv; | |
4437 } | |
4438 } | |
4439 return rv; | |
4440 } | |
4441 | |
4442 /************************************************************************** | |
4443 * Append Handshake functions. | |
4444 * All these functions set appropriate error codes. | |
4445 * Most rely on ssl3_AppendHandshake to set the error code. | |
4446 **************************************************************************/ | |
4447 SECStatus | |
4448 ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes) | |
4449 { | |
4450 unsigned char *src = (unsigned char *)void_src; | |
4451 int room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; | |
4452 SECStatus rv; | |
4453 | |
4454 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); /* protects s
endBuf. */ | |
4455 | |
4456 if (!bytes) | |
4457 return SECSuccess; | |
4458 if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) { | |
4459 rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH, | |
4460 PR_MIN(MAX_SEND_BUF_LENG
TH, ss->sec.ci.sendBuf.len + bytes))); | |
4461 if (rv != SECSuccess) | |
4462 return rv; /* sslBuffer_Grow has set a memory error code. */ | |
4463 room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; | |
4464 } | |
4465 | |
4466 PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char *)void_src, bytes))
; | |
4467 rv = ssl3_UpdateHandshakeHashes(ss, src, bytes); | |
4468 if (rv != SECSuccess) | |
4469 return rv; /* error code set by ssl3_UpdateHandshakeHashes */ | |
4470 | |
4471 while (bytes > room) { | |
4472 if (room > 0) | |
4473 PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, | |
4474 room); | |
4475 ss->sec.ci.sendBuf.len += room; | |
4476 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); | |
4477 if (rv != SECSuccess) { | |
4478 return rv; /* error code set by ssl3_FlushHandshake */ | |
4479 } | |
4480 bytes -= room; | |
4481 src += room; | |
4482 room = ss->sec.ci.sendBuf.space; | |
4483 PORT_Assert(ss->sec.ci.sendBuf.len == 0); | |
4484 } | |
4485 PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes); | |
4486 ss->sec.ci.sendBuf.len += bytes; | |
4487 return SECSuccess; | |
4488 } | |
4489 | |
4490 SECStatus | |
4491 ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize) | |
4492 { | |
4493 SECStatus rv; | |
4494 PRUint8 b[4]; | |
4495 PRUint8 *p = b; | |
4496 | |
4497 PORT_Assert(lenSize <= 4 && lenSize > 0); | |
4498 if (lenSize < 4 && num >= (1L << (lenSize * 8))) { | |
4499 PORT_SetError(SSL_ERROR_TX_RECORD_TOO_LONG); | |
4500 return SECFailure; | |
4501 } | |
4502 | |
4503 switch (lenSize) { | |
4504 case 4: | |
4505 *p++ = (num >> 24) & 0xff; | |
4506 case 3: | |
4507 *p++ = (num >> 16) & 0xff; | |
4508 case 2: | |
4509 *p++ = (num >> 8) & 0xff; | |
4510 case 1: | |
4511 *p = num & 0xff; | |
4512 } | |
4513 SSL_TRC(60, ("%d: number:", SSL_GETPID())); | |
4514 rv = ssl3_AppendHandshake(ss, &b[0], lenSize); | |
4515 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4516 } | |
4517 | |
4518 SECStatus | |
4519 ssl3_AppendHandshakeVariable( | |
4520 sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize) | |
4521 { | |
4522 SECStatus rv; | |
4523 | |
4524 PORT_Assert((bytes < (1 << 8) && lenSize == 1) || | |
4525 (bytes < (1L << 16) && lenSize == 2) || | |
4526 (bytes < (1L << 24) && lenSize == 3)); | |
4527 | |
4528 SSL_TRC(60, ("%d: append variable:", SSL_GETPID())); | |
4529 rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize); | |
4530 if (rv != SECSuccess) { | |
4531 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4532 } | |
4533 SSL_TRC(60, ("data:")); | |
4534 rv = ssl3_AppendHandshake(ss, src, bytes); | |
4535 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4536 } | |
4537 | |
4538 SECStatus | |
4539 ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length) | |
4540 { | |
4541 SECStatus rv; | |
4542 | |
4543 /* If we already have a message in place, we need to enqueue it. | |
4544 * This empties the buffer. This is a convenient place to call | |
4545 * dtls_StageHandshakeMessage to mark the message boundary. | |
4546 */ | |
4547 if (IS_DTLS(ss)) { | |
4548 rv = dtls_StageHandshakeMessage(ss); | |
4549 if (rv != SECSuccess) { | |
4550 return rv; | |
4551 } | |
4552 } | |
4553 | |
4554 SSL_TRC(30, ("%d: SSL3[%d]: append handshake header: type %s", | |
4555 SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t))); | |
4556 | |
4557 rv = ssl3_AppendHandshakeNumber(ss, t, 1); | |
4558 if (rv != SECSuccess) { | |
4559 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4560 } | |
4561 rv = ssl3_AppendHandshakeNumber(ss, length, 3); | |
4562 if (rv != SECSuccess) { | |
4563 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4564 } | |
4565 | |
4566 if (IS_DTLS(ss)) { | |
4567 /* Note that we make an unfragmented message here. We fragment in the | |
4568 * transmission code, if necessary */ | |
4569 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2); | |
4570 if (rv != SECSuccess) { | |
4571 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4572 } | |
4573 ss->ssl3.hs.sendMessageSeq++; | |
4574 | |
4575 /* 0 is the fragment offset, because it's not fragmented yet */ | |
4576 rv = ssl3_AppendHandshakeNumber(ss, 0, 3); | |
4577 if (rv != SECSuccess) { | |
4578 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4579 } | |
4580 | |
4581 /* Fragment length -- set to the packet length because not fragmented */ | |
4582 rv = ssl3_AppendHandshakeNumber(ss, length, 3); | |
4583 if (rv != SECSuccess) { | |
4584 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4585 } | |
4586 } | |
4587 | |
4588 return rv; /* error code set by AppendHandshake, if applicable. */ | |
4589 } | |
4590 | |
4591 /* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of | |
4592 * |sigAndHash| to the current handshake message. */ | |
4593 SECStatus | |
4594 ssl3_AppendSignatureAndHashAlgorithm( | |
4595 sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash) | |
4596 { | |
4597 PRUint8 serialized[2]; | |
4598 | |
4599 serialized[0] = (PRUint8)sigAndHash->hashAlg; | |
4600 serialized[1] = (PRUint8)sigAndHash->sigAlg; | |
4601 | |
4602 return ssl3_AppendHandshake(ss, serialized, sizeof(serialized)); | |
4603 } | |
4604 | |
4605 /************************************************************************** | |
4606 * Consume Handshake functions. | |
4607 * | |
4608 * All data used in these functions is protected by two locks, | |
4609 * the RecvBufLock and the SSL3HandshakeLock | |
4610 **************************************************************************/ | |
4611 | |
4612 /* Read up the next "bytes" number of bytes from the (decrypted) input | |
4613 * stream "b" (which is *length bytes long). Copy them into buffer "v". | |
4614 * Reduces *length by bytes. Advances *b by bytes. | |
4615 * | |
4616 * If this function returns SECFailure, it has already sent an alert, | |
4617 * and has set a generic error code. The caller should probably | |
4618 * override the generic error code by setting another. | |
4619 */ | |
4620 SECStatus | |
4621 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b, | |
4622 PRUint32 *length) | |
4623 { | |
4624 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
4625 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
4626 | |
4627 if ((PRUint32)bytes > *length) { | |
4628 return ssl3_DecodeError(ss); | |
4629 } | |
4630 PORT_Memcpy(v, *b, bytes); | |
4631 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); | |
4632 *b += bytes; | |
4633 *length -= bytes; | |
4634 return SECSuccess; | |
4635 } | |
4636 | |
4637 /* Read up the next "bytes" number of bytes from the (decrypted) input | |
4638 * stream "b" (which is *length bytes long), and interpret them as an | |
4639 * integer in network byte order. Returns the received value. | |
4640 * Reduces *length by bytes. Advances *b by bytes. | |
4641 * | |
4642 * Returns SECFailure (-1) on failure. | |
4643 * This value is indistinguishable from the equivalent received value. | |
4644 * Only positive numbers are to be received this way. | |
4645 * Thus, the largest value that may be sent this way is 0x7fffffff. | |
4646 * On error, an alert has been sent, and a generic error code has been set. | |
4647 */ | |
4648 PRInt32 | |
4649 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b, | |
4650 PRUint32 *length) | |
4651 { | |
4652 PRUint8 *buf = *b; | |
4653 int i; | |
4654 PRInt32 num = 0; | |
4655 | |
4656 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
4657 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
4658 PORT_Assert(bytes <= sizeof num); | |
4659 | |
4660 if ((PRUint32)bytes > *length) { | |
4661 return ssl3_DecodeError(ss); | |
4662 } | |
4663 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); | |
4664 | |
4665 for (i = 0; i < bytes; i++) | |
4666 num = (num << 8) + buf[i]; | |
4667 *b += bytes; | |
4668 *length -= bytes; | |
4669 return num; | |
4670 } | |
4671 | |
4672 /* Read in two values from the incoming decrypted byte stream "b", which is | |
4673 * *length bytes long. The first value is a number whose size is "bytes" | |
4674 * bytes long. The second value is a byte-string whose size is the value | |
4675 * of the first number received. The latter byte-string, and its length, | |
4676 * is returned in the SECItem i. | |
4677 * | |
4678 * Returns SECFailure (-1) on failure. | |
4679 * On error, an alert has been sent, and a generic error code has been set. | |
4680 * | |
4681 * RADICAL CHANGE for NSS 3.11. All callers of this function make copies | |
4682 * of the data returned in the SECItem *i, so making a copy of it here | |
4683 * is simply wasteful. So, This function now just sets SECItem *i to | |
4684 * point to the values in the buffer **b. | |
4685 */ | |
4686 SECStatus | |
4687 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes, | |
4688 SSL3Opaque **b, PRUint32 *length) | |
4689 { | |
4690 PRInt32 count; | |
4691 | |
4692 PORT_Assert(bytes <= 3); | |
4693 i->len = 0; | |
4694 i->data = NULL; | |
4695 i->type = siBuffer; | |
4696 count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length); | |
4697 if (count < 0) { /* Can't test for SECSuccess here. */ | |
4698 return SECFailure; | |
4699 } | |
4700 if (count > 0) { | |
4701 if ((PRUint32)count > *length) { | |
4702 return ssl3_DecodeError(ss); | |
4703 } | |
4704 i->data = *b; | |
4705 i->len = count; | |
4706 *b += count; | |
4707 *length -= count; | |
4708 } | |
4709 return SECSuccess; | |
4710 } | |
4711 | |
4712 /* tlsHashOIDMap contains the mapping between TLS hash identifiers and the | |
4713 * SECOidTag used internally by NSS. */ | |
4714 static const struct { | |
4715 SSLHashType tlsHash; | |
4716 SECOidTag oid; | |
4717 } tlsHashOIDMap[] = { | |
4718 { ssl_hash_sha1, SEC_OID_SHA1 }, | |
4719 { ssl_hash_sha256, SEC_OID_SHA256 }, | |
4720 { ssl_hash_sha384, SEC_OID_SHA384 }, | |
4721 { ssl_hash_sha512, SEC_OID_SHA512 } | |
4722 }; | |
4723 | |
4724 /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value. | |
4725 * If the hash is not recognised, SEC_OID_UNKNOWN is returned. | |
4726 * | |
4727 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ | |
4728 SECOidTag | |
4729 ssl3_TLSHashAlgorithmToOID(SSLHashType hashFunc) | |
4730 { | |
4731 unsigned int i; | |
4732 | |
4733 for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) { | |
4734 if (hashFunc == tlsHashOIDMap[i].tlsHash) { | |
4735 return tlsHashOIDMap[i].oid; | |
4736 } | |
4737 } | |
4738 return SEC_OID_UNKNOWN; | |
4739 } | |
4740 | |
4741 /* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm | |
4742 * identifier for a given KeyType. */ | |
4743 static SECStatus | |
4744 ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType, SSLSignType *out) | |
4745 { | |
4746 switch (keyType) { | |
4747 case rsaKey: | |
4748 *out = ssl_sign_rsa; | |
4749 return SECSuccess; | |
4750 case dsaKey: | |
4751 *out = ssl_sign_dsa; | |
4752 return SECSuccess; | |
4753 case ecKey: | |
4754 *out = ssl_sign_ecdsa; | |
4755 return SECSuccess; | |
4756 default: | |
4757 PORT_SetError(SEC_ERROR_INVALID_KEY); | |
4758 return SECFailure; | |
4759 } | |
4760 } | |
4761 | |
4762 /* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature | |
4763 * algorithm identifier for the given certificate. */ | |
4764 static SECStatus | |
4765 ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert, | |
4766 SSLSignType *out) | |
4767 { | |
4768 SECKEYPublicKey *key; | |
4769 KeyType keyType; | |
4770 | |
4771 key = CERT_ExtractPublicKey(cert); | |
4772 if (key == NULL) { | |
4773 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); | |
4774 return SECFailure; | |
4775 } | |
4776 | |
4777 keyType = key->keyType; | |
4778 SECKEY_DestroyPublicKey(key); | |
4779 return ssl3_TLSSignatureAlgorithmForKeyType(keyType, out); | |
4780 } | |
4781 | |
4782 /* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature | |
4783 * algorithm identifier in |sigAndHash| is consistent with the public key in | |
4784 * |cert|. It also checks the hash algorithm against the configured signature | |
4785 * algorithms. If all the tests pass, SECSuccess is returned. Otherwise, | |
4786 * PORT_SetError is called and SECFailure is returned. */ | |
4787 SECStatus | |
4788 ssl3_CheckSignatureAndHashAlgorithmConsistency( | |
4789 sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash, | |
4790 CERTCertificate *cert) | |
4791 { | |
4792 SECStatus rv; | |
4793 SSLSignType sigAlg; | |
4794 unsigned int i; | |
4795 | |
4796 /* If we're a client, check that the signature algorithm matches the signing | |
4797 * key type of the cipher suite. */ | |
4798 if (!ss->sec.isServer && | |
4799 ss->ssl3.hs.kea_def->signKeyType != sigAndHash->sigAlg) { | |
4800 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM); | |
4801 return SECFailure; | |
4802 } | |
4803 | |
4804 /* Verify that the signature algorithm used for the | |
4805 * signature matches the signing key. */ | |
4806 rv = ssl3_TLSSignatureAlgorithmForCertificate(cert, &sigAlg); | |
4807 if (rv != SECSuccess) { | |
4808 return rv; | |
4809 } | |
4810 if (sigAlg != sigAndHash->sigAlg) { | |
4811 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM); | |
4812 return SECFailure; | |
4813 } | |
4814 | |
4815 for (i = 0; i < ss->ssl3.signatureAlgorithmCount; ++i) { | |
4816 const SSLSignatureAndHashAlg *alg = &ss->ssl3.signatureAlgorithms[i]; | |
4817 if (sigAndHash->sigAlg == alg->sigAlg && | |
4818 sigAndHash->hashAlg == alg->hashAlg) { | |
4819 return SECSuccess; | |
4820 } | |
4821 } | |
4822 PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); | |
4823 return SECFailure; | |
4824 } | |
4825 | |
4826 PRBool | |
4827 ssl3_IsSupportedSignatureAlgorithm(const SSLSignatureAndHashAlg *alg) | |
4828 { | |
4829 static const SSLHashType supportedHashes[] = { | |
4830 ssl_hash_sha1, | |
4831 ssl_hash_sha256, | |
4832 ssl_hash_sha384, | |
4833 ssl_hash_sha512 | |
4834 }; | |
4835 | |
4836 static const SSLSignType supportedSigAlgs[] = { | |
4837 ssl_sign_rsa, | |
4838 #ifndef NSS_DISABLE_ECC | |
4839 ssl_sign_ecdsa, | |
4840 #endif | |
4841 ssl_sign_dsa | |
4842 }; | |
4843 | |
4844 unsigned int i; | |
4845 PRBool hashOK = PR_FALSE; | |
4846 PRBool signOK = PR_FALSE; | |
4847 | |
4848 for (i = 0; i < PR_ARRAY_SIZE(supportedHashes); ++i) { | |
4849 if (alg->hashAlg == supportedHashes[i]) { | |
4850 hashOK = PR_TRUE; | |
4851 break; | |
4852 } | |
4853 } | |
4854 | |
4855 for (i = 0; i < PR_ARRAY_SIZE(supportedSigAlgs); ++i) { | |
4856 if (alg->sigAlg == supportedSigAlgs[i]) { | |
4857 signOK = PR_TRUE; | |
4858 break; | |
4859 } | |
4860 } | |
4861 | |
4862 return hashOK && signOK; | |
4863 } | |
4864 | |
4865 /* ssl3_ConsumeSignatureAndHashAlgorithm reads a SignatureAndHashAlgorithm | |
4866 * structure from |b| and puts the resulting value into |out|. |b| and |length| | |
4867 * are updated accordingly. | |
4868 * | |
4869 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ | |
4870 SECStatus | |
4871 ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss, | |
4872 SSL3Opaque **b, | |
4873 PRUint32 *length, | |
4874 SSLSignatureAndHashAlg *out) | |
4875 { | |
4876 PRUint8 bytes[2]; | |
4877 SECStatus rv; | |
4878 | |
4879 rv = ssl3_ConsumeHandshake(ss, bytes, sizeof(bytes), b, length); | |
4880 if (rv != SECSuccess) { | |
4881 return rv; | |
4882 } | |
4883 | |
4884 out->hashAlg = (SSLHashType)bytes[0]; | |
4885 out->sigAlg = (SSLSignType)bytes[1]; | |
4886 if (!ssl3_IsSupportedSignatureAlgorithm(out)) { | |
4887 PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); | |
4888 return SECFailure; | |
4889 } | |
4890 return SECSuccess; | |
4891 } | |
4892 | |
4893 /************************************************************************** | |
4894 * end of Consume Handshake functions. | |
4895 **************************************************************************/ | |
4896 | |
4897 /* Extract the hashes of handshake messages to this point. | |
4898 * Called from ssl3_SendCertificateVerify | |
4899 * ssl3_SendFinished | |
4900 * ssl3_HandleHandshakeMessage | |
4901 * | |
4902 * Caller must hold the SSL3HandshakeLock. | |
4903 * Caller must hold a read or write lock on the Spec R/W lock. | |
4904 * (There is presently no way to assert on a Read lock.) | |
4905 */ | |
4906 SECStatus | |
4907 ssl3_ComputeHandshakeHashes(sslSocket *ss, | |
4908 ssl3CipherSpec *spec, /* uses ->master_secret */ | |
4909 SSL3Hashes *hashes, /* output goes here. */ | |
4910 PRUint32 sender) | |
4911 { | |
4912 SECStatus rv = SECSuccess; | |
4913 PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0); | |
4914 unsigned int outLength; | |
4915 SSL3Opaque md5_inner[MAX_MAC_LENGTH]; | |
4916 SSL3Opaque sha_inner[MAX_MAC_LENGTH]; | |
4917 | |
4918 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
4919 if (ss->ssl3.hs.hashType == handshake_hash_unknown) { | |
4920 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
4921 return SECFailure; | |
4922 } | |
4923 | |
4924 hashes->hashAlg = ssl_hash_none; | |
4925 | |
4926 #ifndef NO_PKCS11_BYPASS | |
4927 if (ss->opt.bypassPKCS11 && | |
4928 ss->ssl3.hs.hashType == handshake_hash_single) { | |
4929 /* compute them without PKCS11 */ | |
4930 PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; | |
4931 | |
4932 ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx); | |
4933 ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len, | |
4934 sizeof(hashes->u.raw)); | |
4935 | |
4936 PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len)); | |
4937 | |
4938 /* If we ever support ciphersuites where the PRF hash isn't SHA-256 | |
4939 * then this will need to be updated. */ | |
4940 hashes->hashAlg = ssl_hash_sha256; | |
4941 rv = SECSuccess; | |
4942 } else if (ss->opt.bypassPKCS11) { | |
4943 /* compute them without PKCS11 */ | |
4944 PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS]; | |
4945 PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; | |
4946 | |
4947 #define md5cx ((MD5Context *)md5_cx) | |
4948 #define shacx ((SHA1Context *)sha_cx) | |
4949 | |
4950 MD5_Clone(md5cx, (MD5Context *)ss->ssl3.hs.md5_cx); | |
4951 SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx); | |
4952 | |
4953 if (!isTLS) { | |
4954 /* compute hashes for SSL3. */ | |
4955 unsigned char s[4]; | |
4956 | |
4957 if (!spec->msItem.data) { | |
4958 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); | |
4959 return SECFailure; | |
4960 } | |
4961 | |
4962 s[0] = (unsigned char)(sender >> 24); | |
4963 s[1] = (unsigned char)(sender >> 16); | |
4964 s[2] = (unsigned char)(sender >> 8); | |
4965 s[3] = (unsigned char)sender; | |
4966 | |
4967 if (sender != 0) { | |
4968 MD5_Update(md5cx, s, 4); | |
4969 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); | |
4970 } | |
4971 | |
4972 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, | |
4973 mac_defs[mac_md5].pad_size)); | |
4974 | |
4975 MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); | |
4976 MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size); | |
4977 MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH); | |
4978 | |
4979 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); | |
4980 | |
4981 if (sender != 0) { | |
4982 SHA1_Update(shacx, s, 4); | |
4983 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); | |
4984 } | |
4985 | |
4986 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, | |
4987 mac_defs[mac_sha].pad_size)); | |
4988 | |
4989 SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); | |
4990 SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size); | |
4991 SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH); | |
4992 | |
4993 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); | |
4994 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, | |
4995 mac_defs[mac_md5].pad_size)); | |
4996 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH))
; | |
4997 | |
4998 MD5_Begin(md5cx); | |
4999 MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); | |
5000 MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size); | |
5001 MD5_Update(md5cx, md5_inner, MD5_LENGTH); | |
5002 } | |
5003 MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH); | |
5004 | |
5005 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); | |
5006 | |
5007 if (!isTLS) { | |
5008 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, | |
5009 mac_defs[mac_sha].pad_size)); | |
5010 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)
); | |
5011 | |
5012 SHA1_Begin(shacx); | |
5013 SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); | |
5014 SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size); | |
5015 SHA1_Update(shacx, sha_inner, SHA1_LENGTH); | |
5016 } | |
5017 SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH); | |
5018 | |
5019 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH))
; | |
5020 | |
5021 hashes->len = MD5_LENGTH + SHA1_LENGTH; | |
5022 rv = SECSuccess; | |
5023 #undef md5cx | |
5024 #undef shacx | |
5025 } else | |
5026 #endif | |
5027 if (ss->ssl3.hs.hashType == handshake_hash_single) { | |
5028 /* compute hashes with PKCS11 */ | |
5029 PK11Context *h; | |
5030 unsigned int stateLen; | |
5031 unsigned char stackBuf[1024]; | |
5032 unsigned char *stateBuf = NULL; | |
5033 | |
5034 h = ss->ssl3.hs.sha; | |
5035 stateBuf = PK11_SaveContextAlloc(h, stackBuf, | |
5036 sizeof(stackBuf), &stateLen); | |
5037 if (stateBuf == NULL) { | |
5038 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
5039 goto tls12_loser; | |
5040 } | |
5041 rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len, | |
5042 sizeof(hashes->u.raw)); | |
5043 if (rv != SECSuccess) { | |
5044 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
5045 rv = SECFailure; | |
5046 goto tls12_loser; | |
5047 } | |
5048 /* If we ever support ciphersuites where the PRF hash isn't SHA-256 | |
5049 * then this will need to be updated. */ | |
5050 hashes->hashAlg = ssl_hash_sha256; | |
5051 rv = SECSuccess; | |
5052 | |
5053 tls12_loser: | |
5054 if (stateBuf) { | |
5055 if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) { | |
5056 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); | |
5057 rv = SECFailure; | |
5058 } | |
5059 if (stateBuf != stackBuf) { | |
5060 PORT_ZFree(stateBuf, stateLen); | |
5061 } | |
5062 } | |
5063 } else { | |
5064 /* compute hashes with PKCS11 */ | |
5065 PK11Context *md5; | |
5066 PK11Context *sha = NULL; | |
5067 unsigned char *md5StateBuf = NULL; | |
5068 unsigned char *shaStateBuf = NULL; | |
5069 unsigned int md5StateLen, shaStateLen; | |
5070 unsigned char md5StackBuf[256]; | |
5071 unsigned char shaStackBuf[512]; | |
5072 | |
5073 md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf, | |
5074 sizeof md5StackBuf, &md5StateLen); | |
5075 if (md5StateBuf == NULL) { | |
5076 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
5077 goto loser; | |
5078 } | |
5079 md5 = ss->ssl3.hs.md5; | |
5080 | |
5081 shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf, | |
5082 sizeof shaStackBuf, &shaStateLen); | |
5083 if (shaStateBuf == NULL) { | |
5084 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
5085 goto loser; | |
5086 } | |
5087 sha = ss->ssl3.hs.sha; | |
5088 | |
5089 if (!isTLS) { | |
5090 /* compute hashes for SSL3. */ | |
5091 unsigned char s[4]; | |
5092 | |
5093 if (!spec->master_secret) { | |
5094 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); | |
5095 rv = SECFailure; | |
5096 goto loser; | |
5097 } | |
5098 | |
5099 s[0] = (unsigned char)(sender >> 24); | |
5100 s[1] = (unsigned char)(sender >> 16); | |
5101 s[2] = (unsigned char)(sender >> 8); | |
5102 s[3] = (unsigned char)sender; | |
5103 | |
5104 if (sender != 0) { | |
5105 rv |= PK11_DigestOp(md5, s, 4); | |
5106 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); | |
5107 } | |
5108 | |
5109 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, | |
5110 mac_defs[mac_md5].pad_size)); | |
5111 | |
5112 rv |= PK11_DigestKey(md5, spec->master_secret); | |
5113 rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size); | |
5114 rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH); | |
5115 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); | |
5116 if (rv != SECSuccess) { | |
5117 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
5118 rv = SECFailure; | |
5119 goto loser; | |
5120 } | |
5121 | |
5122 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); | |
5123 | |
5124 if (sender != 0) { | |
5125 rv |= PK11_DigestOp(sha, s, 4); | |
5126 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); | |
5127 } | |
5128 | |
5129 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, | |
5130 mac_defs[mac_sha].pad_size)); | |
5131 | |
5132 rv |= PK11_DigestKey(sha, spec->master_secret); | |
5133 rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size); | |
5134 rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH); | |
5135 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); | |
5136 if (rv != SECSuccess) { | |
5137 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
5138 rv = SECFailure; | |
5139 goto loser; | |
5140 } | |
5141 | |
5142 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); | |
5143 | |
5144 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, | |
5145 mac_defs[mac_md5].pad_size)); | |
5146 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH))
; | |
5147 | |
5148 rv |= PK11_DigestBegin(md5); | |
5149 rv |= PK11_DigestKey(md5, spec->master_secret); | |
5150 rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size); | |
5151 rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH); | |
5152 } | |
5153 rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH); | |
5154 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); | |
5155 if (rv != SECSuccess) { | |
5156 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
5157 rv = SECFailure; | |
5158 goto loser; | |
5159 } | |
5160 | |
5161 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); | |
5162 | |
5163 if (!isTLS) { | |
5164 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, | |
5165 mac_defs[mac_sha].pad_size)); | |
5166 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)
); | |
5167 | |
5168 rv |= PK11_DigestBegin(sha); | |
5169 rv |= PK11_DigestKey(sha, spec->master_secret); | |
5170 rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size); | |
5171 rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH); | |
5172 } | |
5173 rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH); | |
5174 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); | |
5175 if (rv != SECSuccess) { | |
5176 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
5177 rv = SECFailure; | |
5178 goto loser; | |
5179 } | |
5180 | |
5181 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH))
; | |
5182 | |
5183 hashes->len = MD5_LENGTH + SHA1_LENGTH; | |
5184 rv = SECSuccess; | |
5185 | |
5186 loser: | |
5187 if (md5StateBuf) { | |
5188 if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) !
= | |
5189 SECSuccess) { | |
5190 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); | |
5191 rv = SECFailure; | |
5192 } | |
5193 if (md5StateBuf != md5StackBuf) { | |
5194 PORT_ZFree(md5StateBuf, md5StateLen); | |
5195 } | |
5196 } | |
5197 if (shaStateBuf) { | |
5198 if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) !
= | |
5199 SECSuccess) { | |
5200 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
5201 rv = SECFailure; | |
5202 } | |
5203 if (shaStateBuf != shaStackBuf) { | |
5204 PORT_ZFree(shaStateBuf, shaStateLen); | |
5205 } | |
5206 } | |
5207 } | |
5208 return rv; | |
5209 } | |
5210 | |
5211 static SECStatus | |
5212 ssl3_ComputeBackupHandshakeHashes(sslSocket *ss, | |
5213 SSL3Hashes *hashes) /* output goes here. */ | |
5214 { | |
5215 SECStatus rv = SECSuccess; | |
5216 | |
5217 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
5218 PORT_Assert(!ss->sec.isServer); | |
5219 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single); | |
5220 | |
5221 rv = PK11_DigestFinal(ss->ssl3.hs.backupHash, hashes->u.raw, &hashes->len, | |
5222 sizeof(hashes->u.raw)); | |
5223 if (rv != SECSuccess) { | |
5224 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); | |
5225 rv = SECFailure; | |
5226 goto loser; | |
5227 } | |
5228 hashes->hashAlg = ssl_hash_sha1; | |
5229 | |
5230 loser: | |
5231 PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); | |
5232 ss->ssl3.hs.backupHash = NULL; | |
5233 return rv; | |
5234 } | |
5235 | |
5236 /* | |
5237 * SSL 2 based implementations pass in the initial outbound buffer | |
5238 * so that the handshake hash can contain the included information. | |
5239 * | |
5240 * Called from ssl2_BeginClientHandshake() in sslcon.c | |
5241 */ | |
5242 SECStatus | |
5243 ssl3_StartHandshakeHash(sslSocket *ss, unsigned char *buf, int length) | |
5244 { | |
5245 SECStatus rv; | |
5246 | |
5247 ssl_GetSSL3HandshakeLock(ss); /**************************************/ | |
5248 | |
5249 rv = ssl3_InitState(ss); | |
5250 if (rv != SECSuccess) { | |
5251 goto done; /* ssl3_InitState has set the error code. */ | |
5252 } | |
5253 rv = ssl3_RestartHandshakeHashes(ss); | |
5254 if (rv != SECSuccess) { | |
5255 goto done; | |
5256 } | |
5257 | |
5258 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); | |
5259 PORT_Memcpy( | |
5260 &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES
], | |
5261 &ss->sec.ci.clientChallenge, | |
5262 SSL_CHALLENGE_BYTES); | |
5263 | |
5264 rv = ssl3_UpdateHandshakeHashes(ss, buf, length); | |
5265 /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */ | |
5266 | |
5267 done: | |
5268 ssl_ReleaseSSL3HandshakeLock(ss); /**************************************/ | |
5269 return rv; | |
5270 } | |
5271 | |
5272 /************************************************************************** | |
5273 * end of Handshake Hash functions. | |
5274 * Begin Send and Handle functions for handshakes. | |
5275 **************************************************************************/ | |
5276 | |
5277 /* Called from ssl3_HandleHelloRequest(), | |
5278 * ssl3_RedoHandshake() | |
5279 * ssl2_BeginClientHandshake (when resuming ssl3 session) | |
5280 * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE) | |
5281 */ | |
5282 SECStatus | |
5283 ssl3_SendClientHello(sslSocket *ss, PRBool resending) | |
5284 { | |
5285 sslSessionID *sid; | |
5286 ssl3CipherSpec *cwSpec; | |
5287 SECStatus rv; | |
5288 int i; | |
5289 int length; | |
5290 int num_suites; | |
5291 int actual_count = 0; | |
5292 PRBool isTLS = PR_FALSE; | |
5293 PRBool requestingResume = PR_FALSE, fallbackSCSV = PR_FALSE; | |
5294 PRInt32 total_exten_len = 0; | |
5295 unsigned paddingExtensionLen; | |
5296 unsigned numCompressionMethods; | |
5297 PRInt32 flags; | |
5298 | |
5299 SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(), | |
5300 ss->fd)); | |
5301 | |
5302 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
5303 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
5304 | |
5305 rv = ssl3_InitState(ss); | |
5306 if (rv != SECSuccess) { | |
5307 return rv; /* ssl3_InitState has set the error code. */ | |
5308 } | |
5309 /* These must be reset every handshake. */ | |
5310 ss->ssl3.hs.sendingSCSV = PR_FALSE; | |
5311 ss->ssl3.hs.preliminaryInfo = 0; | |
5312 PORT_Assert(IS_DTLS(ss) || !resending); | |
5313 | |
5314 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); | |
5315 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; | |
5316 | |
5317 /* We might be starting a session renegotiation in which case we should | |
5318 * clear previous state. | |
5319 */ | |
5320 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); | |
5321 | |
5322 rv = ssl3_RestartHandshakeHashes(ss); | |
5323 if (rv != SECSuccess) { | |
5324 return rv; | |
5325 } | |
5326 | |
5327 /* | |
5328 * During a renegotiation, ss->clientHelloVersion will be used again to | |
5329 * work around a Windows SChannel bug. Ensure that it is still enabled. | |
5330 */ | |
5331 if (ss->firstHsDone) { | |
5332 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { | |
5333 PORT_SetError(SSL_ERROR_SSL_DISABLED); | |
5334 return SECFailure; | |
5335 } | |
5336 | |
5337 if (ss->clientHelloVersion < ss->vrange.min || | |
5338 ss->clientHelloVersion > ss->vrange.max) { | |
5339 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); | |
5340 return SECFailure; | |
5341 } | |
5342 } | |
5343 | |
5344 /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup | |
5345 * handles expired entries and other details. | |
5346 * XXX If we've been called from ssl2_BeginClientHandshake, then | |
5347 * this lookup is duplicative and wasteful. | |
5348 */ | |
5349 sid = (ss->opt.noCache) ? NULL | |
5350 : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, s
s->peerID, ss->url); | |
5351 | |
5352 /* We can't resume based on a different token. If the sid exists, | |
5353 * make sure the token that holds the master secret still exists ... | |
5354 * If we previously did client-auth, make sure that the token that holds | |
5355 * the private key still exists, is logged in, hasn't been removed, etc. | |
5356 */ | |
5357 if (sid) { | |
5358 PRBool sidOK = PR_TRUE; | |
5359 if (sid->u.ssl3.keys.msIsWrapped) { | |
5360 /* Session key was wrapped, which means it was using PKCS11, */ | |
5361 PK11SlotInfo *slot = NULL; | |
5362 if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) { | |
5363 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, | |
5364 sid->u.ssl3.masterSlotID); | |
5365 } | |
5366 if (slot == NULL) { | |
5367 sidOK = PR_FALSE; | |
5368 } else { | |
5369 PK11SymKey *wrapKey = NULL; | |
5370 if (!PK11_IsPresent(slot) || | |
5371 ((wrapKey = PK11_GetWrapKey(slot, | |
5372 sid->u.ssl3.masterWrapIndex, | |
5373 sid->u.ssl3.masterWrapMech, | |
5374 sid->u.ssl3.masterWrapSeries, | |
5375 ss->pkcs11PinArg)) == NULL)) { | |
5376 sidOK = PR_FALSE; | |
5377 } | |
5378 if (wrapKey) | |
5379 PK11_FreeSymKey(wrapKey); | |
5380 PK11_FreeSlot(slot); | |
5381 slot = NULL; | |
5382 } | |
5383 } | |
5384 /* If we previously did client-auth, make sure that the token that | |
5385 ** holds the private key still exists, is logged in, hasn't been | |
5386 ** removed, etc. | |
5387 */ | |
5388 if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) { | |
5389 sidOK = PR_FALSE; | |
5390 } | |
5391 | |
5392 if (sidOK) { | |
5393 /* Set ss->version based on the session cache */ | |
5394 if (ss->firstHsDone) { | |
5395 /* | |
5396 * Windows SChannel compares the client_version inside the RSA | |
5397 * EncryptedPreMasterSecret of a renegotiation with the | |
5398 * client_version of the initial ClientHello rather than the | |
5399 * ClientHello in the renegotiation. To work around this bug, we | |
5400 * continue to use the client_version used in the initial | |
5401 * ClientHello when renegotiating. | |
5402 * | |
5403 * The client_version of the initial ClientHello is still | |
5404 * available in ss->clientHelloVersion. Ensure that | |
5405 * sid->version is bounded within | |
5406 * [ss->vrange.min, ss->clientHelloVersion], otherwise we | |
5407 * can't use sid. | |
5408 */ | |
5409 if (sid->version >= ss->vrange.min && | |
5410 sid->version <= ss->clientHelloVersion) { | |
5411 ss->version = ss->clientHelloVersion; | |
5412 } else { | |
5413 sidOK = PR_FALSE; | |
5414 } | |
5415 } else { | |
5416 /* | |
5417 * Check sid->version is OK first. | |
5418 * Previously, we would cap the version based on sid->version, | |
5419 * but that prevents negotiation of a higher version if the | |
5420 * previous session was reduced (e.g., with version fallback) | |
5421 */ | |
5422 if (sid->version < ss->vrange.min || | |
5423 sid->version > ss->vrange.max) { | |
5424 sidOK = PR_FALSE; | |
5425 } else { | |
5426 rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPO
RTED, | |
5427 PR_TRUE); | |
5428 if (rv != SECSuccess) { | |
5429 return rv; /* error code was set */ | |
5430 } | |
5431 } | |
5432 } | |
5433 } | |
5434 | |
5435 if (!sidOK) { | |
5436 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_not_ok); | |
5437 if (ss->sec.uncache) | |
5438 (*ss->sec.uncache)(sid); | |
5439 ssl_FreeSID(sid); | |
5440 sid = NULL; | |
5441 } | |
5442 } | |
5443 | |
5444 if (sid) { | |
5445 requestingResume = PR_TRUE; | |
5446 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_hits); | |
5447 | |
5448 PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID, | |
5449 sid->u.ssl3.sessionIDLength)); | |
5450 | |
5451 ss->ssl3.policy = sid->u.ssl3.policy; | |
5452 } else { | |
5453 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_misses); | |
5454 | |
5455 /* | |
5456 * Windows SChannel compares the client_version inside the RSA | |
5457 * EncryptedPreMasterSecret of a renegotiation with the | |
5458 * client_version of the initial ClientHello rather than the | |
5459 * ClientHello in the renegotiation. To work around this bug, we | |
5460 * continue to use the client_version used in the initial | |
5461 * ClientHello when renegotiating. | |
5462 */ | |
5463 if (ss->firstHsDone) { | |
5464 ss->version = ss->clientHelloVersion; | |
5465 } else { | |
5466 rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED, | |
5467 PR_TRUE); | |
5468 if (rv != SECSuccess) | |
5469 return rv; /* error code was set */ | |
5470 } | |
5471 | |
5472 sid = ssl3_NewSessionID(ss, PR_FALSE); | |
5473 if (!sid) { | |
5474 return SECFailure; /* memory error is set */ | |
5475 } | |
5476 } | |
5477 | |
5478 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { | |
5479 rv = tls13_SetupClientHello(ss); | |
5480 if (rv != SECSuccess) { | |
5481 if (sid) { | |
5482 ssl_FreeSID(sid); | |
5483 } | |
5484 return rv; | |
5485 } | |
5486 } | |
5487 | |
5488 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0); | |
5489 ssl_GetSpecWriteLock(ss); | |
5490 cwSpec = ss->ssl3.cwSpec; | |
5491 if (cwSpec->mac_def->mac == mac_null) { | |
5492 /* SSL records are not being MACed. */ | |
5493 cwSpec->version = ss->version; | |
5494 } | |
5495 ssl_ReleaseSpecWriteLock(ss); | |
5496 | |
5497 if (ss->sec.ci.sid != NULL) { | |
5498 ssl_FreeSID(ss->sec.ci.sid); /* decrement ref count, free if zero */ | |
5499 } | |
5500 ss->sec.ci.sid = sid; | |
5501 | |
5502 ss->sec.send = ssl3_SendApplicationData; | |
5503 | |
5504 /* shouldn't get here if SSL3 is disabled, but ... */ | |
5505 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { | |
5506 PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled"); | |
5507 PORT_SetError(SSL_ERROR_SSL_DISABLED); | |
5508 return SECFailure; | |
5509 } | |
5510 | |
5511 /* how many suites does our PKCS11 support (regardless of policy)? */ | |
5512 num_suites = ssl3_config_match_init(ss); | |
5513 if (!num_suites) | |
5514 return SECFailure; /* ssl3_config_match_init has set error code. */ | |
5515 | |
5516 /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV, | |
5517 * only if TLS is disabled. | |
5518 */ | |
5519 if (!ss->firstHsDone && !isTLS) { | |
5520 /* Must set this before calling Hello Extension Senders, | |
5521 * to suppress sending of empty RI extension. | |
5522 */ | |
5523 ss->ssl3.hs.sendingSCSV = PR_TRUE; | |
5524 } | |
5525 | |
5526 /* When we attempt session resumption (only), we must lock the sid to | |
5527 * prevent races with other resumption connections that receive a | |
5528 * NewSessionTicket that will cause the ticket in the sid to be replaced. | |
5529 * Once we've copied the session ticket into our ClientHello message, it | |
5530 * is OK for the ticket to change, so we just need to make sure we hold | |
5531 * the lock across the calls to ssl3_CallHelloExtensionSenders. | |
5532 */ | |
5533 if (sid->u.ssl3.lock) { | |
5534 PR_RWLock_Rlock(sid->u.ssl3.lock); | |
5535 } | |
5536 | |
5537 if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) { | |
5538 PRUint32 maxBytes = 65535; /* 2^16 - 1 */ | |
5539 PRInt32 extLen; | |
5540 | |
5541 extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL); | |
5542 if (extLen < 0) { | |
5543 if (sid->u.ssl3.lock) { | |
5544 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5545 } | |
5546 return SECFailure; | |
5547 } | |
5548 total_exten_len += extLen; | |
5549 | |
5550 if (total_exten_len > 0) | |
5551 total_exten_len += 2; | |
5552 } | |
5553 | |
5554 #ifndef NSS_DISABLE_ECC | |
5555 if (!total_exten_len || !isTLS) { | |
5556 /* not sending the elliptic_curves and ec_point_formats extensions */ | |
5557 ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */ | |
5558 } | |
5559 #endif /* NSS_DISABLE_ECC */ | |
5560 | |
5561 if (IS_DTLS(ss)) { | |
5562 ssl3_DisableNonDTLSSuites(ss); | |
5563 } | |
5564 | |
5565 /* how many suites are permitted by policy and user preference? */ | |
5566 num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE); | |
5567 if (!num_suites) { | |
5568 if (sid->u.ssl3.lock) { | |
5569 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5570 } | |
5571 return SECFailure; /* count_cipher_suites has set error code. */ | |
5572 } | |
5573 | |
5574 fallbackSCSV = ss->opt.enableFallbackSCSV && (!requestingResume || | |
5575 ss->version < sid->version); | |
5576 /* make room for SCSV */ | |
5577 if (ss->ssl3.hs.sendingSCSV) { | |
5578 ++num_suites; | |
5579 } | |
5580 if (fallbackSCSV) { | |
5581 ++num_suites; | |
5582 } | |
5583 | |
5584 /* count compression methods */ | |
5585 numCompressionMethods = 0; | |
5586 for (i = 0; i < compressionMethodsCount; i++) { | |
5587 if (compressionEnabled(ss, compressions[i])) | |
5588 numCompressionMethods++; | |
5589 } | |
5590 | |
5591 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + | |
5592 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) + | |
5593 2 + num_suites * sizeof(ssl3CipherSuite) + | |
5594 1 + numCompressionMethods + total_exten_len; | |
5595 if (IS_DTLS(ss)) { | |
5596 length += 1 + ss->ssl3.hs.cookieLen; | |
5597 } | |
5598 | |
5599 /* A padding extension may be included to ensure that the record containing | |
5600 * the ClientHello doesn't have a length between 256 and 511 bytes | |
5601 * (inclusive). Initial, ClientHello records with such lengths trigger bugs | |
5602 * in F5 devices. | |
5603 * | |
5604 * This is not done for DTLS nor for renegotiation. */ | |
5605 if (!IS_DTLS(ss) && isTLS && !ss->firstHsDone) { | |
5606 paddingExtensionLen = ssl3_CalculatePaddingExtensionLength(length); | |
5607 total_exten_len += paddingExtensionLen; | |
5608 length += paddingExtensionLen; | |
5609 } else { | |
5610 paddingExtensionLen = 0; | |
5611 } | |
5612 | |
5613 rv = ssl3_AppendHandshakeHeader(ss, client_hello, length); | |
5614 if (rv != SECSuccess) { | |
5615 if (sid->u.ssl3.lock) { | |
5616 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5617 } | |
5618 return rv; /* err set by ssl3_AppendHandshake* */ | |
5619 } | |
5620 | |
5621 if (ss->firstHsDone) { | |
5622 /* The client hello version must stay unchanged to work around | |
5623 * the Windows SChannel bug described above. */ | |
5624 PORT_Assert(ss->version == ss->clientHelloVersion); | |
5625 } | |
5626 ss->clientHelloVersion = ss->version; | |
5627 if (IS_DTLS(ss)) { | |
5628 PRUint16 version; | |
5629 | |
5630 version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); | |
5631 rv = ssl3_AppendHandshakeNumber(ss, version, 2); | |
5632 } else { | |
5633 rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2); | |
5634 } | |
5635 if (rv != SECSuccess) { | |
5636 if (sid->u.ssl3.lock) { | |
5637 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5638 } | |
5639 return rv; /* err set by ssl3_AppendHandshake* */ | |
5640 } | |
5641 | |
5642 if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */ | |
5643 rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random); | |
5644 if (rv != SECSuccess) { | |
5645 if (sid->u.ssl3.lock) { | |
5646 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5647 } | |
5648 return rv; /* err set by GetNewRandom. */ | |
5649 } | |
5650 } | |
5651 rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random, | |
5652 SSL3_RANDOM_LENGTH); | |
5653 if (rv != SECSuccess) { | |
5654 if (sid->u.ssl3.lock) { | |
5655 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5656 } | |
5657 return rv; /* err set by ssl3_AppendHandshake* */ | |
5658 } | |
5659 | |
5660 if (sid) | |
5661 rv = ssl3_AppendHandshakeVariable( | |
5662 ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); | |
5663 else | |
5664 rv = ssl3_AppendHandshakeNumber(ss, 0, 1); | |
5665 if (rv != SECSuccess) { | |
5666 if (sid->u.ssl3.lock) { | |
5667 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5668 } | |
5669 return rv; /* err set by ssl3_AppendHandshake* */ | |
5670 } | |
5671 | |
5672 if (IS_DTLS(ss)) { | |
5673 rv = ssl3_AppendHandshakeVariable( | |
5674 ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1); | |
5675 if (rv != SECSuccess) { | |
5676 if (sid->u.ssl3.lock) { | |
5677 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5678 } | |
5679 return rv; /* err set by ssl3_AppendHandshake* */ | |
5680 } | |
5681 } | |
5682 | |
5683 rv = ssl3_AppendHandshakeNumber(ss, num_suites * sizeof(ssl3CipherSuite), 2)
; | |
5684 if (rv != SECSuccess) { | |
5685 if (sid->u.ssl3.lock) { | |
5686 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5687 } | |
5688 return rv; /* err set by ssl3_AppendHandshake* */ | |
5689 } | |
5690 | |
5691 if (ss->ssl3.hs.sendingSCSV) { | |
5692 /* Add the actual SCSV */ | |
5693 rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, | |
5694 sizeof(ssl3CipherSuite)); | |
5695 if (rv != SECSuccess) { | |
5696 if (sid->u.ssl3.lock) { | |
5697 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5698 } | |
5699 return rv; /* err set by ssl3_AppendHandshake* */ | |
5700 } | |
5701 actual_count++; | |
5702 } | |
5703 if (fallbackSCSV) { | |
5704 rv = ssl3_AppendHandshakeNumber(ss, TLS_FALLBACK_SCSV, | |
5705 sizeof(ssl3CipherSuite)); | |
5706 if (rv != SECSuccess) { | |
5707 if (sid->u.ssl3.lock) { | |
5708 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5709 } | |
5710 return rv; /* err set by ssl3_AppendHandshake* */ | |
5711 } | |
5712 actual_count++; | |
5713 } | |
5714 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { | |
5715 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; | |
5716 if (config_match(suite, ss->ssl3.policy, PR_TRUE, &ss->vrange, ss)) { | |
5717 actual_count++; | |
5718 if (actual_count > num_suites) { | |
5719 if (sid->u.ssl3.lock) { | |
5720 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5721 } | |
5722 /* set error card removal/insertion error */ | |
5723 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); | |
5724 return SECFailure; | |
5725 } | |
5726 rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite, | |
5727 sizeof(ssl3CipherSuite)); | |
5728 if (rv != SECSuccess) { | |
5729 if (sid->u.ssl3.lock) { | |
5730 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5731 } | |
5732 return rv; /* err set by ssl3_AppendHandshake* */ | |
5733 } | |
5734 } | |
5735 } | |
5736 | |
5737 /* if cards were removed or inserted between count_cipher_suites and | |
5738 * generating our list, detect the error here rather than send it off to | |
5739 * the server.. */ | |
5740 if (actual_count != num_suites) { | |
5741 /* Card removal/insertion error */ | |
5742 if (sid->u.ssl3.lock) { | |
5743 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5744 } | |
5745 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); | |
5746 return SECFailure; | |
5747 } | |
5748 | |
5749 rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1); | |
5750 if (rv != SECSuccess) { | |
5751 if (sid->u.ssl3.lock) { | |
5752 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5753 } | |
5754 return rv; /* err set by ssl3_AppendHandshake* */ | |
5755 } | |
5756 for (i = 0; i < compressionMethodsCount; i++) { | |
5757 if (!compressionEnabled(ss, compressions[i])) | |
5758 continue; | |
5759 rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1); | |
5760 if (rv != SECSuccess) { | |
5761 if (sid->u.ssl3.lock) { | |
5762 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5763 } | |
5764 return rv; /* err set by ssl3_AppendHandshake* */ | |
5765 } | |
5766 } | |
5767 | |
5768 if (total_exten_len) { | |
5769 PRUint32 maxBytes = total_exten_len - 2; | |
5770 PRInt32 extLen; | |
5771 | |
5772 rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2); | |
5773 if (rv != SECSuccess) { | |
5774 if (sid->u.ssl3.lock) { | |
5775 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5776 } | |
5777 return rv; /* err set by AppendHandshake. */ | |
5778 } | |
5779 | |
5780 extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL); | |
5781 if (extLen < 0) { | |
5782 if (sid->u.ssl3.lock) { | |
5783 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5784 } | |
5785 return SECFailure; | |
5786 } | |
5787 maxBytes -= extLen; | |
5788 | |
5789 extLen = ssl3_AppendPaddingExtension(ss, paddingExtensionLen, maxBytes); | |
5790 if (extLen < 0) { | |
5791 if (sid->u.ssl3.lock) { | |
5792 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5793 } | |
5794 return SECFailure; | |
5795 } | |
5796 maxBytes -= extLen; | |
5797 | |
5798 PORT_Assert(!maxBytes); | |
5799 } | |
5800 | |
5801 if (sid->u.ssl3.lock) { | |
5802 PR_RWLock_Unlock(sid->u.ssl3.lock); | |
5803 } | |
5804 | |
5805 if (ss->xtnData.sentSessionTicketInClientHello) { | |
5806 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes); | |
5807 } | |
5808 | |
5809 if (ss->ssl3.hs.sendingSCSV) { | |
5810 /* Since we sent the SCSV, pretend we sent empty RI extension. */ | |
5811 TLSExtensionData *xtnData = &ss->xtnData; | |
5812 xtnData->advertised[xtnData->numAdvertised++] = | |
5813 ssl_renegotiation_info_xtn; | |
5814 } | |
5815 | |
5816 flags = 0; | |
5817 if (!ss->firstHsDone && !IS_DTLS(ss)) { | |
5818 flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION; | |
5819 } | |
5820 rv = ssl3_FlushHandshake(ss, flags); | |
5821 if (rv != SECSuccess) { | |
5822 return rv; /* error code set by ssl3_FlushHandshake */ | |
5823 } | |
5824 | |
5825 ss->ssl3.hs.ws = wait_server_hello; | |
5826 return rv; | |
5827 } | |
5828 | |
5829 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a | |
5830 * complete ssl3 Hello Request. | |
5831 * Caller must hold Handshake and RecvBuf locks. | |
5832 */ | |
5833 static SECStatus | |
5834 ssl3_HandleHelloRequest(sslSocket *ss) | |
5835 { | |
5836 sslSessionID *sid = ss->sec.ci.sid; | |
5837 SECStatus rv; | |
5838 | |
5839 SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake", | |
5840 SSL_GETPID(), ss->fd)); | |
5841 | |
5842 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
5843 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
5844 PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3); | |
5845 | |
5846 if (ss->ssl3.hs.ws == wait_server_hello) | |
5847 return SECSuccess; | |
5848 if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) { | |
5849 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
5850 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); | |
5851 return SECFailure; | |
5852 } | |
5853 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { | |
5854 (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation); | |
5855 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); | |
5856 return SECFailure; | |
5857 } | |
5858 | |
5859 if (sid) { | |
5860 if (ss->sec.uncache) | |
5861 ss->sec.uncache(sid); | |
5862 ssl_FreeSID(sid); | |
5863 ss->sec.ci.sid = NULL; | |
5864 } | |
5865 | |
5866 if (IS_DTLS(ss)) { | |
5867 dtls_RehandshakeCleanup(ss); | |
5868 } | |
5869 | |
5870 ssl_GetXmitBufLock(ss); | |
5871 rv = ssl3_SendClientHello(ss, PR_FALSE); | |
5872 ssl_ReleaseXmitBufLock(ss); | |
5873 | |
5874 return rv; | |
5875 } | |
5876 | |
5877 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff | |
5878 | |
5879 static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = { | |
5880 CKM_DES3_ECB, | |
5881 CKM_CAST5_ECB, | |
5882 CKM_DES_ECB, | |
5883 CKM_KEY_WRAP_LYNKS, | |
5884 CKM_IDEA_ECB, | |
5885 CKM_CAST3_ECB, | |
5886 CKM_CAST_ECB, | |
5887 CKM_RC5_ECB, | |
5888 CKM_RC2_ECB, | |
5889 CKM_CDMF_ECB, | |
5890 CKM_SKIPJACK_WRAP, | |
5891 CKM_SKIPJACK_CBC64, | |
5892 CKM_AES_ECB, | |
5893 CKM_CAMELLIA_ECB, | |
5894 CKM_SEED_ECB, | |
5895 UNKNOWN_WRAP_MECHANISM | |
5896 }; | |
5897 | |
5898 static int | |
5899 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech) | |
5900 { | |
5901 const CK_MECHANISM_TYPE *pMech = wrapMechanismList; | |
5902 | |
5903 while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) { | |
5904 ++pMech; | |
5905 } | |
5906 return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1 | |
5907 : (pMech - wrapMechanismList); | |
5908 } | |
5909 | |
5910 static PK11SymKey * | |
5911 ssl_UnwrapSymWrappingKey( | |
5912 SSLWrappedSymWrappingKey *pWswk, | |
5913 SECKEYPrivateKey *svrPrivKey, | |
5914 SSL3KEAType exchKeyType, | |
5915 CK_MECHANISM_TYPE masterWrapMech, | |
5916 void *pwArg) | |
5917 { | |
5918 PK11SymKey *unwrappedWrappingKey = NULL; | |
5919 SECItem wrappedKey; | |
5920 #ifndef NSS_DISABLE_ECC | |
5921 PK11SymKey *Ks; | |
5922 SECKEYPublicKey pubWrapKey; | |
5923 ECCWrappedKeyInfo *ecWrapped; | |
5924 #endif /* NSS_DISABLE_ECC */ | |
5925 | |
5926 /* found the wrapping key on disk. */ | |
5927 PORT_Assert(pWswk->symWrapMechanism == masterWrapMech); | |
5928 PORT_Assert(pWswk->exchKeyType == exchKeyType); | |
5929 if (pWswk->symWrapMechanism != masterWrapMech || | |
5930 pWswk->exchKeyType != exchKeyType) { | |
5931 goto loser; | |
5932 } | |
5933 wrappedKey.type = siBuffer; | |
5934 wrappedKey.data = pWswk->wrappedSymmetricWrappingkey; | |
5935 wrappedKey.len = pWswk->wrappedSymKeyLen; | |
5936 PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey); | |
5937 | |
5938 switch (exchKeyType) { | |
5939 | |
5940 case kt_rsa: | |
5941 unwrappedWrappingKey = | |
5942 PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey, | |
5943 masterWrapMech, CKA_UNWRAP, 0); | |
5944 break; | |
5945 | |
5946 #ifndef NSS_DISABLE_ECC | |
5947 case kt_ecdh: | |
5948 /* | |
5949 * For kt_ecdh, we first create an EC public key based on | |
5950 * data stored with the wrappedSymmetricWrappingkey. Next, | |
5951 * we do an ECDH computation involving this public key and | |
5952 * the SSL server's (long-term) EC private key. The resulting | |
5953 * shared secret is treated the same way as Fortezza's Ks, i.e., | |
5954 * it is used to recover the symmetric wrapping key. | |
5955 * | |
5956 * The data in wrappedSymmetricWrappingkey is laid out as defined | |
5957 * in the ECCWrappedKeyInfo structure. | |
5958 */ | |
5959 ecWrapped = (ECCWrappedKeyInfo *)pWswk->wrappedSymmetricWrappingkey; | |
5960 | |
5961 PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen + | |
5962 ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLE
N); | |
5963 | |
5964 if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen + | |
5965 ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) { | |
5966 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
5967 goto loser; | |
5968 } | |
5969 | |
5970 pubWrapKey.keyType = ecKey; | |
5971 pubWrapKey.u.ec.size = ecWrapped->size; | |
5972 pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen; | |
5973 pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var; | |
5974 pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen; | |
5975 pubWrapKey.u.ec.publicValue.data = ecWrapped->var + | |
5976 ecWrapped->encodedParamLen; | |
5977 | |
5978 wrappedKey.len = ecWrapped->wrappedKeyLen; | |
5979 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + | |
5980 ecWrapped->pubValueLen; | |
5981 | |
5982 /* Derive Ks using ECDH */ | |
5983 Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL, | |
5984 NULL, CKM_ECDH1_DERIVE, masterWrapMech, | |
5985 CKA_DERIVE, 0, CKD_NULL, NULL, NULL); | |
5986 if (Ks == NULL) { | |
5987 goto loser; | |
5988 } | |
5989 | |
5990 /* Use Ks to unwrap the wrapping key */ | |
5991 unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL, | |
5992 &wrappedKey, masterWrapMech
, | |
5993 CKA_UNWRAP, 0); | |
5994 PK11_FreeSymKey(Ks); | |
5995 | |
5996 break; | |
5997 #endif | |
5998 | |
5999 default: | |
6000 /* Assert? */ | |
6001 SET_ERROR_CODE | |
6002 goto loser; | |
6003 } | |
6004 loser: | |
6005 return unwrappedWrappingKey; | |
6006 } | |
6007 | |
6008 /* Each process sharing the server session ID cache has its own array of | |
6009 * SymKey pointers for the symmetric wrapping keys that are used to wrap | |
6010 * the master secrets. There is one key for each KEA type. These Symkeys | |
6011 * correspond to the wrapped SymKeys kept in the server session cache. | |
6012 */ | |
6013 | |
6014 typedef struct { | |
6015 PK11SymKey *symWrapKey[kt_kea_size]; | |
6016 } ssl3SymWrapKey; | |
6017 | |
6018 static PZLock *symWrapKeysLock = NULL; | |
6019 static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS]; | |
6020 | |
6021 SECStatus | |
6022 ssl_FreeSymWrapKeysLock(void) | |
6023 { | |
6024 if (symWrapKeysLock) { | |
6025 PZ_DestroyLock(symWrapKeysLock); | |
6026 symWrapKeysLock = NULL; | |
6027 return SECSuccess; | |
6028 } | |
6029 PORT_SetError(SEC_ERROR_NOT_INITIALIZED); | |
6030 return SECFailure; | |
6031 } | |
6032 | |
6033 SECStatus | |
6034 SSL3_ShutdownServerCache(void) | |
6035 { | |
6036 int i, j; | |
6037 | |
6038 if (!symWrapKeysLock) | |
6039 return SECSuccess; /* lock was never initialized */ | |
6040 PZ_Lock(symWrapKeysLock); | |
6041 /* get rid of all symWrapKeys */ | |
6042 for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) { | |
6043 for (j = 0; j < kt_kea_size; ++j) { | |
6044 PK11SymKey **pSymWrapKey; | |
6045 pSymWrapKey = &symWrapKeys[i].symWrapKey[j]; | |
6046 if (*pSymWrapKey) { | |
6047 PK11_FreeSymKey(*pSymWrapKey); | |
6048 *pSymWrapKey = NULL; | |
6049 } | |
6050 } | |
6051 } | |
6052 | |
6053 PZ_Unlock(symWrapKeysLock); | |
6054 return SECSuccess; | |
6055 } | |
6056 | |
6057 SECStatus | |
6058 ssl_InitSymWrapKeysLock(void) | |
6059 { | |
6060 symWrapKeysLock = PZ_NewLock(nssILockOther); | |
6061 return symWrapKeysLock ? SECSuccess : SECFailure; | |
6062 } | |
6063 | |
6064 /* Try to get wrapping key for mechanism from in-memory array. | |
6065 * If that fails, look for one on disk. | |
6066 * If that fails, generate a new one, put the new one on disk, | |
6067 * Put the new key in the in-memory array. | |
6068 */ | |
6069 static PK11SymKey * | |
6070 getWrappingKey(sslSocket *ss, | |
6071 PK11SlotInfo *masterSecretSlot, | |
6072 SSL3KEAType exchKeyType, | |
6073 CK_MECHANISM_TYPE masterWrapMech, | |
6074 void *pwArg) | |
6075 { | |
6076 SECKEYPrivateKey *svrPrivKey; | |
6077 SECKEYPublicKey *svrPubKey = NULL; | |
6078 PK11SymKey *unwrappedWrappingKey = NULL; | |
6079 PK11SymKey **pSymWrapKey; | |
6080 CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM; | |
6081 int length; | |
6082 int symWrapMechIndex; | |
6083 SECStatus rv; | |
6084 SECItem wrappedKey; | |
6085 SSLWrappedSymWrappingKey wswk; | |
6086 #ifndef NSS_DISABLE_ECC | |
6087 PK11SymKey *Ks = NULL; | |
6088 SECKEYPublicKey *pubWrapKey = NULL; | |
6089 SECKEYPrivateKey *privWrapKey = NULL; | |
6090 ECCWrappedKeyInfo *ecWrapped; | |
6091 #endif /* NSS_DISABLE_ECC */ | |
6092 | |
6093 svrPrivKey = ss->serverCerts[exchKeyType].SERVERKEY; | |
6094 PORT_Assert(svrPrivKey != NULL); | |
6095 if (!svrPrivKey) { | |
6096 return NULL; /* why are we here?!? */ | |
6097 } | |
6098 | |
6099 symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech); | |
6100 PORT_Assert(symWrapMechIndex >= 0); | |
6101 if (symWrapMechIndex < 0) | |
6102 return NULL; /* invalid masterWrapMech. */ | |
6103 | |
6104 pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType]; | |
6105 | |
6106 ssl_InitSessionCacheLocks(); | |
6107 | |
6108 PZ_Lock(symWrapKeysLock); | |
6109 | |
6110 unwrappedWrappingKey = *pSymWrapKey; | |
6111 if (unwrappedWrappingKey != NULL) { | |
6112 if (PK11_VerifyKeyOK(unwrappedWrappingKey)) { | |
6113 unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey); | |
6114 goto done; | |
6115 } | |
6116 /* slot series has changed, so this key is no good any more. */ | |
6117 PK11_FreeSymKey(unwrappedWrappingKey); | |
6118 *pSymWrapKey = unwrappedWrappingKey = NULL; | |
6119 } | |
6120 | |
6121 /* Try to get wrapped SymWrapping key out of the (disk) cache. */ | |
6122 /* Following call fills in wswk on success. */ | |
6123 if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) { | |
6124 /* found the wrapped sym wrapping key on disk. */ | |
6125 unwrappedWrappingKey = | |
6126 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, | |
6127 masterWrapMech, pwArg); | |
6128 if (unwrappedWrappingKey) { | |
6129 goto install; | |
6130 } | |
6131 } | |
6132 | |
6133 if (!masterSecretSlot) /* caller doesn't want to create a new one. */ | |
6134 goto loser; | |
6135 | |
6136 length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech); | |
6137 /* Zero length means fixed key length algorithm, or error. | |
6138 * It's ambiguous. | |
6139 */ | |
6140 unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL, | |
6141 length, pwArg); | |
6142 if (!unwrappedWrappingKey) { | |
6143 goto loser; | |
6144 } | |
6145 | |
6146 /* Prepare the buffer to receive the wrappedWrappingKey, | |
6147 * the symmetric wrapping key wrapped using the server's pub key. | |
6148 */ | |
6149 PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */ | |
6150 | |
6151 if (ss->serverCerts[exchKeyType].serverKeyPair) { | |
6152 svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey; | |
6153 } | |
6154 if (svrPubKey == NULL) { | |
6155 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
6156 goto loser; | |
6157 } | |
6158 wrappedKey.type = siBuffer; | |
6159 wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey); | |
6160 wrappedKey.data = wswk.wrappedSymmetricWrappingkey; | |
6161 | |
6162 PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey); | |
6163 if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey) | |
6164 goto loser; | |
6165 | |
6166 /* wrap symmetric wrapping key in server's public key. */ | |
6167 switch (exchKeyType) { | |
6168 case kt_rsa: | |
6169 asymWrapMechanism = CKM_RSA_PKCS; | |
6170 rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey, | |
6171 unwrappedWrappingKey, &wrappedKey); | |
6172 break; | |
6173 | |
6174 #ifndef NSS_DISABLE_ECC | |
6175 case kt_ecdh: | |
6176 /* | |
6177 * We generate an ephemeral EC key pair. Perform an ECDH | |
6178 * computation involving this ephemeral EC public key and | |
6179 * the SSL server's (long-term) EC private key. The resulting | |
6180 * shared secret is treated in the same way as Fortezza's Ks, | |
6181 * i.e., it is used to wrap the wrapping key. To facilitate | |
6182 * unwrapping in ssl_UnwrapWrappingKey, we also store all | |
6183 * relevant info about the ephemeral EC public key in | |
6184 * wswk.wrappedSymmetricWrappingkey and lay it out as | |
6185 * described in the ECCWrappedKeyInfo structure. | |
6186 */ | |
6187 PORT_Assert(svrPubKey->keyType == ecKey); | |
6188 if (svrPubKey->keyType != ecKey) { | |
6189 /* something is wrong in sslsecur.c if this isn't an ecKey */ | |
6190 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
6191 rv = SECFailure; | |
6192 goto ec_cleanup; | |
6193 } | |
6194 | |
6195 privWrapKey = SECKEY_CreateECPrivateKey( | |
6196 &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL); | |
6197 if ((privWrapKey == NULL) || (pubWrapKey == NULL)) { | |
6198 rv = SECFailure; | |
6199 goto ec_cleanup; | |
6200 } | |
6201 | |
6202 /* Set the key size in bits */ | |
6203 if (pubWrapKey->u.ec.size == 0) { | |
6204 pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey
); | |
6205 } | |
6206 | |
6207 PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len + | |
6208 pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KE
Y_BUFLEN); | |
6209 if (pubWrapKey->u.ec.DEREncodedParams.len + | |
6210 pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLE
N) { | |
6211 PORT_SetError(SEC_ERROR_INVALID_KEY); | |
6212 rv = SECFailure; | |
6213 goto ec_cleanup; | |
6214 } | |
6215 | |
6216 /* Derive Ks using ECDH */ | |
6217 Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL, | |
6218 NULL, CKM_ECDH1_DERIVE, masterWrapMech, | |
6219 CKA_DERIVE, 0, CKD_NULL, NULL, NULL); | |
6220 if (Ks == NULL) { | |
6221 rv = SECFailure; | |
6222 goto ec_cleanup; | |
6223 } | |
6224 | |
6225 ecWrapped = (ECCWrappedKeyInfo *)(wswk.wrappedSymmetricWrappingkey); | |
6226 ecWrapped->size = pubWrapKey->u.ec.size; | |
6227 ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len; | |
6228 PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data, | |
6229 pubWrapKey->u.ec.DEREncodedParams.len); | |
6230 | |
6231 ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len; | |
6232 PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen, | |
6233 pubWrapKey->u.ec.publicValue.data, | |
6234 pubWrapKey->u.ec.publicValue.len); | |
6235 | |
6236 wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN - | |
6237 (ecWrapped->encodedParamLen + ecWrapped->pubValueLe
n); | |
6238 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + | |
6239 ecWrapped->pubValueLen; | |
6240 | |
6241 /* wrap symmetricWrapping key with the local Ks */ | |
6242 rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks, | |
6243 unwrappedWrappingKey, &wrappedKey); | |
6244 | |
6245 if (rv != SECSuccess) { | |
6246 goto ec_cleanup; | |
6247 } | |
6248 | |
6249 /* Write down the length of wrapped key in the buffer | |
6250 * wswk.wrappedSymmetricWrappingkey at the appropriate offset | |
6251 */ | |
6252 ecWrapped->wrappedKeyLen = wrappedKey.len; | |
6253 | |
6254 ec_cleanup: | |
6255 if (privWrapKey) | |
6256 SECKEY_DestroyPrivateKey(privWrapKey); | |
6257 if (pubWrapKey) | |
6258 SECKEY_DestroyPublicKey(pubWrapKey); | |
6259 if (Ks) | |
6260 PK11_FreeSymKey(Ks); | |
6261 asymWrapMechanism = masterWrapMech; | |
6262 break; | |
6263 #endif /* NSS_DISABLE_ECC */ | |
6264 | |
6265 default: | |
6266 rv = SECFailure; | |
6267 break; | |
6268 } | |
6269 | |
6270 if (rv != SECSuccess) { | |
6271 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
6272 goto loser; | |
6273 } | |
6274 | |
6275 PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM); | |
6276 | |
6277 wswk.symWrapMechanism = masterWrapMech; | |
6278 wswk.symWrapMechIndex = symWrapMechIndex; | |
6279 wswk.asymWrapMechanism = asymWrapMechanism; | |
6280 wswk.exchKeyType = exchKeyType; | |
6281 wswk.wrappedSymKeyLen = wrappedKey.len; | |
6282 | |
6283 /* put it on disk. */ | |
6284 /* If the wrapping key for this KEA type has already been set, | |
6285 * then abandon the value we just computed and | |
6286 * use the one we got from the disk. | |
6287 */ | |
6288 if (ssl_SetWrappingKey(&wswk)) { | |
6289 /* somebody beat us to it. The original contents of our wswk | |
6290 * has been replaced with the content on disk. Now, discard | |
6291 * the key we just created and unwrap this new one. | |
6292 */ | |
6293 PK11_FreeSymKey(unwrappedWrappingKey); | |
6294 | |
6295 unwrappedWrappingKey = | |
6296 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, | |
6297 masterWrapMech, pwArg); | |
6298 } | |
6299 | |
6300 install: | |
6301 if (unwrappedWrappingKey) { | |
6302 *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey); | |
6303 } | |
6304 | |
6305 loser: | |
6306 done: | |
6307 PZ_Unlock(symWrapKeysLock); | |
6308 return unwrappedWrappingKey; | |
6309 } | |
6310 | |
6311 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2| | |
6312 * bytes to |out|. */ | |
6313 static void | |
6314 hexEncode(char *out, const unsigned char *in, unsigned int length) | |
6315 { | |
6316 static const char hextable[] = "0123456789abcdef"; | |
6317 unsigned int i; | |
6318 | |
6319 for (i = 0; i < length; i++) { | |
6320 *(out++) = hextable[in[i] >> 4]; | |
6321 *(out++) = hextable[in[i] & 15]; | |
6322 } | |
6323 } | |
6324 | |
6325 /* Called from ssl3_SendClientKeyExchange(). */ | |
6326 /* Presently, this always uses PKCS11. There is no bypass for this. */ | |
6327 static SECStatus | |
6328 sendRSAClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey) | |
6329 { | |
6330 PK11SymKey *pms = NULL; | |
6331 SECStatus rv = SECFailure; | |
6332 SECItem enc_pms = { siBuffer, NULL, 0 }; | |
6333 PRBool isTLS; | |
6334 | |
6335 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
6336 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
6337 | |
6338 /* Generate the pre-master secret ... */ | |
6339 ssl_GetSpecWriteLock(ss); | |
6340 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
6341 | |
6342 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL); | |
6343 ssl_ReleaseSpecWriteLock(ss); | |
6344 if (pms == NULL) { | |
6345 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
6346 goto loser; | |
6347 } | |
6348 | |
6349 /* Get the wrapped (encrypted) pre-master secret, enc_pms */ | |
6350 enc_pms.len = SECKEY_PublicKeyStrength(svrPubKey); | |
6351 enc_pms.data = (unsigned char *)PORT_Alloc(enc_pms.len); | |
6352 if (enc_pms.data == NULL) { | |
6353 goto loser; /* err set by PORT_Alloc */ | |
6354 } | |
6355 | |
6356 /* wrap pre-master secret in server's public key. */ | |
6357 rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms); | |
6358 if (rv != SECSuccess) { | |
6359 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
6360 goto loser; | |
6361 } | |
6362 | |
6363 if (ssl_keylog_iob) { | |
6364 SECStatus extractRV = PK11_ExtractKeyValue(pms); | |
6365 if (extractRV == SECSuccess) { | |
6366 SECItem *keyData = PK11_GetKeyData(pms); | |
6367 if (keyData && keyData->data && keyData->len) { | |
6368 #ifdef TRACE | |
6369 if (ssl_trace >= 100) { | |
6370 ssl_PrintBuf(ss, "Pre-Master Secret", | |
6371 keyData->data, keyData->len); | |
6372 } | |
6373 #endif | |
6374 if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) { | |
6375 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ | |
6376 | |
6377 /* There could be multiple, concurrent writers to the | |
6378 * keylog, so we have to do everything in a single call to | |
6379 * fwrite. */ | |
6380 char buf[4 + 8 * 2 + 1 + 48 * 2 + 1]; | |
6381 | |
6382 strcpy(buf, "RSA "); | |
6383 hexEncode(buf + 4, enc_pms.data, 8); | |
6384 buf[20] = ' '; | |
6385 hexEncode(buf + 21, keyData->data, 48); | |
6386 buf[sizeof(buf) - 1] = '\n'; | |
6387 | |
6388 fwrite(buf, sizeof(buf), 1, ssl_keylog_iob); | |
6389 fflush(ssl_keylog_iob); | |
6390 } | |
6391 } | |
6392 } | |
6393 } | |
6394 | |
6395 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, | |
6396 isTLS ? enc_pms.len + 2 | |
6397 : enc_pms.len); | |
6398 if (rv != SECSuccess) { | |
6399 goto loser; /* err set by ssl3_AppendHandshake* */ | |
6400 } | |
6401 if (isTLS) { | |
6402 rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2); | |
6403 } else { | |
6404 rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len); | |
6405 } | |
6406 if (rv != SECSuccess) { | |
6407 goto loser; /* err set by ssl3_AppendHandshake* */ | |
6408 } | |
6409 | |
6410 rv = ssl3_InitPendingCipherSpec(ss, pms); | |
6411 PK11_FreeSymKey(pms); | |
6412 pms = NULL; | |
6413 | |
6414 if (rv != SECSuccess) { | |
6415 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
6416 goto loser; | |
6417 } | |
6418 | |
6419 rv = SECSuccess; | |
6420 | |
6421 loser: | |
6422 if (enc_pms.data != NULL) { | |
6423 PORT_Free(enc_pms.data); | |
6424 } | |
6425 if (pms != NULL) { | |
6426 PK11_FreeSymKey(pms); | |
6427 } | |
6428 return rv; | |
6429 } | |
6430 | |
6431 /* Called from ssl3_SendClientKeyExchange(). */ | |
6432 /* Presently, this always uses PKCS11. There is no bypass for this. */ | |
6433 static SECStatus | |
6434 sendDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey) | |
6435 { | |
6436 PK11SymKey *pms = NULL; | |
6437 SECStatus rv = SECFailure; | |
6438 PRBool isTLS; | |
6439 CK_MECHANISM_TYPE target; | |
6440 | |
6441 SECKEYDHParams dhParam; /* DH parameters */ | |
6442 SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ | |
6443 SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */ | |
6444 | |
6445 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
6446 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
6447 | |
6448 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
6449 | |
6450 /* Copy DH parameters from server key */ | |
6451 | |
6452 if (svrPubKey->keyType != dhKey) { | |
6453 PORT_SetError(SEC_ERROR_BAD_KEY); | |
6454 goto loser; | |
6455 } | |
6456 dhParam.prime.data = svrPubKey->u.dh.prime.data; | |
6457 dhParam.prime.len = svrPubKey->u.dh.prime.len; | |
6458 dhParam.base.data = svrPubKey->u.dh.base.data; | |
6459 dhParam.base.len = svrPubKey->u.dh.base.len; | |
6460 | |
6461 /* Generate ephemeral DH keypair */ | |
6462 privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL); | |
6463 if (!privKey || !pubKey) { | |
6464 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); | |
6465 rv = SECFailure; | |
6466 goto loser; | |
6467 } | |
6468 PRINT_BUF(50, (ss, "DH public value:", | |
6469 pubKey->u.dh.publicValue.data, | |
6470 pubKey->u.dh.publicValue.len)); | |
6471 | |
6472 if (isTLS) | |
6473 target = CKM_TLS_MASTER_KEY_DERIVE_DH; | |
6474 else | |
6475 target = CKM_SSL3_MASTER_KEY_DERIVE_DH; | |
6476 | |
6477 /* Determine the PMS */ | |
6478 | |
6479 pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL, | |
6480 CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL); | |
6481 | |
6482 if (pms == NULL) { | |
6483 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
6484 goto loser; | |
6485 } | |
6486 | |
6487 SECKEY_DestroyPrivateKey(privKey); | |
6488 privKey = NULL; | |
6489 | |
6490 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, | |
6491 pubKey->u.dh.publicValue.len + 2); | |
6492 if (rv != SECSuccess) { | |
6493 goto loser; /* err set by ssl3_AppendHandshake* */ | |
6494 } | |
6495 rv = ssl3_AppendHandshakeVariable(ss, | |
6496 pubKey->u.dh.publicValue.data, | |
6497 pubKey->u.dh.publicValue.len, 2); | |
6498 SECKEY_DestroyPublicKey(pubKey); | |
6499 pubKey = NULL; | |
6500 | |
6501 if (rv != SECSuccess) { | |
6502 goto loser; /* err set by ssl3_AppendHandshake* */ | |
6503 } | |
6504 | |
6505 rv = ssl3_InitPendingCipherSpec(ss, pms); | |
6506 PK11_FreeSymKey(pms); | |
6507 pms = NULL; | |
6508 | |
6509 if (rv != SECSuccess) { | |
6510 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
6511 goto loser; | |
6512 } | |
6513 | |
6514 rv = SECSuccess; | |
6515 | |
6516 loser: | |
6517 | |
6518 if (pms) | |
6519 PK11_FreeSymKey(pms); | |
6520 if (privKey) | |
6521 SECKEY_DestroyPrivateKey(privKey); | |
6522 if (pubKey) | |
6523 SECKEY_DestroyPublicKey(pubKey); | |
6524 return rv; | |
6525 } | |
6526 | |
6527 /* Called from ssl3_HandleServerHelloDone(). */ | |
6528 static SECStatus | |
6529 ssl3_SendClientKeyExchange(sslSocket *ss) | |
6530 { | |
6531 SECKEYPublicKey *serverKey = NULL; | |
6532 SECStatus rv = SECFailure; | |
6533 PRBool isTLS; | |
6534 | |
6535 SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake", | |
6536 SSL_GETPID(), ss->fd)); | |
6537 | |
6538 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
6539 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
6540 | |
6541 if (ss->sec.peerKey == NULL) { | |
6542 serverKey = CERT_ExtractPublicKey(ss->sec.peerCert); | |
6543 if (serverKey == NULL) { | |
6544 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); | |
6545 return SECFailure; | |
6546 } | |
6547 } else { | |
6548 serverKey = ss->sec.peerKey; | |
6549 ss->sec.peerKey = NULL; /* we're done with it now */ | |
6550 } | |
6551 | |
6552 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
6553 /* enforce limits on kea key sizes. */ | |
6554 if (ss->ssl3.hs.kea_def->is_limited) { | |
6555 unsigned int keyLen = SECKEY_PublicKeyStrengthInBits(serverKey); | |
6556 | |
6557 if (keyLen > ss->ssl3.hs.kea_def->key_size_limit) { | |
6558 if (isTLS) | |
6559 (void)SSL3_SendAlert(ss, alert_fatal, export_restriction); | |
6560 else | |
6561 (void)ssl3_HandshakeFailure(ss); | |
6562 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); | |
6563 goto loser; | |
6564 } | |
6565 } | |
6566 | |
6567 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; | |
6568 ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey); | |
6569 | |
6570 switch (ss->ssl3.hs.kea_def->exchKeyType) { | |
6571 case kt_rsa: | |
6572 rv = sendRSAClientKeyExchange(ss, serverKey); | |
6573 break; | |
6574 | |
6575 case kt_dh: | |
6576 rv = sendDHClientKeyExchange(ss, serverKey); | |
6577 break; | |
6578 | |
6579 #ifndef NSS_DISABLE_ECC | |
6580 case kt_ecdh: | |
6581 rv = ssl3_SendECDHClientKeyExchange(ss, serverKey); | |
6582 break; | |
6583 #endif /* NSS_DISABLE_ECC */ | |
6584 | |
6585 default: | |
6586 /* got an unknown or unsupported Key Exchange Algorithm. */ | |
6587 SEND_ALERT | |
6588 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); | |
6589 break; | |
6590 } | |
6591 | |
6592 SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange", | |
6593 SSL_GETPID(), ss->fd)); | |
6594 | |
6595 loser: | |
6596 if (serverKey) | |
6597 SECKEY_DestroyPublicKey(serverKey); | |
6598 return rv; /* err code already set. */ | |
6599 } | |
6600 | |
6601 /* Called from ssl3_HandleServerHelloDone(). */ | |
6602 SECStatus | |
6603 ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey) | |
6604 { | |
6605 SECStatus rv = SECFailure; | |
6606 PRBool isTLS; | |
6607 PRBool isTLS12; | |
6608 PRBool isTLS13; | |
6609 SECItem buf = { siBuffer, NULL, 0 }; | |
6610 SSL3Hashes hashes; | |
6611 KeyType keyType; | |
6612 unsigned int len; | |
6613 SSLSignatureAndHashAlg sigAndHash; | |
6614 | |
6615 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
6616 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
6617 | |
6618 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake", | |
6619 SSL_GETPID(), ss->fd)); | |
6620 | |
6621 isTLS13 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3); | |
6622 ssl_GetSpecReadLock(ss); | |
6623 if (ss->ssl3.hs.hashType == handshake_hash_single && | |
6624 ss->ssl3.hs.backupHash) { | |
6625 PORT_Assert(!ss->ssl3.hs.backupHash); | |
6626 PORT_Assert(!isTLS13); | |
6627 /* TODO(ekr@rtfm.com): The backup hash here contains a SHA-1 hash | |
6628 * but in TLS 1.3, we always sign H(Context, Hash(handshake)) | |
6629 * where: | |
6630 * | |
6631 * H is the negotiated signature hash and | |
6632 * Hash is the cipher-suite specific handshake hash | |
6633 * Generally this means that Hash is SHA-256. | |
6634 * | |
6635 * We need code to negotiate H but the current code is a mess. | |
6636 */ | |
6637 if (isTLS13) { | |
6638 /* rv is already set to SECFailure */ | |
6639 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
6640 } else { | |
6641 rv = ssl3_ComputeBackupHandshakeHashes(ss, &hashes); | |
6642 } | |
6643 } else { | |
6644 ssl3CipherSpec *spec; | |
6645 | |
6646 if (isTLS13) { | |
6647 /* In TLS 1.3, we are already encrypted. */ | |
6648 spec = ss->ssl3.cwSpec; | |
6649 } else { | |
6650 spec = ss->ssl3.pwSpec; | |
6651 } | |
6652 | |
6653 rv = ssl3_ComputeHandshakeHashes(ss, spec, &hashes, 0); | |
6654 } | |
6655 ssl_ReleaseSpecReadLock(ss); | |
6656 if (rv != SECSuccess) { | |
6657 goto done; /* err code was set by ssl3_ComputeHandshakeHashes */ | |
6658 } | |
6659 | |
6660 if (isTLS13) { | |
6661 rv = tls13_AddContextToHashes(ss, &hashes, tls13_GetHash(ss), PR_TRUE); | |
6662 if (rv != SECSuccess) { | |
6663 goto done; /* err code was set by tls13_AddContextToHashes */ | |
6664 } | |
6665 } | |
6666 | |
6667 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
6668 isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
6669 | |
6670 keyType = privKey->keyType; | |
6671 rv = ssl3_SignHashes(&hashes, privKey, &buf, isTLS); | |
6672 if (rv == SECSuccess && !ss->sec.isServer) { | |
6673 /* Remember the info about the slot that did the signing. | |
6674 ** Later, when doing an SSL restart handshake, verify this. | |
6675 ** These calls are mere accessors, and can't fail. | |
6676 */ | |
6677 PK11SlotInfo *slot; | |
6678 sslSessionID *sid = ss->sec.ci.sid; | |
6679 | |
6680 slot = PK11_GetSlotFromPrivateKey(privKey); | |
6681 sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot); | |
6682 sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot); | |
6683 sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot); | |
6684 sid->u.ssl3.clAuthValid = PR_TRUE; | |
6685 PK11_FreeSlot(slot); | |
6686 } | |
6687 if (rv != SECSuccess) { | |
6688 goto done; /* err code was set by ssl3_SignHashes */ | |
6689 } | |
6690 | |
6691 len = buf.len + 2 + (isTLS12 ? 2 : 0); | |
6692 | |
6693 rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len); | |
6694 if (rv != SECSuccess) { | |
6695 goto done; /* error code set by AppendHandshake */ | |
6696 } | |
6697 if (isTLS12) { | |
6698 rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType, | |
6699 &sigAndHash.sigAlg); | |
6700 if (rv != SECSuccess) { | |
6701 goto done; | |
6702 } | |
6703 sigAndHash.hashAlg = hashes.hashAlg; | |
6704 | |
6705 rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); | |
6706 if (rv != SECSuccess) { | |
6707 goto done; /* err set by AppendHandshake. */ | |
6708 } | |
6709 } | |
6710 rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2); | |
6711 if (rv != SECSuccess) { | |
6712 goto done; /* error code set by AppendHandshake */ | |
6713 } | |
6714 | |
6715 done: | |
6716 if (buf.data) | |
6717 PORT_Free(buf.data); | |
6718 return rv; | |
6719 } | |
6720 | |
6721 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete | |
6722 * ssl3 ServerHello message. | |
6723 * Caller must hold Handshake and RecvBuf locks. | |
6724 */ | |
6725 static SECStatus | |
6726 ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
6727 { | |
6728 sslSessionID *sid = ss->sec.ci.sid; | |
6729 PRInt32 temp; /* allow for consume number failure */ | |
6730 PRBool suite_found = PR_FALSE; | |
6731 int i; | |
6732 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; | |
6733 SECStatus rv; | |
6734 SECItem sidBytes = { siBuffer, NULL, 0 }; | |
6735 PRBool sid_match; | |
6736 PRBool isTLS = PR_FALSE; | |
6737 SSL3AlertDescription desc = illegal_parameter; | |
6738 SSL3ProtocolVersion version; | |
6739 SSL3ProtocolVersion downgradeCheckVersion; | |
6740 | |
6741 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake", | |
6742 SSL_GETPID(), ss->fd)); | |
6743 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
6744 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
6745 PORT_Assert(ss->ssl3.initialized); | |
6746 | |
6747 if (ss->ssl3.hs.ws != wait_server_hello) { | |
6748 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO; | |
6749 desc = unexpected_message; | |
6750 goto alert_loser; | |
6751 } | |
6752 | |
6753 /* clean up anything left from previous handshake. */ | |
6754 if (ss->ssl3.clientCertChain != NULL) { | |
6755 CERT_DestroyCertificateList(ss->ssl3.clientCertChain); | |
6756 ss->ssl3.clientCertChain = NULL; | |
6757 } | |
6758 if (ss->ssl3.clientCertificate != NULL) { | |
6759 CERT_DestroyCertificate(ss->ssl3.clientCertificate); | |
6760 ss->ssl3.clientCertificate = NULL; | |
6761 } | |
6762 if (ss->ssl3.clientPrivateKey != NULL) { | |
6763 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); | |
6764 ss->ssl3.clientPrivateKey = NULL; | |
6765 } | |
6766 | |
6767 if (ss->ssl3.channelID != NULL) { | |
6768 SECKEY_DestroyPrivateKey(ss->ssl3.channelID); | |
6769 ss->ssl3.channelID = NULL; | |
6770 } | |
6771 if (ss->ssl3.channelIDPub != NULL) { | |
6772 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub); | |
6773 ss->ssl3.channelIDPub = NULL; | |
6774 } | |
6775 | |
6776 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); | |
6777 if (temp < 0) { | |
6778 goto loser; /* alert has been sent */ | |
6779 } | |
6780 version = (SSL3ProtocolVersion)temp; | |
6781 | |
6782 if (IS_DTLS(ss)) { | |
6783 /* RFC 4347 required that you verify that the server versions | |
6784 * match (Section 4.2.1) in the HelloVerifyRequest and the | |
6785 * ServerHello. | |
6786 * | |
6787 * RFC 6347 suggests (SHOULD) that servers always use 1.0 | |
6788 * in HelloVerifyRequest and allows the versions not to match, | |
6789 * especially when 1.2 is being negotiated. | |
6790 * | |
6791 * Therefore we do not check for matching here. | |
6792 */ | |
6793 version = dtls_DTLSVersionToTLSVersion(version); | |
6794 if (version == 0) { /* Insane version number */ | |
6795 goto alert_loser; | |
6796 } | |
6797 } | |
6798 | |
6799 rv = ssl3_NegotiateVersion(ss, version, PR_FALSE); | |
6800 if (rv != SECSuccess) { | |
6801 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version | |
6802 : handshake_failure; | |
6803 errCode = SSL_ERROR_UNSUPPORTED_VERSION; | |
6804 goto alert_loser; | |
6805 } | |
6806 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; | |
6807 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0); | |
6808 | |
6809 rv = ssl3_InitHandshakeHashes(ss); | |
6810 if (rv != SECSuccess) { | |
6811 desc = internal_error; | |
6812 errCode = PORT_GetError(); | |
6813 goto alert_loser; | |
6814 } | |
6815 | |
6816 rv = ssl3_ConsumeHandshake( | |
6817 ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length); | |
6818 if (rv != SECSuccess) { | |
6819 goto loser; /* alert has been sent */ | |
6820 } | |
6821 | |
6822 /* Check the ServerHello.random per | |
6823 * [draft-ietf-tls-tls13-11 Section 6.3.1.1]. | |
6824 * | |
6825 * TLS 1.3 clients receiving a TLS 1.2 or below ServerHello MUST check | |
6826 * that the top eight octets are not equal to either of these values. | |
6827 * TLS 1.2 clients SHOULD also perform this check if the ServerHello | |
6828 * indicates TLS 1.1 or below. If a match is found the client MUST | |
6829 * abort the handshake with a fatal "illegal_parameter" alert. | |
6830 */ | |
6831 downgradeCheckVersion = ss->ssl3.downgradeCheckVersion ? ss->ssl3.downgradeC
heckVersion | |
6832 : ss->vrange.max; | |
6833 | |
6834 if (downgradeCheckVersion >= SSL_LIBRARY_VERSION_TLS_1_2 && | |
6835 downgradeCheckVersion > ss->version) { | |
6836 if (!PORT_Memcmp(ss->ssl3.hs.server_random.rand, | |
6837 tls13_downgrade_random, | |
6838 sizeof(tls13_downgrade_random)) || | |
6839 !PORT_Memcmp(ss->ssl3.hs.server_random.rand, | |
6840 tls12_downgrade_random, | |
6841 sizeof(tls12_downgrade_random))) { | |
6842 desc = illegal_parameter; | |
6843 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; | |
6844 goto alert_loser; | |
6845 } | |
6846 } | |
6847 | |
6848 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { | |
6849 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); | |
6850 if (rv != SECSuccess) { | |
6851 goto loser; /* alert has been sent */ | |
6852 } | |
6853 if (sidBytes.len > SSL3_SESSIONID_BYTES) { | |
6854 if (isTLS) | |
6855 desc = decode_error; | |
6856 goto alert_loser; /* malformed. */ | |
6857 } | |
6858 } | |
6859 | |
6860 /* find selected cipher suite in our list. */ | |
6861 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); | |
6862 if (temp < 0) { | |
6863 goto loser; /* alert has been sent */ | |
6864 } | |
6865 ssl3_config_match_init(ss); | |
6866 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { | |
6867 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; | |
6868 if (temp == suite->cipher_suite) { | |
6869 SSLVersionRange vrange = { ss->version, ss->version }; | |
6870 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) { | |
6871 /* config_match already checks whether the cipher suite is | |
6872 * acceptable for the version, but the check is repeated here | |
6873 * in order to give a more precise error code. */ | |
6874 if (!ssl3_CipherSuiteAllowedForVersionRange(temp, &vrange)) { | |
6875 desc = handshake_failure; | |
6876 errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION; | |
6877 goto alert_loser; | |
6878 } | |
6879 | |
6880 break; /* failure */ | |
6881 } | |
6882 | |
6883 suite_found = PR_TRUE; | |
6884 break; /* success */ | |
6885 } | |
6886 } | |
6887 if (!suite_found) { | |
6888 desc = handshake_failure; | |
6889 errCode = SSL_ERROR_NO_CYPHER_OVERLAP; | |
6890 goto alert_loser; | |
6891 } | |
6892 ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp; | |
6893 ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp); | |
6894 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; | |
6895 PORT_Assert(ss->ssl3.hs.suite_def); | |
6896 if (!ss->ssl3.hs.suite_def) { | |
6897 errCode = SEC_ERROR_LIBRARY_FAILURE; | |
6898 PORT_SetError(errCode); | |
6899 goto loser; /* we don't send alerts for our screw-ups. */ | |
6900 } | |
6901 | |
6902 ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; | |
6903 | |
6904 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { | |
6905 /* find selected compression method in our list. */ | |
6906 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); | |
6907 if (temp < 0) { | |
6908 goto loser; /* alert has been sent */ | |
6909 } | |
6910 suite_found = PR_FALSE; | |
6911 for (i = 0; i < compressionMethodsCount; i++) { | |
6912 if (temp == compressions[i]) { | |
6913 if (!compressionEnabled(ss, compressions[i])) { | |
6914 break; /* failure */ | |
6915 } | |
6916 suite_found = PR_TRUE; | |
6917 break; /* success */ | |
6918 } | |
6919 } | |
6920 if (!suite_found) { | |
6921 desc = handshake_failure; | |
6922 errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; | |
6923 goto alert_loser; | |
6924 } | |
6925 ss->ssl3.hs.compression = (SSLCompressionMethod)temp; | |
6926 } else { | |
6927 ss->ssl3.hs.compression = ssl_compression_null; | |
6928 } | |
6929 | |
6930 /* Note that if !isTLS and the extra stuff is not extensions, we | |
6931 * do NOT goto alert_loser. | |
6932 * There are some old SSL 3.0 implementations that do send stuff | |
6933 * after the end of the server hello, and we deliberately ignore | |
6934 * such stuff in the interest of maximal interoperability (being | |
6935 * "generous in what you accept"). | |
6936 * Update: Starting in NSS 3.12.6, we handle the renegotiation_info | |
6937 * extension in SSL 3.0. | |
6938 */ | |
6939 if (length != 0) { | |
6940 SECItem extensions; | |
6941 rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length); | |
6942 if (rv != SECSuccess || length != 0) { | |
6943 if (isTLS) | |
6944 goto alert_loser; | |
6945 } else { | |
6946 rv = ssl3_HandleHelloExtensions(ss, &extensions.data, | |
6947 &extensions.len, server_hello); | |
6948 if (rv != SECSuccess) | |
6949 goto alert_loser; | |
6950 } | |
6951 } | |
6952 if ((ss->opt.requireSafeNegotiation || | |
6953 (ss->firstHsDone && (ss->peerRequestedProtection || | |
6954 ss->opt.enableRenegotiation == | |
6955 SSL_RENEGOTIATE_REQUIRES_XTN))) && | |
6956 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { | |
6957 desc = handshake_failure; | |
6958 errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED | |
6959 : SSL_ERROR_UNSAFE_NEGOTIATION; | |
6960 goto alert_loser; | |
6961 } | |
6962 | |
6963 /* Any errors after this point are not "malformed" errors. */ | |
6964 desc = handshake_failure; | |
6965 | |
6966 /* we need to call ssl3_SetupPendingCipherSpec here so we can check the | |
6967 * key exchange algorithm. */ | |
6968 rv = ssl3_SetupPendingCipherSpec(ss); | |
6969 if (rv != SECSuccess) { | |
6970 goto alert_loser; /* error code is set. */ | |
6971 } | |
6972 | |
6973 /* We may or may not have sent a session id, we may get one back or | |
6974 * not and if so it may match the one we sent. | |
6975 * Attempt to restore the master secret to see if this is so... | |
6976 * Don't consider failure to find a matching SID an error. | |
6977 */ | |
6978 sid_match = (PRBool)(sidBytes.len > 0 && | |
6979 sidBytes.len == | |
6980 sid->u.ssl3.sessionIDLength && | |
6981 !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidB
ytes.len)); | |
6982 | |
6983 if (sid_match && | |
6984 sid->version == ss->version && | |
6985 sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) | |
6986 do { | |
6987 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; | |
6988 | |
6989 SECItem wrappedMS; /* wrapped master secret. */ | |
6990 | |
6991 /* [draft-ietf-tls-session-hash-06; Section 5.3] | |
6992 * | |
6993 * o If the original session did not use the "extended_master_secre
t" | |
6994 * extension but the new ServerHello contains the extension, the | |
6995 * client MUST abort the handshake. | |
6996 */ | |
6997 if (!sid->u.ssl3.keys.extendedMasterSecretUsed && | |
6998 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { | |
6999 errCode = SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET; | |
7000 goto alert_loser; | |
7001 } | |
7002 | |
7003 /* | |
7004 * o If the original session used an extended master secret but t
he new | |
7005 * ServerHello does not contain the "extended_master_secret" | |
7006 * extension, the client SHOULD abort the handshake. | |
7007 * | |
7008 * TODO(ekr@rtfm.com): Add option to refuse to resume when EMS is no
t | |
7009 * used at all (bug 1176526). | |
7010 */ | |
7011 if (sid->u.ssl3.keys.extendedMasterSecretUsed && | |
7012 !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { | |
7013 errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET; | |
7014 goto alert_loser; | |
7015 } | |
7016 | |
7017 ss->sec.authAlgorithm = sid->authAlgorithm; | |
7018 ss->sec.authKeyBits = sid->authKeyBits; | |
7019 ss->sec.keaType = sid->keaType; | |
7020 ss->sec.keaKeyBits = sid->keaKeyBits; | |
7021 | |
7022 /* 3 cases here: | |
7023 * a) key is wrapped (implies using PKCS11) | |
7024 * b) key is unwrapped, but we're still using PKCS11 | |
7025 * c) key is unwrapped, and we're bypassing PKCS11. | |
7026 */ | |
7027 if (sid->u.ssl3.keys.msIsWrapped) { | |
7028 PK11SlotInfo *slot; | |
7029 PK11SymKey *wrapKey; /* wrapping key */ | |
7030 CK_FLAGS keyFlags = 0; | |
7031 | |
7032 #ifndef NO_PKCS11_BYPASS | |
7033 if (ss->opt.bypassPKCS11) { | |
7034 /* we cannot restart a non-bypass session in a | |
7035 ** bypass socket. | |
7036 */ | |
7037 break; | |
7038 } | |
7039 #endif | |
7040 /* unwrap master secret with PKCS11 */ | |
7041 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, | |
7042 sid->u.ssl3.masterSlotID); | |
7043 if (slot == NULL) { | |
7044 break; /* not considered an error. */ | |
7045 } | |
7046 if (!PK11_IsPresent(slot)) { | |
7047 PK11_FreeSlot(slot); | |
7048 break; /* not considered an error. */ | |
7049 } | |
7050 wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex, | |
7051 sid->u.ssl3.masterWrapMech, | |
7052 sid->u.ssl3.masterWrapSeries, | |
7053 ss->pkcs11PinArg); | |
7054 PK11_FreeSlot(slot); | |
7055 if (wrapKey == NULL) { | |
7056 break; /* not considered an error. */ | |
7057 } | |
7058 | |
7059 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ | |
7060 keyFlags = | |
7061 CKF_SIGN | CKF_VERIFY; | |
7062 } | |
7063 | |
7064 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; | |
7065 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; | |
7066 pwSpec->master_secret = | |
7067 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMe
ch, | |
7068 NULL, &wrappedMS, CKM_SSL3_MASTER
_KEY_DERIVE, | |
7069 CKA_DERIVE, sizeof(SSL3MasterSecr
et), keyFlags); | |
7070 errCode = PORT_GetError(); | |
7071 PK11_FreeSymKey(wrapKey); | |
7072 if (pwSpec->master_secret == NULL) { | |
7073 break; /* errorCode set just after call to UnwrapSymKey. */ | |
7074 } | |
7075 #ifndef NO_PKCS11_BYPASS | |
7076 } else if (ss->opt.bypassPKCS11) { | |
7077 /* MS is not wrapped */ | |
7078 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; | |
7079 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; | |
7080 memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len)
; | |
7081 pwSpec->msItem.data = pwSpec->raw_master_secret; | |
7082 pwSpec->msItem.len = wrappedMS.len; | |
7083 #endif | |
7084 } else { | |
7085 /* We CAN restart a bypass session in a non-bypass socket. */ | |
7086 /* need to import the raw master secret to session object */ | |
7087 PK11SlotInfo *slot = PK11_GetInternalSlot(); | |
7088 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; | |
7089 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; | |
7090 pwSpec->master_secret = | |
7091 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, | |
7092 PK11_OriginUnwrap, CKA_ENCRYPT, | |
7093 &wrappedMS, NULL); | |
7094 PK11_FreeSlot(slot); | |
7095 if (pwSpec->master_secret == NULL) { | |
7096 break; | |
7097 } | |
7098 } | |
7099 | |
7100 /* Got a Match */ | |
7101 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_hits); | |
7102 | |
7103 /* If we sent a session ticket, then this is a stateless resume. */ | |
7104 if (ss->xtnData.sentSessionTicketInClientHello) | |
7105 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_stateless_resumes); | |
7106 | |
7107 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) | |
7108 ss->ssl3.hs.ws = wait_new_session_ticket; | |
7109 else | |
7110 ss->ssl3.hs.ws = wait_change_cipher; | |
7111 | |
7112 ss->ssl3.hs.isResuming = PR_TRUE; | |
7113 | |
7114 /* copy the peer cert from the SID */ | |
7115 if (sid->peerCert != NULL) { | |
7116 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); | |
7117 ssl3_CopyPeerCertsFromSID(ss, sid); | |
7118 } | |
7119 | |
7120 /* NULL value for PMS because we are reusing the old MS */ | |
7121 rv = ssl3_InitPendingCipherSpec(ss, NULL); | |
7122 if (rv != SECSuccess) { | |
7123 goto alert_loser; /* err code was set */ | |
7124 } | |
7125 goto winner; | |
7126 } while (0); | |
7127 | |
7128 if (sid_match) | |
7129 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_not_ok); | |
7130 else | |
7131 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_misses); | |
7132 | |
7133 /* throw the old one away */ | |
7134 sid->u.ssl3.keys.resumable = PR_FALSE; | |
7135 if (ss->sec.uncache) | |
7136 (*ss->sec.uncache)(sid); | |
7137 ssl_FreeSID(sid); | |
7138 | |
7139 /* get a new sid */ | |
7140 ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE); | |
7141 if (sid == NULL) { | |
7142 goto alert_loser; /* memory error is set. */ | |
7143 } | |
7144 | |
7145 sid->version = ss->version; | |
7146 sid->u.ssl3.sessionIDLength = sidBytes.len; | |
7147 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len); | |
7148 | |
7149 sid->u.ssl3.keys.extendedMasterSecretUsed = | |
7150 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn); | |
7151 | |
7152 /* Copy Signed Certificate Timestamps, if any. */ | |
7153 if (ss->xtnData.signedCertTimestamps.data) { | |
7154 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps, | |
7155 &ss->xtnData.signedCertTimestamps); | |
7156 if (rv != SECSuccess) | |
7157 goto loser; | |
7158 /* Clean up the temporary pointer to the handshake buffer. */ | |
7159 ss->xtnData.signedCertTimestamps.data = NULL; | |
7160 ss->xtnData.signedCertTimestamps.len = 0; | |
7161 } | |
7162 | |
7163 ss->ssl3.hs.isResuming = PR_FALSE; | |
7164 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { | |
7165 rv = tls13_HandleServerKeyShare(ss); | |
7166 if (rv != SECSuccess) | |
7167 goto alert_loser; | |
7168 TLS13_SET_HS_STATE(ss, wait_encrypted_extensions); | |
7169 } else if (ss->ssl3.hs.kea_def->signKeyType != ssl_sign_null) { | |
7170 /* All current cipher suites other than those with ssl_sign_null (i.e., | |
7171 * (EC)DH_anon_* suites) require a certificate, so use that signal. */ | |
7172 ss->ssl3.hs.ws = wait_server_cert; | |
7173 } else { | |
7174 /* All the remaining cipher suites must be (EC)DH_anon_* and so | |
7175 * must be ephemeral. Note, if we ever add PSK this might | |
7176 * change. */ | |
7177 PORT_Assert(ss->ssl3.hs.kea_def->ephemeral); | |
7178 ss->ssl3.hs.ws = wait_server_key; | |
7179 } | |
7180 | |
7181 winner: | |
7182 /* If we will need a ChannelID key then we make the callback now. This | |
7183 * allows the handshake to be restarted cleanly if the callback returns | |
7184 * SECWouldBlock. */ | |
7185 if (ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) { | |
7186 rv = ss->getChannelID(ss->getChannelIDArg, ss->fd, | |
7187 &ss->ssl3.channelIDPub, &ss->ssl3.channelID); | |
7188 if (rv == SECWouldBlock) { | |
7189 ssl3_SetAlwaysBlock(ss); | |
7190 return rv; | |
7191 } | |
7192 if (rv != SECSuccess || | |
7193 ss->ssl3.channelIDPub == NULL || | |
7194 ss->ssl3.channelID == NULL) { | |
7195 PORT_SetError(SSL_ERROR_GET_CHANNEL_ID_FAILED); | |
7196 desc = internal_error; | |
7197 goto alert_loser; | |
7198 } | |
7199 } | |
7200 | |
7201 return SECSuccess; | |
7202 | |
7203 alert_loser: | |
7204 (void)SSL3_SendAlert(ss, alert_fatal, desc); | |
7205 | |
7206 loser: | |
7207 /* Clean up the temporary pointer to the handshake buffer. */ | |
7208 ss->xtnData.signedCertTimestamps.data = NULL; | |
7209 ss->xtnData.signedCertTimestamps.len = 0; | |
7210 ssl_MapLowLevelError(errCode); | |
7211 return SECFailure; | |
7212 } | |
7213 | |
7214 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a | |
7215 * complete ssl3 ServerKeyExchange message. | |
7216 * Caller must hold Handshake and RecvBuf locks. | |
7217 */ | |
7218 static SECStatus | |
7219 ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
7220 { | |
7221 PLArenaPool *arena = NULL; | |
7222 SECKEYPublicKey *peerKey = NULL; | |
7223 PRBool isTLS, isTLS12; | |
7224 SECStatus rv; | |
7225 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH; | |
7226 SSL3AlertDescription desc = illegal_parameter; | |
7227 SSL3Hashes hashes; | |
7228 SECItem signature = { siBuffer, NULL, 0 }; | |
7229 SSLSignatureAndHashAlg sigAndHash; | |
7230 | |
7231 sigAndHash.hashAlg = ssl_hash_none; | |
7232 | |
7233 SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake", | |
7234 SSL_GETPID(), ss->fd)); | |
7235 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
7236 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
7237 | |
7238 if (ss->ssl3.hs.ws != wait_server_key) { | |
7239 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH; | |
7240 desc = unexpected_message; | |
7241 goto alert_loser; | |
7242 } | |
7243 | |
7244 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); | |
7245 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
7246 | |
7247 switch (ss->ssl3.hs.kea_def->exchKeyType) { | |
7248 | |
7249 case kt_rsa: { | |
7250 SECItem modulus = { siBuffer, NULL, 0 }; | |
7251 SECItem exponent = { siBuffer, NULL, 0 }; | |
7252 | |
7253 rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length); | |
7254 if (rv != SECSuccess) { | |
7255 goto loser; /* malformed. */ | |
7256 } | |
7257 /* This exchange method is only used by export cipher suites. | |
7258 * Those are broken and so this code will eventually be removed. */ | |
7259 if (SECKEY_BigIntegerBitLength(&modulus) < 512) { | |
7260 desc = isTLS ? insufficient_security : illegal_parameter; | |
7261 goto alert_loser; | |
7262 } | |
7263 rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length); | |
7264 if (rv != SECSuccess) { | |
7265 goto loser; /* malformed. */ | |
7266 } | |
7267 if (isTLS12) { | |
7268 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, | |
7269 &sigAndHash); | |
7270 if (rv != SECSuccess) { | |
7271 goto loser; /* malformed or unsupported. */ | |
7272 } | |
7273 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(ss, | |
7274 &sigAndHash,
ss->sec.peerCert); | |
7275 if (rv != SECSuccess) { | |
7276 goto loser; | |
7277 } | |
7278 } | |
7279 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); | |
7280 if (rv != SECSuccess) { | |
7281 goto loser; /* malformed. */ | |
7282 } | |
7283 if (length != 0) { | |
7284 if (isTLS) | |
7285 desc = | |
7286 decode_error; | |
7287 goto alert_loser; /* malformed. */ | |
7288 } | |
7289 | |
7290 /* failures after this point are not malformed handshakes. */ | |
7291 /* TLS: send decrypt_error if signature failed. */ | |
7292 desc = isTLS ? decrypt_error : handshake_failure; | |
7293 | |
7294 /* | |
7295 * check to make sure the hash is signed by right guy | |
7296 */ | |
7297 rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, expon
ent, | |
7298 &ss->ssl3.hs.client_random, | |
7299 &ss->ssl3.hs.server_random, | |
7300 &hashes, ss->opt.bypassPKCS11); | |
7301 if (rv != SECSuccess) { | |
7302 errCode = | |
7303 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
7304 goto alert_loser; | |
7305 } | |
7306 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, | |
7307 isTLS, ss->pkcs11PinArg); | |
7308 if (rv != SECSuccess) { | |
7309 errCode = | |
7310 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
7311 goto alert_loser; | |
7312 } | |
7313 | |
7314 /* | |
7315 * we really need to build a new key here because we can no longer | |
7316 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocat
e | |
7317 * pkcs11 slots and ID's. | |
7318 */ | |
7319 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); | |
7320 if (arena == NULL) { | |
7321 goto no_memory; | |
7322 } | |
7323 | |
7324 peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); | |
7325 if (peerKey == NULL) { | |
7326 goto no_memory; | |
7327 } | |
7328 | |
7329 peerKey->arena = arena; | |
7330 peerKey->keyType = rsaKey; | |
7331 peerKey->pkcs11Slot = NULL; | |
7332 peerKey->pkcs11ID = CK_INVALID_HANDLE; | |
7333 if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus, &modulus) || | |
7334 SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponen
t)) { | |
7335 goto no_memory; | |
7336 } | |
7337 ss->sec.peerKey = peerKey; | |
7338 ss->ssl3.hs.ws = wait_cert_request; | |
7339 return SECSuccess; | |
7340 } | |
7341 | |
7342 case kt_dh: { | |
7343 SECItem dh_p = { siBuffer, NULL, 0 }; | |
7344 SECItem dh_g = { siBuffer, NULL, 0 }; | |
7345 SECItem dh_Ys = { siBuffer, NULL, 0 }; | |
7346 unsigned dh_p_bits; | |
7347 unsigned dh_g_bits; | |
7348 unsigned dh_Ys_bits; | |
7349 PRInt32 minDH; | |
7350 | |
7351 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length); | |
7352 if (rv != SECSuccess) { | |
7353 goto loser; /* malformed. */ | |
7354 } | |
7355 | |
7356 rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH); | |
7357 if (rv != SECSuccess) { | |
7358 minDH = SSL_DH_MIN_P_BITS; | |
7359 } | |
7360 dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p); | |
7361 if (dh_p_bits < minDH) { | |
7362 errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY; | |
7363 goto alert_loser; | |
7364 } | |
7365 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length); | |
7366 if (rv != SECSuccess) { | |
7367 goto loser; /* malformed. */ | |
7368 } | |
7369 /* Abort if dh_g is 0, 1, or obviously too big. */ | |
7370 dh_g_bits = SECKEY_BigIntegerBitLength(&dh_g); | |
7371 if (dh_g_bits > dh_p_bits || dh_g_bits <= 1) | |
7372 goto alert_loser; | |
7373 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length); | |
7374 if (rv != SECSuccess) { | |
7375 goto loser; /* malformed. */ | |
7376 } | |
7377 dh_Ys_bits = SECKEY_BigIntegerBitLength(&dh_Ys); | |
7378 if (dh_Ys_bits > dh_p_bits || dh_Ys_bits <= 1) | |
7379 goto alert_loser; | |
7380 if (isTLS12) { | |
7381 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, | |
7382 &sigAndHash); | |
7383 if (rv != SECSuccess) { | |
7384 goto loser; /* malformed or unsupported. */ | |
7385 } | |
7386 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(ss, | |
7387 &sigAndHash,
ss->sec.peerCert); | |
7388 if (rv != SECSuccess) { | |
7389 goto loser; | |
7390 } | |
7391 } | |
7392 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); | |
7393 if (rv != SECSuccess) { | |
7394 goto loser; /* malformed. */ | |
7395 } | |
7396 if (length != 0) { | |
7397 if (isTLS) | |
7398 desc = | |
7399 decode_error; | |
7400 goto alert_loser; /* malformed. */ | |
7401 } | |
7402 | |
7403 PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len)); | |
7404 PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len)); | |
7405 PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len)); | |
7406 | |
7407 /* failures after this point are not malformed handshakes. */ | |
7408 /* TLS: send decrypt_error if signature failed. */ | |
7409 desc = isTLS ? decrypt_error : handshake_failure; | |
7410 | |
7411 /* | |
7412 * check to make sure the hash is signed by right guy | |
7413 */ | |
7414 rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys, | |
7415 &ss->ssl3.hs.client_random, | |
7416 &ss->ssl3.hs.server_random, | |
7417 &hashes, ss->opt.bypassPKCS11); | |
7418 if (rv != SECSuccess) { | |
7419 errCode = | |
7420 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
7421 goto alert_loser; | |
7422 } | |
7423 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, | |
7424 isTLS, ss->pkcs11PinArg); | |
7425 if (rv != SECSuccess) { | |
7426 errCode = | |
7427 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
7428 goto alert_loser; | |
7429 } | |
7430 | |
7431 /* | |
7432 * we really need to build a new key here because we can no longer | |
7433 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocat
e | |
7434 * pkcs11 slots and ID's. | |
7435 */ | |
7436 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); | |
7437 if (arena == NULL) { | |
7438 goto no_memory; | |
7439 } | |
7440 | |
7441 peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); | |
7442 if (peerKey == NULL) { | |
7443 goto no_memory; | |
7444 } | |
7445 | |
7446 peerKey->arena = arena; | |
7447 peerKey->keyType = dhKey; | |
7448 peerKey->pkcs11Slot = NULL; | |
7449 peerKey->pkcs11ID = CK_INVALID_HANDLE; | |
7450 | |
7451 if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) || | |
7452 SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) || | |
7453 SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) { | |
7454 goto no_memory; | |
7455 } | |
7456 ss->sec.peerKey = peerKey; | |
7457 ss->ssl3.hs.ws = wait_cert_request; | |
7458 return SECSuccess; | |
7459 } | |
7460 | |
7461 #ifndef NSS_DISABLE_ECC | |
7462 case kt_ecdh: | |
7463 rv = ssl3_HandleECDHServerKeyExchange(ss, b, length); | |
7464 return rv; | |
7465 #endif /* NSS_DISABLE_ECC */ | |
7466 | |
7467 default: | |
7468 desc = handshake_failure; | |
7469 errCode = SEC_ERROR_UNSUPPORTED_KEYALG; | |
7470 break; /* goto alert_loser; */ | |
7471 } | |
7472 | |
7473 alert_loser: | |
7474 (void)SSL3_SendAlert(ss, alert_fatal, desc); | |
7475 loser: | |
7476 if (arena) { | |
7477 PORT_FreeArena(arena, PR_FALSE); | |
7478 } | |
7479 PORT_SetError(errCode); | |
7480 return SECFailure; | |
7481 | |
7482 no_memory: /* no-memory error has already been set. */ | |
7483 if (arena) { | |
7484 PORT_FreeArena(arena, PR_FALSE); | |
7485 } | |
7486 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
7487 return SECFailure; | |
7488 } | |
7489 | |
7490 /* | |
7491 * Returns the TLS signature algorithm for the client authentication key and | |
7492 * whether it is an RSA or DSA key that may be able to sign only SHA-1 hashes. | |
7493 */ | |
7494 static SECStatus | |
7495 ssl3_ExtractClientKeyInfo(sslSocket *ss, | |
7496 SSLSignType *sigAlg, | |
7497 PRBool *preferSha1) | |
7498 { | |
7499 SECStatus rv = SECSuccess; | |
7500 SECKEYPublicKey *pubk; | |
7501 | |
7502 pubk = CERT_ExtractPublicKey(ss->ssl3.clientCertificate); | |
7503 if (pubk == NULL) { | |
7504 rv = SECFailure; | |
7505 goto done; | |
7506 } | |
7507 | |
7508 rv = ssl3_TLSSignatureAlgorithmForKeyType(pubk->keyType, sigAlg); | |
7509 if (rv != SECSuccess) { | |
7510 goto done; | |
7511 } | |
7512 | |
7513 /* If the key is a 1024-bit RSA or DSA key, assume conservatively that | |
7514 * it may be unable to sign SHA-256 hashes. This is the case for older | |
7515 * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and | |
7516 * older, DSA key size is at most 1024 bits and the hash function must | |
7517 * be SHA-1. | |
7518 */ | |
7519 if (pubk->keyType == rsaKey || pubk->keyType == dsaKey) { | |
7520 *preferSha1 = SECKEY_PublicKeyStrength(pubk) <= 128; | |
7521 } else { | |
7522 *preferSha1 = PR_FALSE; | |
7523 } | |
7524 | |
7525 done: | |
7526 if (pubk) | |
7527 SECKEY_DestroyPublicKey(pubk); | |
7528 return rv; | |
7529 } | |
7530 | |
7531 /* Destroys the backup handshake hash context if we don't need it. Note that | |
7532 * this function selects the hash algorithm for client authentication | |
7533 * signatures; ssl3_SendCertificateVerify uses the presence of the backup hash | |
7534 * to determine whether to use SHA-1 or SHA-256. */ | |
7535 static void | |
7536 ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss, | |
7537 const SECItem *algorithms) | |
7538 { | |
7539 SECStatus rv; | |
7540 SSLSignType sigAlg; | |
7541 PRBool preferSha1 = PR_FALSE; | |
7542 PRBool supportsSha1 = PR_FALSE; | |
7543 PRBool supportsSha256 = PR_FALSE; | |
7544 PRBool needBackupHash = PR_FALSE; | |
7545 unsigned int i; | |
7546 | |
7547 #ifndef NO_PKCS11_BYPASS | |
7548 /* Backup handshake hash is not supported in PKCS #11 bypass mode. */ | |
7549 if (ss->opt.bypassPKCS11) { | |
7550 PORT_Assert(!ss->ssl3.hs.backupHash); | |
7551 return; | |
7552 } | |
7553 #endif | |
7554 PORT_Assert(ss->ssl3.hs.backupHash); | |
7555 | |
7556 /* Determine the key's signature algorithm and whether it prefers SHA-1. */ | |
7557 rv = ssl3_ExtractClientKeyInfo(ss, &sigAlg, &preferSha1); | |
7558 if (rv != SECSuccess) { | |
7559 goto done; | |
7560 } | |
7561 | |
7562 /* Determine the server's hash support for that signature algorithm. */ | |
7563 for (i = 0; i < algorithms->len; i += 2) { | |
7564 if (algorithms->data[i + 1] == sigAlg) { | |
7565 if (algorithms->data[i] == ssl_hash_sha1) { | |
7566 supportsSha1 = PR_TRUE; | |
7567 } else if (algorithms->data[i] == ssl_hash_sha256) { | |
7568 supportsSha256 = PR_TRUE; | |
7569 } | |
7570 } | |
7571 } | |
7572 | |
7573 /* If either the server does not support SHA-256 or the client key prefers | |
7574 * SHA-1, leave the backup hash. */ | |
7575 if (supportsSha1 && (preferSha1 || !supportsSha256)) { | |
7576 needBackupHash = PR_TRUE; | |
7577 } | |
7578 | |
7579 done: | |
7580 if (!needBackupHash) { | |
7581 PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); | |
7582 ss->ssl3.hs.backupHash = NULL; | |
7583 } | |
7584 } | |
7585 | |
7586 typedef struct dnameNode { | |
7587 struct dnameNode *next; | |
7588 SECItem name; | |
7589 } dnameNode; | |
7590 | |
7591 /* | |
7592 * Parse the ca_list structure in a CertificateRequest. | |
7593 * | |
7594 * Called from: | |
7595 * ssl3_HandleCertificateRequest | |
7596 * tls13_HandleCertificateRequest | |
7597 */ | |
7598 SECStatus | |
7599 ssl3_ParseCertificateRequestCAs(sslSocket *ss, SSL3Opaque **b, PRUint32 *length, | |
7600 PLArenaPool *arena, CERTDistNames *ca_list) | |
7601 { | |
7602 PRInt32 remaining; | |
7603 int nnames = 0; | |
7604 dnameNode *node; | |
7605 int i; | |
7606 | |
7607 remaining = ssl3_ConsumeHandshakeNumber(ss, 2, b, length); | |
7608 if (remaining < 0) | |
7609 return SECFailure; /* malformed, alert has been sent */ | |
7610 | |
7611 if ((PRUint32)remaining > *length) | |
7612 goto alert_loser; | |
7613 | |
7614 ca_list->head = node = PORT_ArenaZNew(arena, dnameNode); | |
7615 if (node == NULL) | |
7616 goto no_mem; | |
7617 | |
7618 while (remaining > 0) { | |
7619 PRInt32 len; | |
7620 | |
7621 if (remaining < 2) | |
7622 goto alert_loser; /* malformed */ | |
7623 | |
7624 node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, b, length); | |
7625 if (len <= 0) | |
7626 return SECFailure; /* malformed, alert has been sent */ | |
7627 | |
7628 remaining -= 2; | |
7629 if (remaining < len) | |
7630 goto alert_loser; /* malformed */ | |
7631 | |
7632 node->name.data = *b; | |
7633 *b += len; | |
7634 *length -= len; | |
7635 remaining -= len; | |
7636 nnames++; | |
7637 if (remaining <= 0) | |
7638 break; /* success */ | |
7639 | |
7640 node->next = PORT_ArenaZNew(arena, dnameNode); | |
7641 node = node->next; | |
7642 if (node == NULL) | |
7643 goto no_mem; | |
7644 } | |
7645 | |
7646 ca_list->nnames = nnames; | |
7647 ca_list->names = PORT_ArenaNewArray(arena, SECItem, nnames); | |
7648 if (nnames > 0 && ca_list->names == NULL) | |
7649 goto no_mem; | |
7650 | |
7651 for (i = 0, node = (dnameNode *)ca_list->head; | |
7652 i < nnames; | |
7653 i++, node = node->next) { | |
7654 ca_list->names[i] = node->name; | |
7655 } | |
7656 | |
7657 return SECSuccess; | |
7658 | |
7659 no_mem: | |
7660 PORT_SetError(SEC_ERROR_NO_MEMORY); | |
7661 return SECFailure; | |
7662 | |
7663 alert_loser: | |
7664 (void)SSL3_SendAlert(ss, alert_fatal, | |
7665 ss->version < SSL_LIBRARY_VERSION_TLS_1_0 ? illegal_par
ameter | |
7666 : decode_erro
r); | |
7667 PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST); | |
7668 return SECFailure; | |
7669 } | |
7670 | |
7671 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered | |
7672 * a complete ssl3 Certificate Request message. | |
7673 * Caller must hold Handshake and RecvBuf locks. | |
7674 */ | |
7675 static SECStatus | |
7676 ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
7677 { | |
7678 PLArenaPool *arena = NULL; | |
7679 PRBool isTLS = PR_FALSE; | |
7680 PRBool isTLS12 = PR_FALSE; | |
7681 int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST; | |
7682 SECStatus rv; | |
7683 SSL3AlertDescription desc = illegal_parameter; | |
7684 SECItem cert_types = { siBuffer, NULL, 0 }; | |
7685 SECItem algorithms = { siBuffer, NULL, 0 }; | |
7686 CERTDistNames ca_list; | |
7687 | |
7688 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake", | |
7689 SSL_GETPID(), ss->fd)); | |
7690 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
7691 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
7692 | |
7693 if (ss->ssl3.hs.ws != wait_cert_request) { | |
7694 desc = unexpected_message; | |
7695 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST; | |
7696 goto alert_loser; | |
7697 } | |
7698 | |
7699 PORT_Assert(ss->ssl3.clientCertChain == NULL); | |
7700 PORT_Assert(ss->ssl3.clientCertificate == NULL); | |
7701 PORT_Assert(ss->ssl3.clientPrivateKey == NULL); | |
7702 | |
7703 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); | |
7704 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
7705 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length); | |
7706 if (rv != SECSuccess) | |
7707 goto loser; /* malformed, alert has been sent */ | |
7708 | |
7709 PORT_Assert(!ss->requestedCertTypes); | |
7710 ss->requestedCertTypes = &cert_types; | |
7711 | |
7712 if (isTLS12) { | |
7713 rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length); | |
7714 if (rv != SECSuccess) | |
7715 goto loser; /* malformed, alert has been sent */ | |
7716 /* An empty or odd-length value is invalid. | |
7717 * SignatureAndHashAlgorithm | |
7718 * supported_signature_algorithms<2..2^16-2>; | |
7719 */ | |
7720 if (algorithms.len == 0 || (algorithms.len & 1) != 0) | |
7721 goto alert_loser; | |
7722 } | |
7723 | |
7724 arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); | |
7725 if (arena == NULL) | |
7726 goto no_mem; | |
7727 | |
7728 rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, arena, &ca_list); | |
7729 if (rv != SECSuccess) | |
7730 goto done; /* alert sent in ssl3_ParseCertificateRequestCAs */ | |
7731 | |
7732 if (length != 0) | |
7733 goto alert_loser; /* malformed */ | |
7734 | |
7735 desc = no_certificate; | |
7736 | |
7737 ss->ssl3.hs.ws = wait_hello_done; | |
7738 | |
7739 rv = ssl3_CompleteHandleCertificateRequest(ss, &algorithms, &ca_list); | |
7740 if (rv == SECFailure) { | |
7741 PORT_Assert(0); | |
7742 errCode = SEC_ERROR_LIBRARY_FAILURE; | |
7743 desc = internal_error; | |
7744 goto alert_loser; | |
7745 } | |
7746 goto done; | |
7747 | |
7748 no_mem: | |
7749 rv = SECFailure; | |
7750 PORT_SetError(SEC_ERROR_NO_MEMORY); | |
7751 goto done; | |
7752 | |
7753 alert_loser: | |
7754 if (isTLS && desc == illegal_parameter) | |
7755 desc = decode_error; | |
7756 (void)SSL3_SendAlert(ss, alert_fatal, desc); | |
7757 loser: | |
7758 PORT_SetError(errCode); | |
7759 rv = SECFailure; | |
7760 done: | |
7761 ss->requestedCertTypes = NULL; | |
7762 if (arena != NULL) | |
7763 PORT_FreeArena(arena, PR_FALSE); | |
7764 return rv; | |
7765 } | |
7766 | |
7767 SECStatus | |
7768 ssl3_CompleteHandleCertificateRequest(sslSocket *ss, SECItem *algorithms, | |
7769 CERTDistNames *ca_list) | |
7770 { | |
7771 SECStatus rv; | |
7772 | |
7773 if (ss->getClientAuthData != NULL) { | |
7774 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == | |
7775 ssl_preinfo_all); | |
7776 /* XXX Should pass cert_types and algorithms in this call!! */ | |
7777 rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg, | |
7778 ss->fd, ca_list, | |
7779 &ss->ssl3.clientCertificate, | |
7780 &ss->ssl3.clientPrivateKey); | |
7781 } else { | |
7782 rv = SECFailure; /* force it to send a no_certificate alert */ | |
7783 } | |
7784 switch (rv) { | |
7785 case SECWouldBlock: /* getClientAuthData has put up a dialog box. */ | |
7786 ssl3_SetAlwaysBlock(ss); | |
7787 break; /* not an error */ | |
7788 | |
7789 case SECSuccess: | |
7790 /* check what the callback function returned */ | |
7791 if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) { | |
7792 /* we are missing either the key or cert */ | |
7793 if (ss->ssl3.clientCertificate) { | |
7794 /* got a cert, but no key - free it */ | |
7795 CERT_DestroyCertificate(ss->ssl3.clientCertificate); | |
7796 ss->ssl3.clientCertificate = NULL; | |
7797 } | |
7798 if (ss->ssl3.clientPrivateKey) { | |
7799 /* got a key, but no cert - free it */ | |
7800 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); | |
7801 ss->ssl3.clientPrivateKey = NULL; | |
7802 } | |
7803 goto send_no_certificate; | |
7804 } | |
7805 /* Setting ssl3.clientCertChain non-NULL will cause | |
7806 * ssl3_HandleServerHelloDone to call SendCertificate. | |
7807 */ | |
7808 ss->ssl3.clientCertChain = CERT_CertChainFromCert( | |
7809 ss->ssl3.clientCertificate, | |
7810 certUsageSSLClient, PR_FALSE); | |
7811 if (ss->ssl3.clientCertChain == NULL) { | |
7812 CERT_DestroyCertificate(ss->ssl3.clientCertificate); | |
7813 ss->ssl3.clientCertificate = NULL; | |
7814 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); | |
7815 ss->ssl3.clientPrivateKey = NULL; | |
7816 goto send_no_certificate; | |
7817 } | |
7818 if (ss->ssl3.hs.hashType == handshake_hash_single) { | |
7819 ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, algorithms); | |
7820 } | |
7821 break; /* not an error */ | |
7822 | |
7823 case SECFailure: | |
7824 default: | |
7825 send_no_certificate: | |
7826 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { | |
7827 ss->ssl3.sendEmptyCert = PR_TRUE; | |
7828 } else { | |
7829 (void)SSL3_SendAlert(ss, alert_warning, no_certificate); | |
7830 } | |
7831 rv = SECSuccess; | |
7832 break; | |
7833 } | |
7834 | |
7835 return rv; | |
7836 } | |
7837 | |
7838 /* | |
7839 * attempt to restart the handshake after asynchronously handling | |
7840 * a request for the client's certificate. | |
7841 * | |
7842 * inputs: | |
7843 * cert Client cert chosen by application. | |
7844 * Note: ssl takes this reference, and does not bump the | |
7845 * reference count. The caller should drop its reference | |
7846 * without calling CERT_DestroyCert after calling this function. | |
7847 * | |
7848 * key Private key associated with cert. This function takes | |
7849 * ownership of the private key, so the caller should drop its | |
7850 * reference without destroying the private key after this | |
7851 * function returns. | |
7852 * | |
7853 * certChain DER-encoded certs, client cert and its signers. | |
7854 * Note: ssl takes this reference, and does not copy the chain. | |
7855 * The caller should drop its reference without destroying the | |
7856 * chain. SSL will free the chain when it is done with it. | |
7857 * | |
7858 * Return value: XXX | |
7859 * | |
7860 * XXX This code only works on the initial handshake on a connection, XXX | |
7861 * It does not work on a subsequent handshake (redo). | |
7862 * | |
7863 * Caller holds 1stHandshakeLock. | |
7864 */ | |
7865 SECStatus | |
7866 ssl3_RestartHandshakeAfterCertReq(sslSocket *ss, | |
7867 CERTCertificate *cert, | |
7868 SECKEYPrivateKey *key, | |
7869 CERTCertificateList *certChain) | |
7870 { | |
7871 SECStatus rv = SECSuccess; | |
7872 | |
7873 /* XXX This code only works on the initial handshake on a connection, | |
7874 ** XXX It does not work on a subsequent handshake (redo). | |
7875 */ | |
7876 if (ss->handshake != 0) { | |
7877 ss->handshake = ssl_GatherRecord1stHandshake; | |
7878 ss->ssl3.clientCertificate = cert; | |
7879 ss->ssl3.clientPrivateKey = key; | |
7880 ss->ssl3.clientCertChain = certChain; | |
7881 if (!cert || !key || !certChain) { | |
7882 /* we are missing the key, cert, or cert chain */ | |
7883 if (ss->ssl3.clientCertificate) { | |
7884 CERT_DestroyCertificate(ss->ssl3.clientCertificate); | |
7885 ss->ssl3.clientCertificate = NULL; | |
7886 } | |
7887 if (ss->ssl3.clientPrivateKey) { | |
7888 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); | |
7889 ss->ssl3.clientPrivateKey = NULL; | |
7890 } | |
7891 if (ss->ssl3.clientCertChain != NULL) { | |
7892 CERT_DestroyCertificateList(ss->ssl3.clientCertChain); | |
7893 ss->ssl3.clientCertChain = NULL; | |
7894 } | |
7895 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { | |
7896 ss->ssl3.sendEmptyCert = PR_TRUE; | |
7897 } else { | |
7898 (void)SSL3_SendAlert(ss, alert_warning, no_certificate); | |
7899 } | |
7900 } | |
7901 } else { | |
7902 if (cert) { | |
7903 CERT_DestroyCertificate(cert); | |
7904 } | |
7905 if (key) { | |
7906 SECKEY_DestroyPrivateKey(key); | |
7907 } | |
7908 if (certChain) { | |
7909 CERT_DestroyCertificateList(certChain); | |
7910 } | |
7911 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
7912 rv = SECFailure; | |
7913 } | |
7914 return rv; | |
7915 } | |
7916 | |
7917 static SECStatus | |
7918 ssl3_CheckFalseStart(sslSocket *ss) | |
7919 { | |
7920 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
7921 PORT_Assert(!ss->ssl3.hs.authCertificatePending); | |
7922 PORT_Assert(!ss->ssl3.hs.canFalseStart); | |
7923 | |
7924 if (!ss->canFalseStartCallback) { | |
7925 SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start", | |
7926 SSL_GETPID(), ss->fd)); | |
7927 } else { | |
7928 PRBool maybeFalseStart; | |
7929 SECStatus rv; | |
7930 | |
7931 /* An attacker can control the selected ciphersuite so we only wish to | |
7932 * do False Start in the case that the selected ciphersuite is | |
7933 * sufficiently strong that the attack can gain no advantage. | |
7934 * Therefore we always require an 80-bit cipher. */ | |
7935 ssl_GetSpecReadLock(ss); | |
7936 maybeFalseStart = ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10; | |
7937 ssl_ReleaseSpecReadLock(ss); | |
7938 | |
7939 if (!maybeFalseStart) { | |
7940 SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher", | |
7941 SSL_GETPID(), ss->fd)); | |
7942 } else { | |
7943 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == | |
7944 ssl_preinfo_all); | |
7945 rv = (ss->canFalseStartCallback)(ss->fd, | |
7946 ss->canFalseStartCallbackData, | |
7947 &ss->ssl3.hs.canFalseStart); | |
7948 if (rv == SECSuccess) { | |
7949 SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s", | |
7950 SSL_GETPID(), ss->fd, | |
7951 ss->ssl3.hs.canFalseStart ? "TRUE" | |
7952 : "FALSE")); | |
7953 } else { | |
7954 SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)", | |
7955 SSL_GETPID(), ss->fd, | |
7956 PR_ErrorToName(PR_GetError()))); | |
7957 } | |
7958 return rv; | |
7959 } | |
7960 } | |
7961 | |
7962 ss->ssl3.hs.canFalseStart = PR_FALSE; | |
7963 return SECSuccess; | |
7964 } | |
7965 | |
7966 PRBool | |
7967 ssl3_WaitingForServerSecondRound(sslSocket *ss) | |
7968 { | |
7969 PRBool result; | |
7970 | |
7971 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
7972 | |
7973 switch (ss->ssl3.hs.ws) { | |
7974 case wait_new_session_ticket: | |
7975 case wait_change_cipher: | |
7976 case wait_finished: | |
7977 result = PR_TRUE; | |
7978 break; | |
7979 default: | |
7980 result = PR_FALSE; | |
7981 break; | |
7982 } | |
7983 | |
7984 return result; | |
7985 } | |
7986 | |
7987 static SECStatus ssl3_SendClientSecondRound(sslSocket *ss); | |
7988 | |
7989 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered | |
7990 * a complete ssl3 Server Hello Done message. | |
7991 * Caller must hold Handshake and RecvBuf locks. | |
7992 */ | |
7993 static SECStatus | |
7994 ssl3_HandleServerHelloDone(sslSocket *ss) | |
7995 { | |
7996 SECStatus rv; | |
7997 SSL3WaitState ws = ss->ssl3.hs.ws; | |
7998 | |
7999 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake", | |
8000 SSL_GETPID(), ss->fd)); | |
8001 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
8002 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
8003 | |
8004 /* Skipping CertificateRequest is always permitted. */ | |
8005 if (ws != wait_hello_done && | |
8006 ws != wait_cert_request) { | |
8007 SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
8008 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); | |
8009 return SECFailure; | |
8010 } | |
8011 | |
8012 rv = ssl3_SendClientSecondRound(ss); | |
8013 | |
8014 return rv; | |
8015 } | |
8016 | |
8017 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete. | |
8018 * | |
8019 * Caller must hold Handshake and RecvBuf locks. | |
8020 */ | |
8021 static SECStatus | |
8022 ssl3_SendClientSecondRound(sslSocket *ss) | |
8023 { | |
8024 SECStatus rv; | |
8025 PRBool sendClientCert; | |
8026 | |
8027 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
8028 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
8029 | |
8030 sendClientCert = !ss->ssl3.sendEmptyCert && | |
8031 ss->ssl3.clientCertChain != NULL && | |
8032 ss->ssl3.clientPrivateKey != NULL; | |
8033 | |
8034 if (!sendClientCert && | |
8035 ss->ssl3.hs.hashType == handshake_hash_single && | |
8036 ss->ssl3.hs.backupHash) { | |
8037 /* Don't need the backup handshake hash. */ | |
8038 PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); | |
8039 ss->ssl3.hs.backupHash = NULL; | |
8040 } | |
8041 | |
8042 /* We must wait for the server's certificate to be authenticated before | |
8043 * sending the client certificate in order to disclosing the client | |
8044 * certificate to an attacker that does not have a valid cert for the | |
8045 * domain we are connecting to. | |
8046 * | |
8047 * XXX: We should do the same for the NPN extension, but for that we | |
8048 * need an option to give the application the ability to leak the NPN | |
8049 * information to get better performance. | |
8050 * | |
8051 * During the initial handshake on a connection, we never send/receive | |
8052 * application data until we have authenticated the server's certificate; | |
8053 * i.e. we have fully authenticated the handshake before using the cipher | |
8054 * specs agreed upon for that handshake. During a renegotiation, we may | |
8055 * continue sending and receiving application data during the handshake | |
8056 * interleaved with the handshake records. If we were to send the client's | |
8057 * second round for a renegotiation before the server's certificate was | |
8058 * authenticated, then the application data sent/received after this point | |
8059 * would be using cipher spec that hadn't been authenticated. By waiting | |
8060 * until the server's certificate has been authenticated during | |
8061 * renegotiations, we ensure that renegotiations have the same property | |
8062 * as initial handshakes; i.e. we have fully authenticated the handshake | |
8063 * before using the cipher specs agreed upon for that handshake for | |
8064 * application data. | |
8065 */ | |
8066 if (ss->ssl3.hs.restartTarget) { | |
8067 PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget"); | |
8068 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
8069 return SECFailure; | |
8070 } | |
8071 if (ss->ssl3.hs.authCertificatePending && | |
8072 (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) { | |
8073 SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because" | |
8074 " certificate authentication is still pending.", | |
8075 SSL_GETPID(), ss->fd)); | |
8076 ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound; | |
8077 return SECWouldBlock; | |
8078 } | |
8079 | |
8080 ssl_GetXmitBufLock(ss); /*******************************/ | |
8081 | |
8082 if (ss->ssl3.sendEmptyCert) { | |
8083 ss->ssl3.sendEmptyCert = PR_FALSE; | |
8084 rv = ssl3_SendEmptyCertificate(ss); | |
8085 /* Don't send verify */ | |
8086 if (rv != SECSuccess) { | |
8087 goto loser; /* error code is set. */ | |
8088 } | |
8089 } else if (sendClientCert) { | |
8090 rv = ssl3_SendCertificate(ss); | |
8091 if (rv != SECSuccess) { | |
8092 goto loser; /* error code is set. */ | |
8093 } | |
8094 } | |
8095 | |
8096 rv = ssl3_SendClientKeyExchange(ss); | |
8097 if (rv != SECSuccess) { | |
8098 goto loser; /* err is set. */ | |
8099 } | |
8100 | |
8101 if (sendClientCert) { | |
8102 rv = ssl3_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey); | |
8103 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); | |
8104 ss->ssl3.clientPrivateKey = NULL; | |
8105 if (rv != SECSuccess) { | |
8106 goto loser; /* err is set. */ | |
8107 } | |
8108 } | |
8109 | |
8110 rv = ssl3_SendChangeCipherSpecs(ss); | |
8111 if (rv != SECSuccess) { | |
8112 goto loser; /* err code was set. */ | |
8113 } | |
8114 | |
8115 /* This must be done after we've set ss->ssl3.cwSpec in | |
8116 * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information | |
8117 * from cwSpec. This must be done before we call ssl3_CheckFalseStart | |
8118 * because the false start callback (if any) may need the information from | |
8119 * the functions that depend on this being set. | |
8120 */ | |
8121 ss->enoughFirstHsDone = PR_TRUE; | |
8122 | |
8123 if (!ss->firstHsDone) { | |
8124 /* XXX: If the server's certificate hasn't been authenticated by this | |
8125 * point, then we may be leaking this NPN message to an attacker. | |
8126 */ | |
8127 rv = ssl3_SendNextProto(ss); | |
8128 if (rv != SECSuccess) { | |
8129 goto loser; /* err code was set. */ | |
8130 } | |
8131 } | |
8132 | |
8133 rv = ssl3_SendChannelIDEncryptedExtensions(ss); | |
8134 if (rv != SECSuccess) { | |
8135 goto loser; /* err code was set. */ | |
8136 } | |
8137 | |
8138 if (!ss->firstHsDone) { | |
8139 if (ss->opt.enableFalseStart) { | |
8140 if (!ss->ssl3.hs.authCertificatePending) { | |
8141 /* When we fix bug 589047, we will need to know whether we are | |
8142 * false starting before we try to flush the client second | |
8143 * round to the network. With that in mind, we purposefully | |
8144 * call ssl3_CheckFalseStart before calling ssl3_SendFinished, | |
8145 * which includes a call to ssl3_FlushHandshake, so that | |
8146 * no application develops a reliance on such flushing being | |
8147 * done before its false start callback is called. | |
8148 */ | |
8149 ssl_ReleaseXmitBufLock(ss); | |
8150 rv = ssl3_CheckFalseStart(ss); | |
8151 ssl_GetXmitBufLock(ss); | |
8152 if (rv != SECSuccess) { | |
8153 goto loser; | |
8154 } | |
8155 } else { | |
8156 /* The certificate authentication and the server's Finished | |
8157 * message are racing each other. If the certificate | |
8158 * authentication wins, then we will try to false start in | |
8159 * ssl3_AuthCertificateComplete. | |
8160 */ | |
8161 SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because" | |
8162 " certificate authentication is still pending.", | |
8163 SSL_GETPID(), ss->fd)); | |
8164 } | |
8165 } | |
8166 } | |
8167 | |
8168 rv = ssl3_SendFinished(ss, 0); | |
8169 if (rv != SECSuccess) { | |
8170 goto loser; /* err code was set. */ | |
8171 } | |
8172 | |
8173 ssl_ReleaseXmitBufLock(ss); /*******************************/ | |
8174 | |
8175 if (!ss->ssl3.hs.isResuming && | |
8176 ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) { | |
8177 /* If we are negotiating ChannelID on a full handshake then we record | |
8178 * the handshake hashes in |sid| at this point. They will be needed in | |
8179 * the event that we resume this session and use ChannelID on the | |
8180 * resumption handshake. */ | |
8181 SSL3Hashes hashes; | |
8182 SECItem *originalHandshakeHash = | |
8183 &ss->sec.ci.sid->u.ssl3.originalHandshakeHash; | |
8184 PORT_Assert(ss->sec.ci.sid->cached == never_cached); | |
8185 | |
8186 ssl_GetSpecReadLock(ss); | |
8187 PORT_Assert(ss->version > SSL_LIBRARY_VERSION_3_0); | |
8188 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0); | |
8189 ssl_ReleaseSpecReadLock(ss); | |
8190 if (rv != SECSuccess) { | |
8191 return rv; | |
8192 } | |
8193 | |
8194 PORT_Assert(originalHandshakeHash->len == 0); | |
8195 originalHandshakeHash->data = PORT_Alloc(hashes.len); | |
8196 if (!originalHandshakeHash->data) | |
8197 return SECFailure; | |
8198 originalHandshakeHash->len = hashes.len; | |
8199 memcpy(originalHandshakeHash->data, hashes.u.raw, hashes.len); | |
8200 } | |
8201 | |
8202 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) | |
8203 ss->ssl3.hs.ws = wait_new_session_ticket; | |
8204 else | |
8205 ss->ssl3.hs.ws = wait_change_cipher; | |
8206 | |
8207 PORT_Assert(ssl3_WaitingForServerSecondRound(ss)); | |
8208 | |
8209 return SECSuccess; | |
8210 | |
8211 loser: | |
8212 ssl_ReleaseXmitBufLock(ss); | |
8213 return rv; | |
8214 } | |
8215 | |
8216 /* | |
8217 * Routines used by servers | |
8218 */ | |
8219 static SECStatus | |
8220 ssl3_SendHelloRequest(sslSocket *ss) | |
8221 { | |
8222 SECStatus rv; | |
8223 | |
8224 SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(), | |
8225 ss->fd)); | |
8226 | |
8227 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
8228 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
8229 | |
8230 rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0); | |
8231 if (rv != SECSuccess) { | |
8232 return rv; /* err set by AppendHandshake */ | |
8233 } | |
8234 rv = ssl3_FlushHandshake(ss, 0); | |
8235 if (rv != SECSuccess) { | |
8236 return rv; /* error code set by ssl3_FlushHandshake */ | |
8237 } | |
8238 ss->ssl3.hs.ws = wait_client_hello; | |
8239 return SECSuccess; | |
8240 } | |
8241 | |
8242 /* | |
8243 * Called from: | |
8244 * ssl3_HandleClientHello() | |
8245 */ | |
8246 static SECComparison | |
8247 ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2) | |
8248 { | |
8249 if (!name1 != !name2) { | |
8250 return SECLessThan; | |
8251 } | |
8252 if (!name1) { | |
8253 return SECEqual; | |
8254 } | |
8255 if (name1->type != name2->type) { | |
8256 return SECLessThan; | |
8257 } | |
8258 return SECITEM_CompareItem(name1, name2); | |
8259 } | |
8260 | |
8261 /* Sets memory error when returning NULL. | |
8262 * Called from: | |
8263 * ssl3_SendClientHello() | |
8264 * ssl3_HandleServerHello() | |
8265 * ssl3_HandleClientHello() | |
8266 * ssl3_HandleV2ClientHello() | |
8267 */ | |
8268 sslSessionID * | |
8269 ssl3_NewSessionID(sslSocket *ss, PRBool is_server) | |
8270 { | |
8271 sslSessionID *sid; | |
8272 | |
8273 sid = PORT_ZNew(sslSessionID); | |
8274 if (sid == NULL) | |
8275 return sid; | |
8276 | |
8277 if (is_server) { | |
8278 const SECItem *srvName; | |
8279 SECStatus rv = SECSuccess; | |
8280 | |
8281 ssl_GetSpecReadLock(ss); /********************************/ | |
8282 srvName = &ss->ssl3.prSpec->srvVirtName; | |
8283 if (srvName->len && srvName->data) { | |
8284 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName); | |
8285 } | |
8286 ssl_ReleaseSpecReadLock(ss); /************************************/ | |
8287 if (rv != SECSuccess) { | |
8288 PORT_Free(sid); | |
8289 return NULL; | |
8290 } | |
8291 } | |
8292 sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID); | |
8293 sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url); | |
8294 sid->addr = ss->sec.ci.peer; | |
8295 sid->port = ss->sec.ci.port; | |
8296 sid->references = 1; | |
8297 sid->cached = never_cached; | |
8298 sid->version = ss->version; | |
8299 | |
8300 sid->u.ssl3.keys.resumable = PR_TRUE; | |
8301 sid->u.ssl3.policy = SSL_ALLOWED; | |
8302 sid->u.ssl3.clientWriteKey = NULL; | |
8303 sid->u.ssl3.serverWriteKey = NULL; | |
8304 sid->u.ssl3.keys.extendedMasterSecretUsed = PR_FALSE; | |
8305 | |
8306 if (is_server) { | |
8307 SECStatus rv; | |
8308 int pid = SSL_GETPID(); | |
8309 | |
8310 sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES; | |
8311 sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff; | |
8312 sid->u.ssl3.sessionID[1] = pid & 0xff; | |
8313 rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2, | |
8314 SSL3_SESSIONID_BYTES - 2); | |
8315 if (rv != SECSuccess) { | |
8316 ssl_FreeSID(sid); | |
8317 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); | |
8318 return NULL; | |
8319 } | |
8320 } | |
8321 return sid; | |
8322 } | |
8323 | |
8324 /* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */ | |
8325 static SECStatus | |
8326 ssl3_SendServerHelloSequence(sslSocket *ss) | |
8327 { | |
8328 const ssl3KEADef *kea_def; | |
8329 SECStatus rv; | |
8330 | |
8331 SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence", | |
8332 SSL_GETPID(), ss->fd)); | |
8333 | |
8334 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
8335 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
8336 | |
8337 rv = ssl3_SendServerHello(ss); | |
8338 if (rv != SECSuccess) { | |
8339 return rv; /* err code is set. */ | |
8340 } | |
8341 rv = ssl3_SendCertificate(ss); | |
8342 if (rv != SECSuccess) { | |
8343 return rv; /* error code is set. */ | |
8344 } | |
8345 rv = ssl3_SendCertificateStatus(ss); | |
8346 if (rv != SECSuccess) { | |
8347 return rv; /* error code is set. */ | |
8348 } | |
8349 /* We have to do this after the call to ssl3_SendServerHello, | |
8350 * because kea_def is set up by ssl3_SendServerHello(). | |
8351 */ | |
8352 kea_def = ss->ssl3.hs.kea_def; | |
8353 ss->ssl3.hs.usedStepDownKey = PR_FALSE; | |
8354 | |
8355 if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) { | |
8356 /* see if we can legally use the key in the cert. */ | |
8357 unsigned int keyLen; /* bytes */ | |
8358 | |
8359 keyLen = PK11_GetPrivateModulusLen( | |
8360 ss->serverCerts[kea_def->exchKeyType].SERVERKEY); | |
8361 | |
8362 if (keyLen > 0 && | |
8363 keyLen * BPB <= kea_def->key_size_limit) { | |
8364 /* XXX AND cert is not signing only!! */ | |
8365 /* just fall through and use it. */ | |
8366 } else if (ss->stepDownKeyPair != NULL) { | |
8367 ss->ssl3.hs.usedStepDownKey = PR_TRUE; | |
8368 rv = ssl3_SendServerKeyExchange(ss); | |
8369 if (rv != SECSuccess) { | |
8370 return rv; /* err code was set. */ | |
8371 } | |
8372 } else { | |
8373 #ifndef HACKED_EXPORT_SERVER | |
8374 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); | |
8375 return rv; | |
8376 #endif | |
8377 } | |
8378 } else if (kea_def->ephemeral) { | |
8379 rv = ssl3_SendServerKeyExchange(ss); | |
8380 if (rv != SECSuccess) { | |
8381 return rv; /* err code was set. */ | |
8382 } | |
8383 } | |
8384 | |
8385 if (ss->opt.requestCertificate) { | |
8386 rv = ssl3_SendCertificateRequest(ss); | |
8387 if (rv != SECSuccess) { | |
8388 return rv; /* err code is set. */ | |
8389 } | |
8390 } | |
8391 rv = ssl3_SendServerHelloDone(ss); | |
8392 if (rv != SECSuccess) { | |
8393 return rv; /* err code is set. */ | |
8394 } | |
8395 | |
8396 ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert | |
8397 : wait_client_key; | |
8398 return SECSuccess; | |
8399 } | |
8400 | |
8401 /* An empty TLS Renegotiation Info (RI) extension */ | |
8402 static const PRUint8 emptyRIext[5] = { 0xff, 0x01, 0x00, 0x01, 0x00 }; | |
8403 | |
8404 static PRBool | |
8405 ssl3_KEAAllowsSessionTicket(SSL3KeyExchangeAlgorithm kea) | |
8406 { | |
8407 switch (kea) { | |
8408 case kea_dhe_dss: | |
8409 case kea_dhe_dss_export: | |
8410 case kea_dh_dss_export: | |
8411 case kea_dh_dss: | |
8412 /* TODO: Fix session tickets for DSS. The server code rejects the | |
8413 * session ticket received from the client. Bug 1174677 */ | |
8414 return PR_FALSE; | |
8415 default: | |
8416 return PR_TRUE; | |
8417 }; | |
8418 } | |
8419 | |
8420 static void | |
8421 ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid) | |
8422 { | |
8423 PLArenaPool *arena; | |
8424 ssl3CertNode *lastCert = NULL; | |
8425 ssl3CertNode *certs = NULL; | |
8426 int i; | |
8427 | |
8428 if (!sid->peerCertChain[0]) | |
8429 return; | |
8430 PORT_Assert(!ss->ssl3.peerCertArena); | |
8431 PORT_Assert(!ss->ssl3.peerCertChain); | |
8432 ss->ssl3.peerCertArena = arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); | |
8433 for (i = 0; i < MAX_PEER_CERT_CHAIN_SIZE && sid->peerCertChain[i]; i++) { | |
8434 ssl3CertNode *c = PORT_ArenaNew(arena, ssl3CertNode); | |
8435 c->cert = CERT_DupCertificate(sid->peerCertChain[i]); | |
8436 c->next = NULL; | |
8437 if (lastCert) { | |
8438 lastCert->next = c; | |
8439 } else { | |
8440 certs = c; | |
8441 } | |
8442 lastCert = c; | |
8443 } | |
8444 ss->ssl3.peerCertChain = certs; | |
8445 } | |
8446 | |
8447 static void | |
8448 ssl3_CopyPeerCertsToSID(ssl3CertNode *certs, sslSessionID *sid) | |
8449 { | |
8450 int i = 0; | |
8451 ssl3CertNode *c = certs; | |
8452 for (; i < MAX_PEER_CERT_CHAIN_SIZE && c; i++, c = c->next) { | |
8453 PORT_Assert(!sid->peerCertChain[i]); | |
8454 sid->peerCertChain[i] = CERT_DupCertificate(c->cert); | |
8455 } | |
8456 } | |
8457 | |
8458 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete | |
8459 * ssl3 Client Hello message. | |
8460 * Caller must hold Handshake and RecvBuf locks. | |
8461 */ | |
8462 static SECStatus | |
8463 ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
8464 { | |
8465 sslSessionID *sid = NULL; | |
8466 PRInt32 tmp; | |
8467 unsigned int i; | |
8468 int j; | |
8469 SECStatus rv; | |
8470 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; | |
8471 SSL3AlertDescription desc = illegal_parameter; | |
8472 SSL3AlertLevel level = alert_fatal; | |
8473 SSL3ProtocolVersion version; | |
8474 SECItem sidBytes = { siBuffer, NULL, 0 }; | |
8475 SECItem cookieBytes = { siBuffer, NULL, 0 }; | |
8476 SECItem suites = { siBuffer, NULL, 0 }; | |
8477 SECItem comps = { siBuffer, NULL, 0 }; | |
8478 PRBool haveSpecWriteLock = PR_FALSE; | |
8479 PRBool haveXmitBufLock = PR_FALSE; | |
8480 PRBool canOfferSessionTicket = PR_FALSE; | |
8481 PRBool isTLS13 = PR_FALSE; | |
8482 | |
8483 SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake", | |
8484 SSL_GETPID(), ss->fd)); | |
8485 | |
8486 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
8487 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
8488 PORT_Assert(ss->ssl3.initialized); | |
8489 ss->ssl3.hs.preliminaryInfo = 0; | |
8490 | |
8491 if (!ss->sec.isServer || | |
8492 (ss->ssl3.hs.ws != wait_client_hello && | |
8493 ss->ssl3.hs.ws != idle_handshake)) { | |
8494 desc = unexpected_message; | |
8495 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; | |
8496 goto alert_loser; | |
8497 } | |
8498 if (ss->ssl3.hs.ws == idle_handshake) { | |
8499 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { | |
8500 desc = unexpected_message; | |
8501 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; | |
8502 goto alert_loser; | |
8503 } | |
8504 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { | |
8505 desc = no_renegotiation; | |
8506 level = alert_warning; | |
8507 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; | |
8508 goto alert_loser; | |
8509 } | |
8510 } | |
8511 | |
8512 /* Get peer name of client */ | |
8513 rv = ssl_GetPeerInfo(ss); | |
8514 if (rv != SECSuccess) { | |
8515 return rv; /* error code is set. */ | |
8516 } | |
8517 | |
8518 /* Clearing the handshake pointers so that ssl_Do1stHandshake won't | |
8519 * call ssl2_HandleMessage. | |
8520 * | |
8521 * The issue here is that TLS ordinarily starts out in | |
8522 * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility | |
8523 * code paths. That function zeroes these next pointers. But with DTLS, | |
8524 * we don't even try to do the v2 ClientHello so we skip that function | |
8525 * and need to reset these values here. | |
8526 */ | |
8527 if (IS_DTLS(ss)) { | |
8528 ss->nextHandshake = 0; | |
8529 ss->securityHandshake = 0; | |
8530 } | |
8531 | |
8532 /* We might be starting session renegotiation in which case we should | |
8533 * clear previous state. | |
8534 */ | |
8535 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); | |
8536 ss->statelessResume = PR_FALSE; | |
8537 | |
8538 if (IS_DTLS(ss)) { | |
8539 dtls_RehandshakeCleanup(ss); | |
8540 } | |
8541 | |
8542 tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); | |
8543 if (tmp < 0) | |
8544 goto loser; /* malformed, alert already sent */ | |
8545 | |
8546 /* Translate the version */ | |
8547 if (IS_DTLS(ss)) { | |
8548 ss->clientHelloVersion = version = | |
8549 dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp); | |
8550 } else { | |
8551 ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp; | |
8552 } | |
8553 | |
8554 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); | |
8555 if (rv != SECSuccess) { | |
8556 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version | |
8557 : handshake_failure; | |
8558 errCode = SSL_ERROR_UNSUPPORTED_VERSION; | |
8559 goto alert_loser; | |
8560 } | |
8561 isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3; | |
8562 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; | |
8563 | |
8564 rv = ssl3_InitHandshakeHashes(ss); | |
8565 if (rv != SECSuccess) { | |
8566 desc = internal_error; | |
8567 errCode = PORT_GetError(); | |
8568 goto alert_loser; | |
8569 } | |
8570 | |
8571 /* Generate the Server Random now so it is available | |
8572 * when we process the ClientKeyShare in TLS 1.3 */ | |
8573 rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random); | |
8574 if (rv != SECSuccess) { | |
8575 errCode = SSL_ERROR_GENERATE_RANDOM_FAILURE; | |
8576 goto loser; | |
8577 } | |
8578 | |
8579 /* | |
8580 * [draft-ietf-tls-tls13-11 Section 6.3.1.1]. | |
8581 * TLS 1.3 server implementations which respond to a ClientHello with a | |
8582 * client_version indicating TLS 1.2 or below MUST set the first eight | |
8583 * bytes of their Random value to the bytes: | |
8584 * | |
8585 * 44 4F 57 4E 47 52 44 01 | |
8586 * | |
8587 * TLS 1.2 server implementations which respond to a ClientHello with a | |
8588 * client_version indicating TLS 1.1 or below SHOULD set the first eight | |
8589 * bytes of their Random value to the bytes: | |
8590 * | |
8591 * 44 4F 57 4E 47 52 44 00 | |
8592 * | |
8593 * TODO(ekr@rtfm.com): Note this change was not added in the SSLv2 | |
8594 * compat processing code since that will most likely be removed before | |
8595 * we ship the final version of TLS 1.3. | |
8596 */ | |
8597 if (ss->vrange.max > ss->version) { | |
8598 switch (ss->vrange.max) { | |
8599 case SSL_LIBRARY_VERSION_TLS_1_3: | |
8600 PORT_Memcpy(ss->ssl3.hs.server_random.rand, | |
8601 tls13_downgrade_random, | |
8602 sizeof(tls13_downgrade_random)); | |
8603 break; | |
8604 case SSL_LIBRARY_VERSION_TLS_1_2: | |
8605 PORT_Memcpy(ss->ssl3.hs.server_random.rand, | |
8606 tls12_downgrade_random, | |
8607 sizeof(tls12_downgrade_random)); | |
8608 break; | |
8609 default: | |
8610 /* Do not change random. */ | |
8611 break; | |
8612 } | |
8613 } | |
8614 | |
8615 /* grab the client random data. */ | |
8616 rv = ssl3_ConsumeHandshake( | |
8617 ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length); | |
8618 if (rv != SECSuccess) { | |
8619 goto loser; /* malformed */ | |
8620 } | |
8621 | |
8622 /* grab the client's SID, if present. */ | |
8623 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); | |
8624 if (rv != SECSuccess) { | |
8625 goto loser; /* malformed */ | |
8626 } | |
8627 | |
8628 /* grab the client's cookie, if present. */ | |
8629 if (IS_DTLS(ss)) { | |
8630 rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length); | |
8631 if (rv != SECSuccess) { | |
8632 goto loser; /* malformed */ | |
8633 } | |
8634 } | |
8635 | |
8636 /* grab the list of cipher suites. */ | |
8637 rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length); | |
8638 if (rv != SECSuccess) { | |
8639 goto loser; /* malformed */ | |
8640 } | |
8641 | |
8642 /* If the ClientHello version is less than our maximum version, check for a | |
8643 * TLS_FALLBACK_SCSV and reject the connection if found. */ | |
8644 if (ss->vrange.max > ss->clientHelloVersion) { | |
8645 for (i = 0; i + 1 < suites.len; i += 2) { | |
8646 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; | |
8647 if (suite_i != TLS_FALLBACK_SCSV) | |
8648 continue; | |
8649 desc = inappropriate_fallback; | |
8650 errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; | |
8651 goto alert_loser; | |
8652 } | |
8653 } | |
8654 | |
8655 /* grab the list of compression methods. */ | |
8656 rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length); | |
8657 if (rv != SECSuccess) { | |
8658 goto loser; /* malformed */ | |
8659 } | |
8660 | |
8661 /* TLS 1.3 requires that compression be empty */ | |
8662 if (isTLS13) { | |
8663 if (comps.len != 1 || comps.data[0] != ssl_compression_null) { | |
8664 goto loser; | |
8665 } | |
8666 } | |
8667 desc = handshake_failure; | |
8668 | |
8669 /* Handle TLS hello extensions for SSL3 & TLS. We do not know if | |
8670 * we are restarting a previous session until extensions have been | |
8671 * parsed, since we might have received a SessionTicket extension. | |
8672 * Note: we allow extensions even when negotiating SSL3 for the sake | |
8673 * of interoperability (and backwards compatibility). | |
8674 */ | |
8675 | |
8676 if (length) { | |
8677 /* Get length of hello extensions */ | |
8678 PRInt32 extension_length; | |
8679 extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); | |
8680 if (extension_length < 0) { | |
8681 goto loser; /* alert already sent */ | |
8682 } | |
8683 if (extension_length != length) { | |
8684 ssl3_DecodeError(ss); /* send alert */ | |
8685 goto loser; | |
8686 } | |
8687 rv = ssl3_HandleHelloExtensions(ss, &b, &length, client_hello); | |
8688 if (rv != SECSuccess) { | |
8689 goto loser; /* malformed */ | |
8690 } | |
8691 } | |
8692 if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { | |
8693 /* If we didn't receive an RI extension, look for the SCSV, | |
8694 * and if found, treat it just like an empty RI extension | |
8695 * by processing a local copy of an empty RI extension. | |
8696 */ | |
8697 for (i = 0; i + 1 < suites.len; i += 2) { | |
8698 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; | |
8699 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { | |
8700 SSL3Opaque *b2 = (SSL3Opaque *)emptyRIext; | |
8701 PRUint32 L2 = sizeof emptyRIext; | |
8702 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2, client_hello); | |
8703 break; | |
8704 } | |
8705 } | |
8706 } | |
8707 if (ss->firstHsDone && | |
8708 (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN || | |
8709 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) && | |
8710 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { | |
8711 desc = no_renegotiation; | |
8712 level = alert_warning; | |
8713 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; | |
8714 goto alert_loser; | |
8715 } | |
8716 if ((ss->opt.requireSafeNegotiation || | |
8717 (ss->firstHsDone && ss->peerRequestedProtection)) && | |
8718 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { | |
8719 desc = handshake_failure; | |
8720 errCode = SSL_ERROR_UNSAFE_NEGOTIATION; | |
8721 goto alert_loser; | |
8722 } | |
8723 | |
8724 /* We do stateful resumes only if either of the following | |
8725 * conditions are satisfied: (1) the client does not support the | |
8726 * session ticket extension, or (2) the client support the session | |
8727 * ticket extension, but sent an empty ticket. | |
8728 */ | |
8729 if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) || | |
8730 ss->xtnData.emptySessionTicket) { | |
8731 if (sidBytes.len > 0 && !ss->opt.noCache) { | |
8732 SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%0
8x%08x%08x%08x", | |
8733 SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0], | |
8734 ss->sec.ci.peer.pr_s6_addr32[1], | |
8735 ss->sec.ci.peer.pr_s6_addr32[2], | |
8736 ss->sec.ci.peer.pr_s6_addr32[3])); | |
8737 if (ssl_sid_lookup) { | |
8738 sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data, | |
8739 sidBytes.len, ss->dbHandle); | |
8740 } else { | |
8741 errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED; | |
8742 goto loser; | |
8743 } | |
8744 } | |
8745 } else if (ss->statelessResume) { | |
8746 /* Fill in the client's session ID if doing a stateless resume. | |
8747 * (When doing stateless resumes, server echos client's SessionID.) | |
8748 */ | |
8749 sid = ss->sec.ci.sid; | |
8750 PORT_Assert(sid != NULL); /* Should have already been filled in.*/ | |
8751 | |
8752 if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) { | |
8753 sid->u.ssl3.sessionIDLength = sidBytes.len; | |
8754 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, | |
8755 sidBytes.len); | |
8756 sid->u.ssl3.sessionIDLength = sidBytes.len; | |
8757 } else { | |
8758 sid->u.ssl3.sessionIDLength = 0; | |
8759 } | |
8760 ss->sec.ci.sid = NULL; | |
8761 } | |
8762 | |
8763 /* We only send a session ticket extension if the client supports | |
8764 * the extension and we are unable to do either a stateful or | |
8765 * stateless resume. | |
8766 * | |
8767 * TODO: send a session ticket if performing a stateful | |
8768 * resumption. (As per RFC4507, a server may issue a session | |
8769 * ticket while doing a (stateless or stateful) session resume, | |
8770 * but OpenSSL-0.9.8g does not accept session tickets while | |
8771 * resuming.) | |
8772 */ | |
8773 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) { | |
8774 canOfferSessionTicket = PR_TRUE; | |
8775 } | |
8776 | |
8777 if (sid != NULL) { | |
8778 /* We've found a session cache entry for this client. | |
8779 * Now, if we're going to require a client-auth cert, | |
8780 * and we don't already have this client's cert in the session cache, | |
8781 * and this is the first handshake on this connection (not a redo), | |
8782 * then drop this old cache entry and start a new session. | |
8783 */ | |
8784 if ((sid->peerCert == NULL) && ss->opt.requestCertificate && | |
8785 ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || | |
8786 (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) || | |
8787 ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) && | |
8788 !ss->firstHsDone))) { | |
8789 | |
8790 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok); | |
8791 if (ss->sec.uncache) | |
8792 ss->sec.uncache(sid); | |
8793 ssl_FreeSID(sid); | |
8794 sid = NULL; | |
8795 } | |
8796 } | |
8797 | |
8798 #ifndef NSS_DISABLE_ECC | |
8799 /* Disable any ECC cipher suites for which we have no cert. */ | |
8800 ssl3_FilterECCipherSuitesByServerCerts(ss); | |
8801 #endif | |
8802 | |
8803 if (IS_DTLS(ss)) { | |
8804 ssl3_DisableNonDTLSSuites(ss); | |
8805 } | |
8806 | |
8807 #ifdef PARANOID | |
8808 /* Look for a matching cipher suite. */ | |
8809 j = ssl3_config_match_init(ss); | |
8810 if (j <= 0) { /* no ciphers are working/supported by PK11 *
/ | |
8811 errCode = PORT_GetError(); /* error code is already set. */ | |
8812 goto alert_loser; | |
8813 } | |
8814 #endif | |
8815 | |
8816 /* If we already have a session for this client, be sure to pick the | |
8817 ** same cipher suite and compression method we picked before. | |
8818 ** This is not a loop, despite appearances. | |
8819 */ | |
8820 if (sid) | |
8821 do { | |
8822 ssl3CipherSuiteCfg *suite; | |
8823 #ifdef PARANOID | |
8824 SSLVersionRange vrange = { ss->version, ss->version }; | |
8825 #endif | |
8826 | |
8827 /* Check that the cached compression method is still enabled. */ | |
8828 if (!compressionEnabled(ss, sid->u.ssl3.compression)) | |
8829 break; | |
8830 | |
8831 /* Check that the cached compression method is in the client's list
*/ | |
8832 for (i = 0; i < comps.len; i++) { | |
8833 if (comps.data[i] == sid->u.ssl3.compression) | |
8834 break; | |
8835 } | |
8836 if (i == comps.len) | |
8837 break; | |
8838 | |
8839 suite = ss->cipherSuites; | |
8840 /* Find the entry for the cipher suite used in the cached session. *
/ | |
8841 for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) { | |
8842 if (suite->cipher_suite == sid->u.ssl3.cipherSuite) | |
8843 break; | |
8844 } | |
8845 PORT_Assert(j > 0); | |
8846 if (j <= 0) | |
8847 break; | |
8848 #ifdef PARANOID | |
8849 /* Double check that the cached cipher suite is still enabled, | |
8850 * implemented, and allowed by policy. Might have been disabled. | |
8851 * The product policy won't change during the process lifetime. | |
8852 * Implemented ("isPresent") shouldn't change for servers. | |
8853 */ | |
8854 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) | |
8855 break; | |
8856 #else | |
8857 if (!suite->enabled) | |
8858 break; | |
8859 #endif | |
8860 /* Double check that the cached cipher suite is in the client's list
*/ | |
8861 for (i = 0; i + 1 < suites.len; i += 2) { | |
8862 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; | |
8863 if (suite_i == suite->cipher_suite) { | |
8864 ss->ssl3.hs.cipher_suite = | |
8865 suite->cipher_suite; | |
8866 ss->ssl3.hs.suite_def = | |
8867 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); | |
8868 ss->ssl3.hs.kea_def = | |
8869 &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; | |
8870 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; | |
8871 | |
8872 /* Use the cached compression method. */ | |
8873 ss->ssl3.hs.compression = | |
8874 sid->u.ssl3.compression; | |
8875 goto compression_found; | |
8876 } | |
8877 } | |
8878 } while (0); | |
8879 | |
8880 /* START A NEW SESSION */ | |
8881 | |
8882 #ifndef PARANOID | |
8883 /* Look for a matching cipher suite. */ | |
8884 j = ssl3_config_match_init(ss); | |
8885 if (j <= 0) { /* no ciphers are working/supported by PK11 *
/ | |
8886 errCode = PORT_GetError(); /* error code is already set. */ | |
8887 goto alert_loser; | |
8888 } | |
8889 #endif | |
8890 | |
8891 /* Select a cipher suite. | |
8892 ** | |
8893 ** NOTE: This suite selection algorithm should be the same as the one in | |
8894 ** ssl3_HandleV2ClientHello(). | |
8895 ** | |
8896 ** If TLS 1.0 is enabled, we could handle the case where the client | |
8897 ** offered TLS 1.1 but offered only export cipher suites by choosing TLS | |
8898 ** 1.0 and selecting one of those export cipher suites. However, a secure | |
8899 ** TLS 1.1 client should not have export cipher suites enabled at all, | |
8900 ** and a TLS 1.1 client should definitely not be offering *only* export | |
8901 ** cipher suites. Therefore, we refuse to negotiate export cipher suites | |
8902 ** with any client that indicates support for TLS 1.1 or higher when we | |
8903 ** (the server) have TLS 1.1 support enabled. | |
8904 */ | |
8905 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { | |
8906 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; | |
8907 SSLVersionRange vrange = { ss->version, ss->version }; | |
8908 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) { | |
8909 continue; | |
8910 } | |
8911 for (i = 0; i + 1 < suites.len; i += 2) { | |
8912 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; | |
8913 if (suite_i == suite->cipher_suite) { | |
8914 ss->ssl3.hs.cipher_suite = suite->cipher_suite; | |
8915 ss->ssl3.hs.suite_def = | |
8916 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); | |
8917 ss->ssl3.hs.kea_def = | |
8918 &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; | |
8919 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_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 if (canOfferSessionTicket) | |
8929 canOfferSessionTicket = ssl3_KEAAllowsSessionTicket( | |
8930 ss->ssl3.hs.suite_def->key_exchange_alg); | |
8931 | |
8932 if (canOfferSessionTicket) { | |
8933 ssl3_RegisterServerHelloExtensionSender(ss, | |
8934 ssl_session_ticket_xtn, ssl3_Sen
dSessionTicketXtn); | |
8935 } | |
8936 | |
8937 /* Select a compression algorithm. */ | |
8938 for (i = 0; i < comps.len; i++) { | |
8939 if (!compressionEnabled(ss, comps.data[i])) | |
8940 continue; | |
8941 for (j = 0; j < compressionMethodsCount; j++) { | |
8942 if (comps.data[i] == compressions[j]) { | |
8943 ss->ssl3.hs.compression = | |
8944 (SSLCompressionMethod)compressions[j]; | |
8945 goto compression_found; | |
8946 } | |
8947 } | |
8948 } | |
8949 errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; | |
8950 /* null compression must be supported */ | |
8951 goto alert_loser; | |
8952 | |
8953 compression_found: | |
8954 suites.data = NULL; | |
8955 comps.data = NULL; | |
8956 | |
8957 ss->sec.send = ssl3_SendApplicationData; | |
8958 | |
8959 /* If there are any failures while processing the old sid, | |
8960 * we don't consider them to be errors. Instead, We just behave | |
8961 * as if the client had sent us no sid to begin with, and make a new one. | |
8962 * The exception here is attempts to resume extended_master_secret | |
8963 * sessions without the extension, which causes an alert. | |
8964 */ | |
8965 if (sid != NULL) | |
8966 do { | |
8967 ssl3CipherSpec *pwSpec; | |
8968 SECItem wrappedMS; /* wrapped key */ | |
8969 | |
8970 if (sid->version != ss->version || | |
8971 sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite || | |
8972 sid->u.ssl3.compression != ss->ssl3.hs.compression) { | |
8973 break; /* not an error */ | |
8974 } | |
8975 | |
8976 /* [draft-ietf-tls-session-hash-06; Section 5.3] | |
8977 * o If the original session did not use the "extended_master_secre
t" | |
8978 * extension but the new ClientHello contains the extension, then
the | |
8979 * server MUST NOT perform the abbreviated handshake. Instead, i
t | |
8980 * SHOULD continue with a full handshake (as described in | |
8981 * Section 5.2) to negotiate a new session. | |
8982 * | |
8983 * o If the original session used the "extended_master_secret" | |
8984 * extension but the new ClientHello does not contain the extensi
on, | |
8985 * the server MUST abort the abbreviated handshake. | |
8986 */ | |
8987 if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { | |
8988 if (!sid->u.ssl3.keys.extendedMasterSecretUsed) { | |
8989 break; /* not an error */ | |
8990 } | |
8991 } else { | |
8992 if (sid->u.ssl3.keys.extendedMasterSecretUsed) { | |
8993 /* Note: we do not destroy the session */ | |
8994 desc = handshake_failure; | |
8995 errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET; | |
8996 goto alert_loser; | |
8997 } | |
8998 } | |
8999 | |
9000 if (ss->sec.ci.sid) { | |
9001 if (ss->sec.uncache) | |
9002 ss->sec.uncache(ss->sec.ci.sid); | |
9003 PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but
... */ | |
9004 if (ss->sec.ci.sid != sid) { | |
9005 ssl_FreeSID(ss->sec.ci.sid); | |
9006 } | |
9007 ss->sec.ci.sid = NULL; | |
9008 } | |
9009 /* we need to resurrect the master secret.... */ | |
9010 | |
9011 ssl_GetSpecWriteLock(ss); | |
9012 haveSpecWriteLock = PR_TRUE; | |
9013 pwSpec = ss->ssl3.pwSpec; | |
9014 if (sid->u.ssl3.keys.msIsWrapped) { | |
9015 PK11SymKey *wrapKey; /* wrapping key */ | |
9016 CK_FLAGS keyFlags = 0; | |
9017 #ifndef NO_PKCS11_BYPASS | |
9018 if (ss->opt.bypassPKCS11) { | |
9019 /* we cannot restart a non-bypass session in a | |
9020 ** bypass socket. | |
9021 */ | |
9022 break; | |
9023 } | |
9024 #endif | |
9025 | |
9026 wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType, | |
9027 sid->u.ssl3.masterWrapMech, | |
9028 ss->pkcs11PinArg); | |
9029 if (!wrapKey) { | |
9030 /* we have a SID cache entry, but no wrapping key for it???
*/ | |
9031 break; | |
9032 } | |
9033 | |
9034 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ | |
9035 keyFlags = | |
9036 CKF_SIGN | CKF_VERIFY; | |
9037 } | |
9038 | |
9039 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; | |
9040 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; | |
9041 | |
9042 /* unwrap the master secret. */ | |
9043 pwSpec->master_secret = | |
9044 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMe
ch, | |
9045 NULL, &wrappedMS, CKM_SSL3_MASTER
_KEY_DERIVE, | |
9046 CKA_DERIVE, sizeof(SSL3MasterSecr
et), keyFlags); | |
9047 PK11_FreeSymKey(wrapKey); | |
9048 if (pwSpec->master_secret == NULL) { | |
9049 break; /* not an error */ | |
9050 } | |
9051 #ifndef NO_PKCS11_BYPASS | |
9052 } else if (ss->opt.bypassPKCS11) { | |
9053 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; | |
9054 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; | |
9055 memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len)
; | |
9056 pwSpec->msItem.data = pwSpec->raw_master_secret; | |
9057 pwSpec->msItem.len = wrappedMS.len; | |
9058 #endif | |
9059 } else { | |
9060 /* We CAN restart a bypass session in a non-bypass socket. */ | |
9061 /* need to import the raw master secret to session object */ | |
9062 PK11SlotInfo *slot; | |
9063 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; | |
9064 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; | |
9065 slot = PK11_GetInternalSlot(); | |
9066 pwSpec->master_secret = | |
9067 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, | |
9068 PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS
, | |
9069 NULL); | |
9070 PK11_FreeSlot(slot); | |
9071 if (pwSpec->master_secret == NULL) { | |
9072 break; /* not an error */ | |
9073 } | |
9074 } | |
9075 ss->sec.ci.sid = sid; | |
9076 if (sid->peerCert != NULL) { | |
9077 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); | |
9078 ssl3_CopyPeerCertsFromSID(ss, sid); | |
9079 } | |
9080 | |
9081 /* | |
9082 * Old SID passed all tests, so resume this old session. | |
9083 * | |
9084 * XXX make sure compression still matches | |
9085 */ | |
9086 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_hits); | |
9087 if (ss->statelessResume) | |
9088 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_stateless_resumes); | |
9089 ss->ssl3.hs.isResuming = PR_TRUE; | |
9090 | |
9091 ss->sec.authAlgorithm = sid->authAlgorithm; | |
9092 ss->sec.authKeyBits = sid->authKeyBits; | |
9093 ss->sec.keaType = sid->keaType; | |
9094 ss->sec.keaKeyBits = sid->keaKeyBits; | |
9095 | |
9096 /* server sids don't remember the server cert we previously sent, | |
9097 ** but they do remember the kea type we originally used, so we | |
9098 ** can locate it again, provided that the current ssl socket | |
9099 ** has had its server certs configured the same as the previous one. | |
9100 */ | |
9101 ss->sec.localCert = | |
9102 CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert); | |
9103 | |
9104 /* Copy cached name in to pending spec */ | |
9105 if (sid != NULL && | |
9106 sid->version > SSL_LIBRARY_VERSION_3_0 && | |
9107 sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) { | |
9108 /* Set server name from sid */ | |
9109 SECItem *sidName = &sid->u.ssl3.srvName; | |
9110 SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName; | |
9111 if (pwsName->data) { | |
9112 SECITEM_FreeItem(pwsName, PR_FALSE); | |
9113 } | |
9114 rv = SECITEM_CopyItem(NULL, pwsName, sidName); | |
9115 if (rv != SECSuccess) { | |
9116 errCode = PORT_GetError(); | |
9117 desc = internal_error; | |
9118 goto alert_loser; | |
9119 } | |
9120 } | |
9121 | |
9122 /* Clean up sni name array */ | |
9123 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) && | |
9124 ss->xtnData.sniNameArr) { | |
9125 PORT_Free(ss->xtnData.sniNameArr); | |
9126 ss->xtnData.sniNameArr = NULL; | |
9127 ss->xtnData.sniNameArrSize = 0; | |
9128 } | |
9129 | |
9130 ssl_GetXmitBufLock(ss); | |
9131 haveXmitBufLock = PR_TRUE; | |
9132 | |
9133 rv = ssl3_SendServerHello(ss); | |
9134 if (rv != SECSuccess) { | |
9135 errCode = PORT_GetError(); | |
9136 goto loser; | |
9137 } | |
9138 | |
9139 if (haveSpecWriteLock) { | |
9140 ssl_ReleaseSpecWriteLock(ss); | |
9141 haveSpecWriteLock = PR_FALSE; | |
9142 } | |
9143 | |
9144 /* NULL value for PMS because we are re-using the old MS */ | |
9145 rv = ssl3_InitPendingCipherSpec(ss, NULL); | |
9146 if (rv != SECSuccess) { | |
9147 errCode = PORT_GetError(); | |
9148 goto loser; | |
9149 } | |
9150 | |
9151 rv = ssl3_SendChangeCipherSpecs(ss); | |
9152 if (rv != SECSuccess) { | |
9153 errCode = PORT_GetError(); | |
9154 goto loser; | |
9155 } | |
9156 rv = ssl3_SendFinished(ss, 0); | |
9157 ss->ssl3.hs.ws = wait_change_cipher; | |
9158 if (rv != SECSuccess) { | |
9159 errCode = PORT_GetError(); | |
9160 goto loser; | |
9161 } | |
9162 | |
9163 if (haveXmitBufLock) { | |
9164 ssl_ReleaseXmitBufLock(ss); | |
9165 haveXmitBufLock = PR_FALSE; | |
9166 } | |
9167 | |
9168 return SECSuccess; | |
9169 } while (0); | |
9170 | |
9171 if (haveSpecWriteLock) { | |
9172 ssl_ReleaseSpecWriteLock(ss); | |
9173 haveSpecWriteLock = PR_FALSE; | |
9174 } | |
9175 | |
9176 if (sid) { /* we had a sid, but it's no longer valid, free it */ | |
9177 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok); | |
9178 if (ss->sec.uncache) | |
9179 ss->sec.uncache(sid); | |
9180 ssl_FreeSID(sid); | |
9181 sid = NULL; | |
9182 } | |
9183 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses); | |
9184 | |
9185 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) { | |
9186 int ret = 0; | |
9187 if (ss->sniSocketConfig) | |
9188 do { /* not a loop */ | |
9189 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == | |
9190 ssl_preinfo_all); | |
9191 | |
9192 ret = SSL_SNI_SEND_ALERT; | |
9193 /* If extension is negotiated, the len of names should > 0. */ | |
9194 if (ss->xtnData.sniNameArrSize) { | |
9195 /* Calling client callback to reconfigure the socket. */ | |
9196 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd, | |
9197 ss->xtnData.sniNameA
rr, | |
9198 ss->xtnData.sniNameA
rrSize, | |
9199 ss->sniSocketConfigA
rg); | |
9200 } | |
9201 if (ret <= SSL_SNI_SEND_ALERT) { | |
9202 /* Application does not know the name or was not able to | |
9203 * properly reconfigure the socket. */ | |
9204 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; | |
9205 desc = unrecognized_name; | |
9206 break; | |
9207 } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) { | |
9208 SECStatus rv = SECSuccess; | |
9209 SECItem *cwsName, *pwsName; | |
9210 | |
9211 ssl_GetSpecWriteLock(ss); /*******************************/ | |
9212 pwsName = &ss->ssl3.pwSpec->srvVirtName; | |
9213 cwsName = &ss->ssl3.cwSpec->srvVirtName; | |
9214 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS | |
9215 /* not allow name change on the 2d HS */ | |
9216 if (ss->firstHsDone) { | |
9217 if (ssl3_ServerNameCompare(pwsName, cwsName)) { | |
9218 ssl_ReleaseSpecWriteLock(ss); /******************/ | |
9219 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; | |
9220 desc = handshake_failure; | |
9221 ret = SSL_SNI_SEND_ALERT; | |
9222 break; | |
9223 } | |
9224 } | |
9225 #endif | |
9226 if (pwsName->data) { | |
9227 SECITEM_FreeItem(pwsName, PR_FALSE); | |
9228 } | |
9229 if (cwsName->data) { | |
9230 rv = SECITEM_CopyItem(NULL, pwsName, cwsName); | |
9231 } | |
9232 ssl_ReleaseSpecWriteLock(ss); /**************************/ | |
9233 if (rv != SECSuccess) { | |
9234 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; | |
9235 desc = internal_error; | |
9236 ret = SSL_SNI_SEND_ALERT; | |
9237 break; | |
9238 } | |
9239 } else if ((unsigned int)ret < ss->xtnData.sniNameArrSize) { | |
9240 /* Application has configured new socket info. Lets check it | |
9241 * and save the name. */ | |
9242 SECStatus rv; | |
9243 SECItem *name = &ss->xtnData.sniNameArr[ret]; | |
9244 int configedCiphers; | |
9245 SECItem *pwsName; | |
9246 | |
9247 /* get rid of the old name and save the newly picked. */ | |
9248 /* This code is protected by ssl3HandshakeLock. */ | |
9249 ssl_GetSpecWriteLock(ss); /*******************************/ | |
9250 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS | |
9251 /* not allow name change on the 2d HS */ | |
9252 if (ss->firstHsDone) { | |
9253 SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName; | |
9254 if (ssl3_ServerNameCompare(name, cwsName)) { | |
9255 ssl_ReleaseSpecWriteLock(ss); /******************/ | |
9256 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; | |
9257 desc = handshake_failure; | |
9258 ret = SSL_SNI_SEND_ALERT; | |
9259 break; | |
9260 } | |
9261 } | |
9262 #endif | |
9263 pwsName = &ss->ssl3.pwSpec->srvVirtName; | |
9264 if (pwsName->data) { | |
9265 SECITEM_FreeItem(pwsName, PR_FALSE); | |
9266 } | |
9267 rv = SECITEM_CopyItem(NULL, pwsName, name); | |
9268 ssl_ReleaseSpecWriteLock(ss); /***************************/ | |
9269 if (rv != SECSuccess) { | |
9270 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; | |
9271 desc = internal_error; | |
9272 ret = SSL_SNI_SEND_ALERT; | |
9273 break; | |
9274 } | |
9275 configedCiphers = ssl3_config_match_init(ss); | |
9276 if (configedCiphers <= 0) { | |
9277 /* no ciphers are working/supported */ | |
9278 errCode = PORT_GetError(); | |
9279 desc = handshake_failure; | |
9280 ret = SSL_SNI_SEND_ALERT; | |
9281 break; | |
9282 } | |
9283 /* Need to tell the client that application has picked | |
9284 * the name from the offered list and reconfigured the socke
t. | |
9285 */ | |
9286 ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_
xtn, | |
9287 ssl3_SendServerNameX
tn); | |
9288 } else { | |
9289 /* Callback returned index outside of the boundary. */ | |
9290 PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize); | |
9291 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; | |
9292 desc = internal_error; | |
9293 ret = SSL_SNI_SEND_ALERT; | |
9294 break; | |
9295 } | |
9296 } while (0); | |
9297 /* Free sniNameArr. The data that each SECItem in the array | |
9298 * points into is the data from the input buffer "b". It will | |
9299 * not be available outside the scope of this or it's child | |
9300 * functions.*/ | |
9301 if (ss->xtnData.sniNameArr) { | |
9302 PORT_Free(ss->xtnData.sniNameArr); | |
9303 ss->xtnData.sniNameArr = NULL; | |
9304 ss->xtnData.sniNameArrSize = 0; | |
9305 } | |
9306 if (ret <= SSL_SNI_SEND_ALERT) { | |
9307 /* desc and errCode should be set. */ | |
9308 goto alert_loser; | |
9309 } | |
9310 } | |
9311 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS | |
9312 else if (ss->firstHsDone) { | |
9313 /* Check that we don't have the name is current spec | |
9314 * if this extension was not negotiated on the 2d hs. */ | |
9315 PRBool passed = PR_TRUE; | |
9316 ssl_GetSpecReadLock(ss); /*******************************/ | |
9317 if (ss->ssl3.cwSpec->srvVirtName.data) { | |
9318 passed = PR_FALSE; | |
9319 } | |
9320 ssl_ReleaseSpecReadLock(ss); /***************************/ | |
9321 if (!passed) { | |
9322 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; | |
9323 desc = handshake_failure; | |
9324 goto alert_loser; | |
9325 } | |
9326 } | |
9327 #endif | |
9328 | |
9329 /* If this is TLS 1.3 we are expecting a ClientKeyShare | |
9330 * extension. Missing/absent extension cause failure | |
9331 * below. */ | |
9332 if (isTLS13) { | |
9333 rv = tls13_HandleClientKeyShare(ss); | |
9334 if (rv != SECSuccess) { | |
9335 errCode = PORT_GetError(); | |
9336 goto alert_loser; | |
9337 } | |
9338 } | |
9339 | |
9340 sid = ssl3_NewSessionID(ss, PR_TRUE); | |
9341 if (sid == NULL) { | |
9342 errCode = PORT_GetError(); | |
9343 goto loser; /* memory error is set. */ | |
9344 } | |
9345 ss->sec.ci.sid = sid; | |
9346 | |
9347 sid->u.ssl3.keys.extendedMasterSecretUsed = | |
9348 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn); | |
9349 ss->ssl3.hs.isResuming = PR_FALSE; | |
9350 | |
9351 ssl_GetXmitBufLock(ss); | |
9352 if (isTLS13) { | |
9353 rv = tls13_SendServerHelloSequence(ss); | |
9354 } else { | |
9355 rv = ssl3_SendServerHelloSequence(ss); | |
9356 } | |
9357 ssl_ReleaseXmitBufLock(ss); | |
9358 if (rv != SECSuccess) { | |
9359 errCode = PORT_GetError(); | |
9360 desc = handshake_failure; | |
9361 goto alert_loser; | |
9362 } | |
9363 | |
9364 if (haveXmitBufLock) { | |
9365 ssl_ReleaseXmitBufLock(ss); | |
9366 haveXmitBufLock = PR_FALSE; | |
9367 } | |
9368 | |
9369 return SECSuccess; | |
9370 | |
9371 alert_loser: | |
9372 if (haveSpecWriteLock) { | |
9373 ssl_ReleaseSpecWriteLock(ss); | |
9374 haveSpecWriteLock = PR_FALSE; | |
9375 } | |
9376 (void)SSL3_SendAlert(ss, level, desc); | |
9377 /* FALLTHRU */ | |
9378 loser: | |
9379 if (haveSpecWriteLock) { | |
9380 ssl_ReleaseSpecWriteLock(ss); | |
9381 haveSpecWriteLock = PR_FALSE; | |
9382 } | |
9383 | |
9384 if (haveXmitBufLock) { | |
9385 ssl_ReleaseXmitBufLock(ss); | |
9386 haveXmitBufLock = PR_FALSE; | |
9387 } | |
9388 | |
9389 PORT_SetError(errCode); | |
9390 return SECFailure; | |
9391 } | |
9392 | |
9393 /* | |
9394 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes | |
9395 * in asking to use the V3 handshake. | |
9396 * Called from ssl2_HandleClientHelloMessage() in sslcon.c | |
9397 */ | |
9398 SECStatus | |
9399 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length) | |
9400 { | |
9401 sslSessionID *sid = NULL; | |
9402 unsigned char *suites; | |
9403 unsigned char *random; | |
9404 SSL3ProtocolVersion version; | |
9405 SECStatus rv; | |
9406 int i; | |
9407 int j; | |
9408 int sid_length; | |
9409 int suite_length; | |
9410 int rand_length; | |
9411 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; | |
9412 SSL3AlertDescription desc = handshake_failure; | |
9413 | |
9414 SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd)); | |
9415 | |
9416 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
9417 | |
9418 ssl_GetSSL3HandshakeLock(ss); | |
9419 | |
9420 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); | |
9421 | |
9422 rv = ssl3_InitState(ss); | |
9423 if (rv != SECSuccess) { | |
9424 ssl_ReleaseSSL3HandshakeLock(ss); | |
9425 return rv; /* ssl3_InitState has set the error code. */ | |
9426 } | |
9427 rv = ssl3_RestartHandshakeHashes(ss); | |
9428 if (rv != SECSuccess) { | |
9429 ssl_ReleaseSSL3HandshakeLock(ss); | |
9430 return rv; | |
9431 } | |
9432 | |
9433 if (ss->ssl3.hs.ws != wait_client_hello) { | |
9434 desc = unexpected_message; | |
9435 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; | |
9436 goto loser; /* alert_loser */ | |
9437 } | |
9438 | |
9439 version = (buffer[1] << 8) | buffer[2]; | |
9440 suite_length = (buffer[3] << 8) | buffer[4]; | |
9441 sid_length = (buffer[5] << 8) | buffer[6]; | |
9442 rand_length = (buffer[7] << 8) | buffer[8]; | |
9443 ss->clientHelloVersion = version; | |
9444 | |
9445 if (version >= SSL_LIBRARY_VERSION_TLS_1_3) { | |
9446 /* [draft-ietf-tls-tls-11; C.3] forbids sending a TLS 1.3 | |
9447 * ClientHello using the backwards-compatible format. */ | |
9448 desc = illegal_parameter; | |
9449 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; | |
9450 goto loser; | |
9451 } | |
9452 | |
9453 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); | |
9454 if (rv != SECSuccess) { | |
9455 /* send back which ever alert client will understand. */ | |
9456 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version | |
9457 : handshake_failure; | |
9458 errCode = SSL_ERROR_UNSUPPORTED_VERSION; | |
9459 goto alert_loser; | |
9460 } | |
9461 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; | |
9462 | |
9463 rv = ssl3_InitHandshakeHashes(ss); | |
9464 if (rv != SECSuccess) { | |
9465 desc = internal_error; | |
9466 errCode = PORT_GetError(); | |
9467 goto alert_loser; | |
9468 } | |
9469 | |
9470 /* if we get a non-zero SID, just ignore it. */ | |
9471 if (length != | |
9472 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) { | |
9473 SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d", | |
9474 SSL_GETPID(), ss->fd, length, | |
9475 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + | |
9476 rand_length)); | |
9477 goto loser; /* malformed */ /* alert_loser */ | |
9478 } | |
9479 | |
9480 suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES; | |
9481 random = suites + suite_length + sid_length; | |
9482 | |
9483 if (rand_length < SSL_MIN_CHALLENGE_BYTES || | |
9484 rand_length > SSL_MAX_CHALLENGE_BYTES) { | |
9485 goto loser; /* malformed */ /* alert_loser */ | |
9486 } | |
9487 | |
9488 PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH); | |
9489 | |
9490 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); | |
9491 PORT_Memcpy( | |
9492 &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length], | |
9493 random, rand_length); | |
9494 | |
9495 PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0], | |
9496 SSL3_RANDOM_LENGTH)); | |
9497 #ifndef NSS_DISABLE_ECC | |
9498 /* Disable any ECC cipher suites for which we have no cert. */ | |
9499 ssl3_FilterECCipherSuitesByServerCerts(ss); | |
9500 #endif | |
9501 i = ssl3_config_match_init(ss); | |
9502 if (i <= 0) { | |
9503 errCode = PORT_GetError(); /* error code is already set. */ | |
9504 goto alert_loser; | |
9505 } | |
9506 | |
9507 /* Select a cipher suite. | |
9508 ** | |
9509 ** NOTE: This suite selection algorithm should be the same as the one in | |
9510 ** ssl3_HandleClientHello(). | |
9511 ** | |
9512 ** See the comments about export cipher suites in ssl3_HandleClientHello(). | |
9513 */ | |
9514 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { | |
9515 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; | |
9516 SSLVersionRange vrange = { ss->version, ss->version }; | |
9517 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) { | |
9518 continue; | |
9519 } | |
9520 for (i = 0; i + 2 < suite_length; i += 3) { | |
9521 PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites
[i + 2]; | |
9522 if (suite_i == suite->cipher_suite) { | |
9523 ss->ssl3.hs.cipher_suite = suite->cipher_suite; | |
9524 ss->ssl3.hs.suite_def = | |
9525 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); | |
9526 ss->ssl3.hs.kea_def = | |
9527 &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; | |
9528 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; | |
9529 goto suite_found; | |
9530 } | |
9531 } | |
9532 } | |
9533 errCode = SSL_ERROR_NO_CYPHER_OVERLAP; | |
9534 goto alert_loser; | |
9535 | |
9536 suite_found: | |
9537 | |
9538 /* Look for the SCSV, and if found, treat it just like an empty RI | |
9539 * extension by processing a local copy of an empty RI extension. | |
9540 */ | |
9541 for (i = 0; i + 2 < suite_length; i += 3) { | |
9542 PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i +
2]; | |
9543 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { | |
9544 SSL3Opaque *b2 = (SSL3Opaque *)emptyRIext; | |
9545 PRUint32 L2 = sizeof emptyRIext; | |
9546 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2, client_hello); | |
9547 break; | |
9548 } | |
9549 } | |
9550 | |
9551 if (ss->opt.requireSafeNegotiation && | |
9552 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { | |
9553 desc = handshake_failure; | |
9554 errCode = SSL_ERROR_UNSAFE_NEGOTIATION; | |
9555 goto alert_loser; | |
9556 } | |
9557 | |
9558 ss->ssl3.hs.compression = ssl_compression_null; | |
9559 ss->sec.send = ssl3_SendApplicationData; | |
9560 | |
9561 /* we don't even search for a cache hit here. It's just a miss. */ | |
9562 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses); | |
9563 sid = ssl3_NewSessionID(ss, PR_TRUE); | |
9564 if (sid == NULL) { | |
9565 errCode = PORT_GetError(); | |
9566 goto loser; /* memory error is set. */ | |
9567 } | |
9568 ss->sec.ci.sid = sid; | |
9569 /* do not worry about memory leak of sid since it now belongs to ci */ | |
9570 | |
9571 /* We have to update the handshake hashes before we can send stuff */ | |
9572 rv = ssl3_UpdateHandshakeHashes(ss, buffer, length); | |
9573 if (rv != SECSuccess) { | |
9574 errCode = PORT_GetError(); | |
9575 goto loser; | |
9576 } | |
9577 | |
9578 ssl_GetXmitBufLock(ss); | |
9579 rv = ssl3_SendServerHelloSequence(ss); | |
9580 ssl_ReleaseXmitBufLock(ss); | |
9581 if (rv != SECSuccess) { | |
9582 errCode = PORT_GetError(); | |
9583 goto loser; | |
9584 } | |
9585 | |
9586 /* XXX_1 The call stack to here is: | |
9587 * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here. | |
9588 * ssl2_HandleClientHelloMessage returns whatever we return here. | |
9589 * ssl_Do1stHandshake will continue looping if it gets back either | |
9590 * SECSuccess or SECWouldBlock. | |
9591 * SECSuccess is preferable here. See XXX_1 in sslgathr.c. | |
9592 */ | |
9593 ssl_ReleaseSSL3HandshakeLock(ss); | |
9594 return SECSuccess; | |
9595 | |
9596 alert_loser: | |
9597 SSL3_SendAlert(ss, alert_fatal, desc); | |
9598 loser: | |
9599 ssl_ReleaseSSL3HandshakeLock(ss); | |
9600 PORT_SetError(errCode); | |
9601 return SECFailure; | |
9602 } | |
9603 | |
9604 /* The negotiated version number has been already placed in ss->version. | |
9605 ** | |
9606 ** Called from: ssl3_HandleClientHello (resuming session), | |
9607 ** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session), | |
9608 ** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session) | |
9609 */ | |
9610 SECStatus | |
9611 ssl3_SendServerHello(sslSocket *ss) | |
9612 { | |
9613 sslSessionID *sid; | |
9614 SECStatus rv; | |
9615 PRUint32 maxBytes = 65535; | |
9616 PRUint32 length; | |
9617 PRInt32 extensions_len = 0; | |
9618 SSL3ProtocolVersion version; | |
9619 | |
9620 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(), | |
9621 ss->fd)); | |
9622 | |
9623 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
9624 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
9625 | |
9626 if (!IS_DTLS(ss)) { | |
9627 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0)); | |
9628 | |
9629 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) { | |
9630 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); | |
9631 return SECFailure; | |
9632 } | |
9633 } else { | |
9634 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0)); | |
9635 | |
9636 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) { | |
9637 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); | |
9638 return SECFailure; | |
9639 } | |
9640 } | |
9641 | |
9642 sid = ss->sec.ci.sid; | |
9643 | |
9644 extensions_len = ssl3_CallHelloExtensionSenders( | |
9645 ss, PR_FALSE, maxBytes, &ss->xtnData.serverHelloSenders[0]); | |
9646 if (extensions_len > 0) | |
9647 extensions_len += 2; /* Add sizeof total extension length */ | |
9648 | |
9649 /* TLS 1.3 doesn't use the session_id or compression_method | |
9650 * fields in the ServerHello. */ | |
9651 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH; | |
9652 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { | |
9653 length += 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength); | |
9654 } | |
9655 length += sizeof(ssl3CipherSuite); | |
9656 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { | |
9657 length += 1; /* Compression */ | |
9658 } | |
9659 length += extensions_len; | |
9660 | |
9661 rv = ssl3_AppendHandshakeHeader(ss, server_hello, length); | |
9662 if (rv != SECSuccess) { | |
9663 return rv; /* err set by AppendHandshake. */ | |
9664 } | |
9665 | |
9666 if (IS_DTLS(ss)) { | |
9667 version = dtls_TLSVersionToDTLSVersion(ss->version); | |
9668 } else { | |
9669 version = ss->version; | |
9670 } | |
9671 | |
9672 rv = ssl3_AppendHandshakeNumber(ss, version, 2); | |
9673 if (rv != SECSuccess) { | |
9674 return rv; /* err set by AppendHandshake. */ | |
9675 } | |
9676 /* Random already generated in ssl3_HandleClientHello */ | |
9677 rv = ssl3_AppendHandshake( | |
9678 ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH); | |
9679 if (rv != SECSuccess) { | |
9680 return rv; /* err set by AppendHandshake. */ | |
9681 } | |
9682 | |
9683 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { | |
9684 if (sid) { | |
9685 rv = ssl3_AppendHandshakeVariable( | |
9686 ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); | |
9687 } else { | |
9688 rv = ssl3_AppendHandshakeNumber(ss, 0, 1); | |
9689 } | |
9690 if (rv != SECSuccess) { | |
9691 return rv; /* err set by AppendHandshake. */ | |
9692 } | |
9693 } | |
9694 | |
9695 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2); | |
9696 if (rv != SECSuccess) { | |
9697 return rv; /* err set by AppendHandshake. */ | |
9698 } | |
9699 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { | |
9700 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1); | |
9701 if (rv != SECSuccess) { | |
9702 return rv; /* err set by AppendHandshake. */ | |
9703 } | |
9704 } | |
9705 if (extensions_len) { | |
9706 PRInt32 sent_len; | |
9707 | |
9708 extensions_len -= 2; | |
9709 rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2); | |
9710 if (rv != SECSuccess) | |
9711 return rv; /* err set by ssl3_AppendHandshakeNumber */ | |
9712 sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len, | |
9713 &ss->xtnData.serverHelloSender
s[0]); | |
9714 PORT_Assert(sent_len == extensions_len); | |
9715 if (sent_len != extensions_len) { | |
9716 if (sent_len >= 0) | |
9717 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
9718 return SECFailure; | |
9719 } | |
9720 } | |
9721 rv = ssl3_SetupPendingCipherSpec(ss); | |
9722 if (rv != SECSuccess) { | |
9723 return rv; /* err set by ssl3_SetupPendingCipherSpec */ | |
9724 } | |
9725 | |
9726 return SECSuccess; | |
9727 } | |
9728 | |
9729 static SECStatus | |
9730 ssl3_PickSignatureHashAlgorithm(sslSocket *ss, | |
9731 SSLSignatureAndHashAlg *out); | |
9732 | |
9733 static SECStatus | |
9734 ssl3_SendDHServerKeyExchange(sslSocket *ss) | |
9735 { | |
9736 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; | |
9737 SECStatus rv = SECFailure; | |
9738 int length; | |
9739 PRBool isTLS; | |
9740 SECItem signed_hash = { siBuffer, NULL, 0 }; | |
9741 SSL3Hashes hashes; | |
9742 SSLSignatureAndHashAlg sigAndHash; | |
9743 SECKEYDHParams dhParam; | |
9744 | |
9745 ssl3KeyPair *keyPair = NULL; | |
9746 SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ | |
9747 SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */ | |
9748 int certIndex = -1; | |
9749 | |
9750 if (kea_def->kea != kea_dhe_dss && kea_def->kea != kea_dhe_rsa) { | |
9751 /* TODO: Support DH_anon. It might be sufficient to drop the signature. | |
9752 See bug 1170510. */ | |
9753 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
9754 return SECFailure; | |
9755 } | |
9756 | |
9757 dhParam.prime.data = ss->dheParams->prime.data; | |
9758 dhParam.prime.len = ss->dheParams->prime.len; | |
9759 dhParam.base.data = ss->dheParams->base.data; | |
9760 dhParam.base.len = ss->dheParams->base.len; | |
9761 | |
9762 PRINT_BUF(60, (NULL, "Server DH p", dhParam.prime.data, | |
9763 dhParam.prime.len)); | |
9764 PRINT_BUF(60, (NULL, "Server DH g", dhParam.base.data, | |
9765 dhParam.base.len)); | |
9766 | |
9767 /* Generate ephemeral DH keypair */ | |
9768 privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL); | |
9769 if (!privKey || !pubKey) { | |
9770 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); | |
9771 rv = SECFailure; | |
9772 goto loser; | |
9773 } | |
9774 | |
9775 keyPair = ssl3_NewKeyPair(privKey, pubKey); | |
9776 if (!keyPair) { | |
9777 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); | |
9778 goto loser; | |
9779 } | |
9780 | |
9781 PRINT_BUF(50, (ss, "DH public value:", | |
9782 pubKey->u.dh.publicValue.data, | |
9783 pubKey->u.dh.publicValue.len)); | |
9784 | |
9785 if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) { | |
9786 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); | |
9787 goto loser; | |
9788 } | |
9789 | |
9790 rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, | |
9791 pubKey->u.dh.prime, | |
9792 pubKey->u.dh.base, | |
9793 pubKey->u.dh.publicValue, | |
9794 &ss->ssl3.hs.client_random, | |
9795 &ss->ssl3.hs.server_random, | |
9796 &hashes, ss->opt.bypassPKCS11); | |
9797 if (rv != SECSuccess) { | |
9798 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
9799 goto loser; | |
9800 } | |
9801 | |
9802 /* It has been suggested to test kea_def->signKeyType instead, and to use | |
9803 * ssl_auth_* instead. Investigate what to do. See bug 102794. */ | |
9804 if (kea_def->kea == kea_dhe_rsa) | |
9805 certIndex = ssl_kea_rsa; | |
9806 else | |
9807 certIndex = ssl_kea_dh; | |
9808 | |
9809 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
9810 rv = ssl3_SignHashes(&hashes, ss->serverCerts[certIndex].SERVERKEY, | |
9811 &signed_hash, isTLS); | |
9812 if (rv != SECSuccess) { | |
9813 goto loser; /* ssl3_SignHashes has set err. */ | |
9814 } | |
9815 if (signed_hash.data == NULL) { | |
9816 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
9817 goto loser; | |
9818 } | |
9819 length = 2 + pubKey->u.dh.prime.len + | |
9820 2 + pubKey->u.dh.base.len + | |
9821 2 + pubKey->u.dh.publicValue.len + | |
9822 2 + signed_hash.len; | |
9823 | |
9824 if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
9825 length += 2; | |
9826 } | |
9827 | |
9828 rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); | |
9829 if (rv != SECSuccess) { | |
9830 goto loser; /* err set by AppendHandshake. */ | |
9831 } | |
9832 | |
9833 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.prime.data, | |
9834 pubKey->u.dh.prime.len, 2); | |
9835 if (rv != SECSuccess) { | |
9836 goto loser; /* err set by AppendHandshake. */ | |
9837 } | |
9838 | |
9839 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.base.data, | |
9840 pubKey->u.dh.base.len, 2); | |
9841 if (rv != SECSuccess) { | |
9842 goto loser; /* err set by AppendHandshake. */ | |
9843 } | |
9844 | |
9845 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.publicValue.data, | |
9846 pubKey->u.dh.publicValue.len, 2); | |
9847 if (rv != SECSuccess) { | |
9848 goto loser; /* err set by AppendHandshake. */ | |
9849 } | |
9850 | |
9851 if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
9852 rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); | |
9853 if (rv != SECSuccess) { | |
9854 goto loser; /* err set by AppendHandshake. */ | |
9855 } | |
9856 } | |
9857 | |
9858 rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data, | |
9859 signed_hash.len, 2); | |
9860 if (rv != SECSuccess) { | |
9861 goto loser; /* err set by AppendHandshake. */ | |
9862 } | |
9863 PORT_Free(signed_hash.data); | |
9864 ss->dheKeyPair = keyPair; | |
9865 return SECSuccess; | |
9866 | |
9867 loser: | |
9868 if (signed_hash.data) | |
9869 PORT_Free(signed_hash.data); | |
9870 if (privKey) | |
9871 SECKEY_DestroyPrivateKey(privKey); | |
9872 if (pubKey) | |
9873 SECKEY_DestroyPublicKey(pubKey); | |
9874 return SECFailure; | |
9875 } | |
9876 | |
9877 /* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing | |
9878 * elements of the handshake. (The negotiated cipher suite determines the | |
9879 * signature algorithm.) Prior to TLS 1.2, the MD5/SHA1 combination is always | |
9880 * used. With TLS 1.2, a client may advertise its support for signature and | |
9881 * hash combinations. */ | |
9882 static SECStatus | |
9883 ssl3_PickSignatureHashAlgorithm(sslSocket *ss, | |
9884 SSLSignatureAndHashAlg *out) | |
9885 { | |
9886 PRUint32 policy; | |
9887 unsigned int i, j; | |
9888 | |
9889 out->sigAlg = ss->ssl3.hs.kea_def->signKeyType; | |
9890 | |
9891 if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) { | |
9892 /* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and | |
9893 * prior. */ | |
9894 out->hashAlg = ssl_hash_none; | |
9895 return SECSuccess; | |
9896 } | |
9897 | |
9898 if (ss->ssl3.hs.numClientSigAndHash == 0) { | |
9899 /* If the client didn't provide any signature_algorithms extension then | |
9900 * we can assume that they support SHA-1: | |
9901 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ | |
9902 out->hashAlg = ssl_hash_sha1; | |
9903 return SECSuccess; | |
9904 } | |
9905 | |
9906 /* Here we look for the first server preference that the client has | |
9907 * indicated support for in their signature_algorithms extension. */ | |
9908 for (i = 0; i < ss->ssl3.signatureAlgorithmCount; ++i) { | |
9909 const SSLSignatureAndHashAlg *serverPref = | |
9910 &ss->ssl3.signatureAlgorithms[i]; | |
9911 SECOidTag hashOID; | |
9912 if (serverPref->sigAlg != out->sigAlg) { | |
9913 continue; | |
9914 } | |
9915 hashOID = ssl3_TLSHashAlgorithmToOID(serverPref->hashAlg); | |
9916 if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) && | |
9917 !(policy & NSS_USE_ALG_IN_SSL_KX)) { | |
9918 /* we ignore hashes we don't support */ | |
9919 continue; | |
9920 } | |
9921 for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) { | |
9922 const SSLSignatureAndHashAlg *clientPref = | |
9923 &ss->ssl3.hs.clientSigAndHash[j]; | |
9924 if (clientPref->hashAlg == serverPref->hashAlg && | |
9925 clientPref->sigAlg == out->sigAlg) { | |
9926 out->hashAlg = serverPref->hashAlg; | |
9927 return SECSuccess; | |
9928 } | |
9929 } | |
9930 } | |
9931 | |
9932 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); | |
9933 return SECFailure; | |
9934 } | |
9935 | |
9936 static SECStatus | |
9937 ssl3_SendServerKeyExchange(sslSocket *ss) | |
9938 { | |
9939 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; | |
9940 SECStatus rv = SECFailure; | |
9941 int length; | |
9942 PRBool isTLS; | |
9943 SECItem signed_hash = { siBuffer, NULL, 0 }; | |
9944 SSL3Hashes hashes; | |
9945 SECKEYPublicKey *sdPub; /* public key for step-down */ | |
9946 SSLSignatureAndHashAlg sigAndHash; | |
9947 | |
9948 SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake", | |
9949 SSL_GETPID(), ss->fd)); | |
9950 | |
9951 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
9952 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
9953 | |
9954 if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) { | |
9955 return SECFailure; | |
9956 } | |
9957 | |
9958 switch (kea_def->exchKeyType) { | |
9959 case kt_rsa: | |
9960 /* Perform SSL Step-Down here. */ | |
9961 sdPub = ss->stepDownKeyPair->pubKey; | |
9962 PORT_Assert(sdPub != NULL); | |
9963 if (!sdPub) { | |
9964 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
9965 return SECFailure; | |
9966 } | |
9967 rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, | |
9968 sdPub->u.rsa.modulus, | |
9969 sdPub->u.rsa.publicExponent, | |
9970 &ss->ssl3.hs.client_random, | |
9971 &ss->ssl3.hs.server_random, | |
9972 &hashes, ss->opt.bypassPKCS11); | |
9973 if (rv != SECSuccess) { | |
9974 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
9975 return rv; | |
9976 } | |
9977 | |
9978 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0)
; | |
9979 rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY, | |
9980 &signed_hash, isTLS); | |
9981 if (rv != SECSuccess) { | |
9982 goto loser; /* ssl3_SignHashes has set err. */ | |
9983 } | |
9984 if (signed_hash.data == NULL) { | |
9985 /* how can this happen and rv == SECSuccess ?? */ | |
9986 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); | |
9987 goto loser; | |
9988 } | |
9989 length = 2 + sdPub->u.rsa.modulus.len + | |
9990 2 + sdPub->u.rsa.publicExponent.len + | |
9991 2 + signed_hash.len; | |
9992 | |
9993 if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
9994 length += 2; | |
9995 } | |
9996 | |
9997 rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); | |
9998 if (rv != SECSuccess) { | |
9999 goto loser; /* err set by AppendHandshake. */ | |
10000 } | |
10001 | |
10002 rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data, | |
10003 sdPub->u.rsa.modulus.len, 2); | |
10004 if (rv != SECSuccess) { | |
10005 goto loser; /* err set by AppendHandshake. */ | |
10006 } | |
10007 | |
10008 rv = ssl3_AppendHandshakeVariable( | |
10009 ss, sdPub->u.rsa.publicExponent.data, | |
10010 sdPub->u.rsa.publicExponent.len, 2); | |
10011 if (rv != SECSuccess) { | |
10012 goto loser; /* err set by AppendHandshake. */ | |
10013 } | |
10014 | |
10015 if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
10016 rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); | |
10017 if (rv != SECSuccess) { | |
10018 goto loser; /* err set by AppendHandshake. */ | |
10019 } | |
10020 } | |
10021 | |
10022 rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data, | |
10023 signed_hash.len, 2); | |
10024 if (rv != SECSuccess) { | |
10025 goto loser; /* err set by AppendHandshake. */ | |
10026 } | |
10027 PORT_Free(signed_hash.data); | |
10028 return SECSuccess; | |
10029 | |
10030 case ssl_kea_dh: { | |
10031 rv = ssl3_SendDHServerKeyExchange(ss); | |
10032 return rv; | |
10033 } | |
10034 | |
10035 #ifndef NSS_DISABLE_ECC | |
10036 case kt_ecdh: { | |
10037 rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash); | |
10038 return rv; | |
10039 } | |
10040 #endif /* NSS_DISABLE_ECC */ | |
10041 | |
10042 case kt_null: | |
10043 default: | |
10044 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); | |
10045 break; | |
10046 } | |
10047 loser: | |
10048 if (signed_hash.data != NULL) | |
10049 PORT_Free(signed_hash.data); | |
10050 return SECFailure; | |
10051 } | |
10052 | |
10053 SECStatus | |
10054 ssl3_EncodeCertificateRequestSigAlgs(sslSocket *ss, PRUint8 *buf, | |
10055 unsigned maxLen, PRUint32 *len) | |
10056 { | |
10057 unsigned int i; | |
10058 | |
10059 PORT_Assert(maxLen >= ss->ssl3.signatureAlgorithmCount * 2); | |
10060 if (maxLen < ss->ssl3.signatureAlgorithmCount * 2) { | |
10061 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
10062 return SECFailure; | |
10063 } | |
10064 | |
10065 *len = 0; | |
10066 for (i = 0; i < ss->ssl3.signatureAlgorithmCount; ++i) { | |
10067 const SSLSignatureAndHashAlg *alg = &ss->ssl3.signatureAlgorithms[i]; | |
10068 /* Note that we don't support a handshake hash with anything other than | |
10069 * SHA-256, so asking for a signature from clients for something else | |
10070 * would be inviting disaster. */ | |
10071 if (alg->hashAlg == ssl_hash_sha256) { | |
10072 buf[(*len)++] = (PRUint8)alg->hashAlg; | |
10073 buf[(*len)++] = (PRUint8)alg->sigAlg; | |
10074 } | |
10075 } | |
10076 | |
10077 if (*len == 0) { | |
10078 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); | |
10079 return SECFailure; | |
10080 } | |
10081 return SECSuccess; | |
10082 } | |
10083 | |
10084 void | |
10085 ssl3_GetCertificateRequestCAs(sslSocket *ss, int *calen, SECItem **names, | |
10086 int *nnames) | |
10087 { | |
10088 SECItem *name; | |
10089 CERTDistNames *ca_list; | |
10090 int i; | |
10091 | |
10092 *calen = 0; | |
10093 *names = NULL; | |
10094 *nnames = 0; | |
10095 | |
10096 /* ssl3.ca_list is initialized to NULL, and never changed. */ | |
10097 ca_list = ss->ssl3.ca_list; | |
10098 if (!ca_list) { | |
10099 ca_list = ssl3_server_ca_list; | |
10100 } | |
10101 | |
10102 if (ca_list != NULL) { | |
10103 *names = ca_list->names; | |
10104 *nnames = ca_list->nnames; | |
10105 } | |
10106 | |
10107 for (i = 0, name = *names; i < *nnames; i++, name++) { | |
10108 *calen += 2 + name->len; | |
10109 } | |
10110 } | |
10111 | |
10112 static SECStatus | |
10113 ssl3_SendCertificateRequest(sslSocket *ss) | |
10114 { | |
10115 PRBool isTLS12; | |
10116 const PRUint8 *certTypes; | |
10117 SECStatus rv; | |
10118 int length; | |
10119 SECItem *names; | |
10120 int calen; | |
10121 int nnames; | |
10122 SECItem *name; | |
10123 int i; | |
10124 int certTypesLength; | |
10125 PRUint8 sigAlgs[MAX_SIGNATURE_ALGORITHMS * 2]; | |
10126 unsigned int sigAlgsLength = 0; | |
10127 | |
10128 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake", | |
10129 SSL_GETPID(), ss->fd)); | |
10130 | |
10131 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
10132 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10133 | |
10134 isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
10135 | |
10136 ssl3_GetCertificateRequestCAs(ss, &calen, &names, &nnames); | |
10137 certTypes = certificate_types; | |
10138 certTypesLength = sizeof certificate_types; | |
10139 | |
10140 length = 1 + certTypesLength + 2 + calen; | |
10141 if (isTLS12) { | |
10142 rv = ssl3_EncodeCertificateRequestSigAlgs(ss, sigAlgs, sizeof(sigAlgs), | |
10143 &sigAlgsLength); | |
10144 if (rv != SECSuccess) { | |
10145 return rv; | |
10146 } | |
10147 length += 2 + sigAlgsLength; | |
10148 } | |
10149 | |
10150 rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length); | |
10151 if (rv != SECSuccess) { | |
10152 return rv; /* err set by AppendHandshake. */ | |
10153 } | |
10154 rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1); | |
10155 if (rv != SECSuccess) { | |
10156 return rv; /* err set by AppendHandshake. */ | |
10157 } | |
10158 if (isTLS12) { | |
10159 rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2); | |
10160 if (rv != SECSuccess) { | |
10161 return rv; /* err set by AppendHandshake. */ | |
10162 } | |
10163 } | |
10164 rv = ssl3_AppendHandshakeNumber(ss, calen, 2); | |
10165 if (rv != SECSuccess) { | |
10166 return rv; /* err set by AppendHandshake. */ | |
10167 } | |
10168 for (i = 0, name = names; i < nnames; i++, name++) { | |
10169 rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2); | |
10170 if (rv != SECSuccess) { | |
10171 return rv; /* err set by AppendHandshake. */ | |
10172 } | |
10173 } | |
10174 | |
10175 return SECSuccess; | |
10176 } | |
10177 | |
10178 static SECStatus | |
10179 ssl3_SendServerHelloDone(sslSocket *ss) | |
10180 { | |
10181 SECStatus rv; | |
10182 | |
10183 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake", | |
10184 SSL_GETPID(), ss->fd)); | |
10185 | |
10186 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
10187 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10188 | |
10189 rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0); | |
10190 if (rv != SECSuccess) { | |
10191 return rv; /* err set by AppendHandshake. */ | |
10192 } | |
10193 rv = ssl3_FlushHandshake(ss, 0); | |
10194 if (rv != SECSuccess) { | |
10195 return rv; /* error code set by ssl3_FlushHandshake */ | |
10196 } | |
10197 return SECSuccess; | |
10198 } | |
10199 | |
10200 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered | |
10201 * a complete ssl3 Certificate Verify message | |
10202 * Caller must hold Handshake and RecvBuf locks. | |
10203 */ | |
10204 static SECStatus | |
10205 ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length, | |
10206 SSL3Hashes *hashes) | |
10207 { | |
10208 SECItem signed_hash = { siBuffer, NULL, 0 }; | |
10209 SECStatus rv; | |
10210 int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY; | |
10211 SSL3AlertDescription desc = handshake_failure; | |
10212 PRBool isTLS, isTLS12; | |
10213 SSLSignatureAndHashAlg sigAndHash; | |
10214 | |
10215 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake", | |
10216 SSL_GETPID(), ss->fd)); | |
10217 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
10218 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10219 | |
10220 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); | |
10221 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); | |
10222 | |
10223 if (ss->ssl3.hs.ws != wait_cert_verify) { | |
10224 desc = unexpected_message; | |
10225 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY; | |
10226 goto alert_loser; | |
10227 } | |
10228 | |
10229 if (!hashes) { | |
10230 PORT_Assert(0); | |
10231 desc = internal_error; | |
10232 errCode = SEC_ERROR_LIBRARY_FAILURE; | |
10233 goto alert_loser; | |
10234 } | |
10235 | |
10236 if (isTLS12) { | |
10237 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, | |
10238 &sigAndHash); | |
10239 if (rv != SECSuccess) { | |
10240 goto loser; /* malformed or unsupported. */ | |
10241 } | |
10242 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( | |
10243 ss, &sigAndHash, ss->sec.peerCert); | |
10244 if (rv != SECSuccess) { | |
10245 errCode = PORT_GetError(); | |
10246 desc = decrypt_error; | |
10247 goto alert_loser; | |
10248 } | |
10249 | |
10250 /* We only support CertificateVerify messages that use the handshake | |
10251 * hash. */ | |
10252 if (sigAndHash.hashAlg != hashes->hashAlg) { | |
10253 errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM; | |
10254 desc = decrypt_error; | |
10255 goto alert_loser; | |
10256 } | |
10257 } | |
10258 | |
10259 rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length); | |
10260 if (rv != SECSuccess) { | |
10261 goto loser; /* malformed. */ | |
10262 } | |
10263 | |
10264 /* XXX verify that the key & kea match */ | |
10265 rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash, | |
10266 isTLS, ss->pkcs11PinArg); | |
10267 if (rv != SECSuccess) { | |
10268 errCode = PORT_GetError(); | |
10269 desc = isTLS ? decrypt_error : handshake_failure; | |
10270 goto alert_loser; | |
10271 } | |
10272 | |
10273 signed_hash.data = NULL; | |
10274 | |
10275 if (length != 0) { | |
10276 desc = isTLS ? decode_error : illegal_parameter; | |
10277 goto alert_loser; /* malformed */ | |
10278 } | |
10279 ss->ssl3.hs.ws = wait_change_cipher; | |
10280 return SECSuccess; | |
10281 | |
10282 alert_loser: | |
10283 SSL3_SendAlert(ss, alert_fatal, desc); | |
10284 loser: | |
10285 PORT_SetError(errCode); | |
10286 return SECFailure; | |
10287 } | |
10288 | |
10289 /* find a slot that is able to generate a PMS and wrap it with RSA. | |
10290 * Then generate and return the PMS. | |
10291 * If the serverKeySlot parameter is non-null, this function will use | |
10292 * that slot to do the job, otherwise it will find a slot. | |
10293 * | |
10294 * Called from ssl3_DeriveConnectionKeysPKCS11() (above) | |
10295 * sendRSAClientKeyExchange() (above) | |
10296 * ssl3_HandleRSAClientKeyExchange() (below) | |
10297 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock | |
10298 */ | |
10299 static PK11SymKey * | |
10300 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, | |
10301 PK11SlotInfo *serverKeySlot) | |
10302 { | |
10303 PK11SymKey *pms = NULL; | |
10304 PK11SlotInfo *slot = serverKeySlot; | |
10305 void *pwArg = ss->pkcs11PinArg; | |
10306 SECItem param; | |
10307 CK_VERSION version; | |
10308 CK_MECHANISM_TYPE mechanism_array[3]; | |
10309 | |
10310 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10311 | |
10312 if (slot == NULL) { | |
10313 SSLCipherAlgorithm calg; | |
10314 /* The specReadLock would suffice here, but we cannot assert on | |
10315 ** read locks. Also, all the callers who call with a non-null | |
10316 ** slot already hold the SpecWriteLock. | |
10317 */ | |
10318 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); | |
10319 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
10320 | |
10321 calg = spec->cipher_def->calg; | |
10322 | |
10323 /* First get an appropriate slot. */ | |
10324 mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN; | |
10325 mechanism_array[1] = CKM_RSA_PKCS; | |
10326 mechanism_array[2] = ssl3_Alg2Mech(calg); | |
10327 | |
10328 slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg); | |
10329 if (slot == NULL) { | |
10330 /* can't find a slot with all three, find a slot with the minimum */ | |
10331 slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg); | |
10332 if (slot == NULL) { | |
10333 PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND); | |
10334 return pms; /* which is NULL */ | |
10335 } | |
10336 } | |
10337 } | |
10338 | |
10339 /* Generate the pre-master secret ... */ | |
10340 if (IS_DTLS(ss)) { | |
10341 SSL3ProtocolVersion temp; | |
10342 | |
10343 temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); | |
10344 version.major = MSB(temp); | |
10345 version.minor = LSB(temp); | |
10346 } else { | |
10347 version.major = MSB(ss->clientHelloVersion); | |
10348 version.minor = LSB(ss->clientHelloVersion); | |
10349 } | |
10350 | |
10351 param.data = (unsigned char *)&version; | |
10352 param.len = sizeof version; | |
10353 | |
10354 pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, ¶m, 0, pwArg); | |
10355 if (!serverKeySlot) | |
10356 PK11_FreeSlot(slot); | |
10357 if (pms == NULL) { | |
10358 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
10359 } | |
10360 return pms; | |
10361 } | |
10362 | |
10363 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER | |
10364 * return any indication of failure of the Client Key Exchange message, | |
10365 * where that failure is caused by the content of the client's message. | |
10366 * This function must not return SECFailure for any reason that is directly | |
10367 * or indirectly caused by the content of the client's encrypted PMS. | |
10368 * We must not send an alert and also not drop the connection. | |
10369 * Instead, we generate a random PMS. This will cause a failure | |
10370 * in the processing the finished message, which is exactly where | |
10371 * the failure must occur. | |
10372 * | |
10373 * Called from ssl3_HandleClientKeyExchange | |
10374 */ | |
10375 static SECStatus | |
10376 ssl3_HandleRSAClientKeyExchange(sslSocket *ss, | |
10377 SSL3Opaque *b, | |
10378 PRUint32 length, | |
10379 SECKEYPrivateKey *serverKey) | |
10380 { | |
10381 #ifndef NO_PKCS11_BYPASS | |
10382 unsigned char *cr = (unsigned char *)&ss->ssl3.hs.client_random; | |
10383 unsigned char *sr = (unsigned char *)&ss->ssl3.hs.server_random; | |
10384 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; | |
10385 unsigned int outLen = 0; | |
10386 PRBool isTLS = PR_FALSE; | |
10387 SECItem pmsItem = { siBuffer, NULL, 0 }; | |
10388 unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH]; | |
10389 #endif | |
10390 SECStatus rv; | |
10391 SECItem enc_pms; | |
10392 | |
10393 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
10394 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10395 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); | |
10396 | |
10397 enc_pms.data = b; | |
10398 enc_pms.len = length; | |
10399 #ifndef NO_PKCS11_BYPASS | |
10400 pmsItem.data = rsaPmsBuf; | |
10401 pmsItem.len = sizeof rsaPmsBuf; | |
10402 #endif | |
10403 | |
10404 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ | |
10405 PRInt32 kLen; | |
10406 kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len); | |
10407 if (kLen < 0) { | |
10408 PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
10409 return SECFailure; | |
10410 } | |
10411 if ((unsigned)kLen < enc_pms.len) { | |
10412 enc_pms.len = kLen; | |
10413 } | |
10414 #ifndef NO_PKCS11_BYPASS | |
10415 isTLS = PR_TRUE; | |
10416 #endif | |
10417 } else { | |
10418 #ifndef NO_PKCS11_BYPASS | |
10419 isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0); | |
10420 #endif | |
10421 } | |
10422 | |
10423 #ifndef NO_PKCS11_BYPASS | |
10424 if (ss->opt.bypassPKCS11) { | |
10425 /* We have not implemented a tls_ExtendedMasterKeyDeriveBypass | |
10426 * and will not negotiate this extension in bypass mode. This | |
10427 * assert just double-checks that. | |
10428 */ | |
10429 PORT_Assert( | |
10430 !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)); | |
10431 | |
10432 /* TRIPLE BYPASS, get PMS directly from RSA decryption. | |
10433 * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer, | |
10434 * then, check for version rollback attack, then | |
10435 * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in | |
10436 * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with | |
10437 * ss and NULL, so that it will use the MS we've already derived here. | |
10438 */ | |
10439 | |
10440 rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen, | |
10441 sizeof rsaPmsBuf, enc_pms.data, enc_pms.len); | |
10442 if (rv != SECSuccess) { | |
10443 /* triple bypass failed. Let's try for a double bypass. */ | |
10444 goto double_bypass; | |
10445 } else if (ss->opt.detectRollBack) { | |
10446 SSL3ProtocolVersion client_version = | |
10447 (rsaPmsBuf[0] << 8) | rsaPmsBuf[1]; | |
10448 | |
10449 if (IS_DTLS(ss)) { | |
10450 client_version = dtls_DTLSVersionToTLSVersion(client_version); | |
10451 } | |
10452 | |
10453 if (client_version != ss->clientHelloVersion) { | |
10454 /* Version roll-back detected. ensure failure. */ | |
10455 rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf); | |
10456 } | |
10457 } | |
10458 /* have PMS, build MS without PKCS11 */ | |
10459 rv = ssl3_MasterSecretDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS, | |
10460 PR_TRUE); | |
10461 if (rv != SECSuccess) { | |
10462 pwSpec->msItem.data = pwSpec->raw_master_secret; | |
10463 pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH; | |
10464 PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len); | |
10465 } | |
10466 rv = ssl3_InitPendingCipherSpec(ss, NULL); | |
10467 } else | |
10468 #endif | |
10469 { | |
10470 PK11SymKey *tmpPms[2] = { NULL, NULL }; | |
10471 PK11SlotInfo *slot; | |
10472 int useFauxPms = 0; | |
10473 #define currentPms tmpPms[!useFauxPms] | |
10474 #define unusedPms tmpPms[useFauxPms] | |
10475 #define realPms tmpPms[1] | |
10476 #define fauxPms tmpPms[0] | |
10477 | |
10478 #ifndef NO_PKCS11_BYPASS | |
10479 double_bypass: | |
10480 #endif | |
10481 | |
10482 /* | |
10483 * Get as close to algorithm 2 from RFC 5246; Section 7.4.7.1 | |
10484 * as we can within the constraints of the PKCS#11 interface. | |
10485 * | |
10486 * 1. Unconditionally generate a bogus PMS (what RFC 5246 | |
10487 * calls R). | |
10488 * 2. Attempt the RSA decryption to recover the PMS (what | |
10489 * RFC 5246 calls M). | |
10490 * 3. Set PMS = (M == NULL) ? R : M | |
10491 * 4. Use ssl3_ComputeMasterSecret(PMS) to attempt to derive | |
10492 * the MS from PMS. This includes performing the version | |
10493 * check and length check. | |
10494 * 5. If either the initial RSA decryption failed or | |
10495 * ssl3_ComputeMasterSecret(PMS) failed, then discard | |
10496 * M and set PMS = R. Else, discard R and set PMS = M. | |
10497 * | |
10498 * We do two derivations here because we can't rely on having | |
10499 * a function that only performs the PMS version and length | |
10500 * check. The only redundant cost is that this runs the PRF, | |
10501 * which isn't necessary here. | |
10502 */ | |
10503 | |
10504 /* Generate the bogus PMS (R) */ | |
10505 slot = PK11_GetSlotFromPrivateKey(serverKey); | |
10506 if (!slot) { | |
10507 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
10508 return SECFailure; | |
10509 } | |
10510 | |
10511 if (!PK11_DoesMechanism(slot, CKM_SSL3_MASTER_KEY_DERIVE)) { | |
10512 PK11_FreeSlot(slot); | |
10513 slot = PK11_GetBestSlot(CKM_SSL3_MASTER_KEY_DERIVE, NULL); | |
10514 if (!slot) { | |
10515 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
10516 return SECFailure; | |
10517 } | |
10518 } | |
10519 | |
10520 ssl_GetSpecWriteLock(ss); | |
10521 fauxPms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot); | |
10522 ssl_ReleaseSpecWriteLock(ss); | |
10523 PK11_FreeSlot(slot); | |
10524 | |
10525 if (fauxPms == NULL) { | |
10526 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
10527 return SECFailure; | |
10528 } | |
10529 | |
10530 /* | |
10531 * unwrap pms out of the incoming buffer | |
10532 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do | |
10533 * the unwrap. Rather, it is the mechanism with which the | |
10534 * unwrapped pms will be used. | |
10535 */ | |
10536 realPms = PK11_PubUnwrapSymKey(serverKey, &enc_pms, | |
10537 CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0
); | |
10538 /* Temporarily use the PMS if unwrapping the real PMS fails. */ | |
10539 useFauxPms |= (realPms == NULL); | |
10540 | |
10541 /* Attempt to derive the MS from the PMS. This is the only way to | |
10542 * check the version field in the RSA PMS. If this fails, we | |
10543 * then use the faux PMS in place of the PMS. Note that this | |
10544 * operation should never fail if we are using the faux PMS | |
10545 * since it is correctly formatted. */ | |
10546 rv = ssl3_ComputeMasterSecret(ss, currentPms, NULL); | |
10547 | |
10548 /* If we succeeded, then select the true PMS and discard the | |
10549 * FPMS. Else, select the FPMS and select the true PMS */ | |
10550 useFauxPms |= (rv != SECSuccess); | |
10551 | |
10552 if (unusedPms) { | |
10553 PK11_FreeSymKey(unusedPms); | |
10554 } | |
10555 | |
10556 /* This step will derive the MS from the PMS, among other things. */ | |
10557 rv = ssl3_InitPendingCipherSpec(ss, currentPms); | |
10558 PK11_FreeSymKey(currentPms); | |
10559 } | |
10560 | |
10561 if (rv != SECSuccess) { | |
10562 SEND_ALERT | |
10563 return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */ | |
10564 } | |
10565 | |
10566 #undef currentPms | |
10567 #undef unusedPms | |
10568 #undef realPms | |
10569 #undef fauxPms | |
10570 | |
10571 return SECSuccess; | |
10572 } | |
10573 | |
10574 static SECStatus | |
10575 ssl3_HandleDHClientKeyExchange(sslSocket *ss, | |
10576 SSL3Opaque *b, | |
10577 PRUint32 length, | |
10578 SECKEYPublicKey *srvrPubKey, | |
10579 SECKEYPrivateKey *serverKey) | |
10580 { | |
10581 PK11SymKey *pms; | |
10582 SECStatus rv; | |
10583 SECKEYPublicKey clntPubKey; | |
10584 CK_MECHANISM_TYPE target; | |
10585 PRBool isTLS; | |
10586 | |
10587 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
10588 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10589 PORT_Assert(srvrPubKey); | |
10590 | |
10591 clntPubKey.keyType = dhKey; | |
10592 clntPubKey.u.dh.prime.len = srvrPubKey->u.dh.prime.len; | |
10593 clntPubKey.u.dh.prime.data = srvrPubKey->u.dh.prime.data; | |
10594 clntPubKey.u.dh.base.len = srvrPubKey->u.dh.base.len; | |
10595 clntPubKey.u.dh.base.data = srvrPubKey->u.dh.base.data; | |
10596 | |
10597 rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.dh.publicValue, | |
10598 2, &b, &length); | |
10599 if (rv != SECSuccess) { | |
10600 goto loser; | |
10601 } | |
10602 | |
10603 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); | |
10604 | |
10605 if (isTLS) | |
10606 target = CKM_TLS_MASTER_KEY_DERIVE_DH; | |
10607 else | |
10608 target = CKM_SSL3_MASTER_KEY_DERIVE_DH; | |
10609 | |
10610 /* Determine the PMS */ | |
10611 pms = PK11_PubDerive(serverKey, &clntPubKey, PR_FALSE, NULL, NULL, | |
10612 CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL); | |
10613 if (pms == NULL) { | |
10614 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); | |
10615 goto loser; | |
10616 } | |
10617 | |
10618 rv = ssl3_InitPendingCipherSpec(ss, pms); | |
10619 PK11_FreeSymKey(pms); | |
10620 pms = NULL; | |
10621 | |
10622 loser: | |
10623 if (ss->dheKeyPair) { | |
10624 ssl3_FreeKeyPair(ss->dheKeyPair); | |
10625 ss->dheKeyPair = NULL; | |
10626 } | |
10627 return rv; | |
10628 } | |
10629 | |
10630 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered | |
10631 * a complete ssl3 ClientKeyExchange message from the remote client | |
10632 * Caller must hold Handshake and RecvBuf locks. | |
10633 */ | |
10634 static SECStatus | |
10635 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
10636 { | |
10637 SECKEYPrivateKey *serverKey = NULL; | |
10638 SECStatus rv; | |
10639 const ssl3KEADef *kea_def; | |
10640 ssl3KeyPair *serverKeyPair = NULL; | |
10641 SECKEYPublicKey *serverPubKey = NULL; | |
10642 | |
10643 SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake", | |
10644 SSL_GETPID(), ss->fd)); | |
10645 | |
10646 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
10647 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10648 | |
10649 if (ss->ssl3.hs.ws != wait_client_key) { | |
10650 SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
10651 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); | |
10652 return SECFailure; | |
10653 } | |
10654 | |
10655 kea_def = ss->ssl3.hs.kea_def; | |
10656 | |
10657 if (ss->ssl3.hs.usedStepDownKey) { | |
10658 PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */ | |
10659 && | |
10660 kea_def->exchKeyType == kt_rsa && | |
10661 ss->stepDownKeyPair != NULL); | |
10662 if (!kea_def->is_limited || | |
10663 kea_def->exchKeyType != kt_rsa || | |
10664 ss->stepDownKeyPair == NULL) { | |
10665 /* shouldn't happen, don't use step down if it does */ | |
10666 goto skip; | |
10667 } | |
10668 serverKeyPair = ss->stepDownKeyPair; | |
10669 ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB; | |
10670 } else | |
10671 skip: | |
10672 if (kea_def->kea == kea_dhe_dss || | |
10673 kea_def->kea == kea_dhe_rsa) { | |
10674 if (ss->dheKeyPair) { | |
10675 serverKeyPair = ss->dheKeyPair; | |
10676 if (serverKeyPair->pubKey) { | |
10677 ss->sec.keaKeyBits = | |
10678 SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey); | |
10679 } | |
10680 } | |
10681 } else | |
10682 #ifndef NSS_DISABLE_ECC | |
10683 /* XXX Using SSLKEAType to index server certifiates | |
10684 * does not work for (EC)DHE ciphers. Until we have | |
10685 * an indexing mechanism general enough for all key | |
10686 * exchange algorithms, we'll need to deal with each | |
10687 * one seprately. | |
10688 */ | |
10689 if ((kea_def->kea == kea_ecdhe_rsa) || | |
10690 (kea_def->kea == kea_ecdhe_ecdsa)) { | |
10691 if (ss->ephemeralECDHKeyPair != NULL) { | |
10692 serverKeyPair = ss->ephemeralECDHKeyPair; | |
10693 if (serverKeyPair->pubKey) { | |
10694 ss->sec.keaKeyBits = | |
10695 SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey); | |
10696 } | |
10697 } | |
10698 } else | |
10699 #endif | |
10700 { | |
10701 sslServerCerts *sc = ss->serverCerts + kea_def->exchKeyType; | |
10702 serverKeyPair = sc->serverKeyPair; | |
10703 ss->sec.keaKeyBits = sc->serverKeyBits; | |
10704 } | |
10705 | |
10706 if (serverKeyPair) { | |
10707 serverKey = serverKeyPair->privKey; | |
10708 } | |
10709 | |
10710 if (serverKey == NULL) { | |
10711 SEND_ALERT | |
10712 PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG); | |
10713 return SECFailure; | |
10714 } | |
10715 | |
10716 ss->sec.keaType = kea_def->exchKeyType; | |
10717 | |
10718 switch (kea_def->exchKeyType) { | |
10719 case kt_rsa: | |
10720 rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey); | |
10721 if (rv != SECSuccess) { | |
10722 SEND_ALERT | |
10723 return SECFailure; /* error code set */ | |
10724 } | |
10725 break; | |
10726 | |
10727 case ssl_kea_dh: | |
10728 if (ss->dheKeyPair && ss->dheKeyPair->pubKey) { | |
10729 serverPubKey = ss->dheKeyPair->pubKey; | |
10730 } | |
10731 if (!serverPubKey) { | |
10732 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); | |
10733 return SECFailure; | |
10734 } | |
10735 rv = ssl3_HandleDHClientKeyExchange(ss, b, length, | |
10736 serverPubKey, serverKey); | |
10737 if (rv != SECSuccess) { | |
10738 SSL3_SendAlert(ss, alert_fatal, handshake_failure); | |
10739 return SECFailure; /* error code set */ | |
10740 } | |
10741 break; | |
10742 | |
10743 #ifndef NSS_DISABLE_ECC | |
10744 case kt_ecdh: | |
10745 /* XXX We really ought to be able to store multiple | |
10746 * EC certs (a requirement if we wish to support both | |
10747 * ECDH-RSA and ECDH-ECDSA key exchanges concurrently). | |
10748 * When we make that change, we'll need an index other | |
10749 * than kt_ecdh to pick the right EC certificate. | |
10750 */ | |
10751 if (serverKeyPair) { | |
10752 serverPubKey = serverKeyPair->pubKey; | |
10753 } | |
10754 if (serverPubKey == NULL) { | |
10755 /* XXX Is this the right error code? */ | |
10756 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); | |
10757 return SECFailure; | |
10758 } | |
10759 rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, | |
10760 serverPubKey, serverKey); | |
10761 if (ss->ephemeralECDHKeyPair) { | |
10762 ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair); | |
10763 ss->ephemeralECDHKeyPair = NULL; | |
10764 } | |
10765 if (rv != SECSuccess) { | |
10766 return SECFailure; /* error code set */ | |
10767 } | |
10768 break; | |
10769 #endif /* NSS_DISABLE_ECC */ | |
10770 | |
10771 default: | |
10772 (void)ssl3_HandshakeFailure(ss); | |
10773 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); | |
10774 return SECFailure; | |
10775 } | |
10776 ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher; | |
10777 return SECSuccess; | |
10778 } | |
10779 | |
10780 /* This is TLS's equivalent of sending a no_certificate alert. */ | |
10781 SECStatus | |
10782 ssl3_SendEmptyCertificate(sslSocket *ss) | |
10783 { | |
10784 SECStatus rv; | |
10785 unsigned int len = 0; | |
10786 PRBool isTLS13 = PR_FALSE; | |
10787 | |
10788 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { | |
10789 len = ss->ssl3.hs.certReqContextLen + 1; | |
10790 isTLS13 = PR_TRUE; | |
10791 } | |
10792 | |
10793 rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3); | |
10794 if (rv != SECSuccess) { | |
10795 return rv; | |
10796 } | |
10797 | |
10798 if (isTLS13) { | |
10799 rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.hs.certReqContext, | |
10800 ss->ssl3.hs.certReqContextLen, 1); | |
10801 if (rv != SECSuccess) { | |
10802 return rv; | |
10803 } | |
10804 } | |
10805 | |
10806 return ssl3_AppendHandshakeNumber(ss, 0, 3); | |
10807 } | |
10808 | |
10809 SECStatus | |
10810 ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
10811 { | |
10812 SECStatus rv; | |
10813 SECItem ticketData; | |
10814 | |
10815 SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake", | |
10816 SSL_GETPID(), ss->fd)); | |
10817 | |
10818 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
10819 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10820 | |
10821 PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); | |
10822 PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket); | |
10823 | |
10824 if (ss->ssl3.hs.ws != wait_new_session_ticket) { | |
10825 SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
10826 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); | |
10827 return SECFailure; | |
10828 } | |
10829 | |
10830 /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid | |
10831 * until it has verified the server's Finished message." See the comment in | |
10832 * ssl3_FinishHandshake for more details. | |
10833 */ | |
10834 ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(); | |
10835 if (length < 4) { | |
10836 (void)SSL3_SendAlert(ss, alert_fatal, decode_error); | |
10837 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); | |
10838 return SECFailure; | |
10839 } | |
10840 ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = | |
10841 (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length); | |
10842 | |
10843 rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length); | |
10844 if (rv != SECSuccess || length != 0) { | |
10845 (void)SSL3_SendAlert(ss, alert_fatal, decode_error); | |
10846 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); | |
10847 return SECFailure; /* malformed */ | |
10848 } | |
10849 /* If the server sent a zero-length ticket, ignore it and keep the | |
10850 * existing ticket. */ | |
10851 if (ticketData.len != 0) { | |
10852 rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket, | |
10853 &ticketData); | |
10854 if (rv != SECSuccess) { | |
10855 return rv; | |
10856 } | |
10857 ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE; | |
10858 } | |
10859 | |
10860 ss->ssl3.hs.ws = wait_change_cipher; | |
10861 return SECSuccess; | |
10862 } | |
10863 | |
10864 #ifdef NISCC_TEST | |
10865 static PRInt32 connNum = 0; | |
10866 | |
10867 static SECStatus | |
10868 get_fake_cert(SECItem *pCertItem, int *pIndex) | |
10869 { | |
10870 PRFileDesc *cf; | |
10871 char *testdir; | |
10872 char *startat; | |
10873 char *stopat; | |
10874 const char *extension; | |
10875 int fileNum; | |
10876 PRInt32 numBytes = 0; | |
10877 PRStatus prStatus; | |
10878 PRFileInfo info; | |
10879 char cfn[100]; | |
10880 | |
10881 pCertItem->data = 0; | |
10882 if ((testdir = PR_GetEnvSecure("NISCC_TEST")) == NULL) { | |
10883 return SECSuccess; | |
10884 } | |
10885 *pIndex = (NULL != strstr(testdir, "root")); | |
10886 extension = (strstr(testdir, "simple") ? "" : ".der"); | |
10887 fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1; | |
10888 if ((startat = PR_GetEnvSecure("START_AT")) != NULL) { | |
10889 fileNum += atoi(startat); | |
10890 } | |
10891 if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL && | |
10892 fileNum >= atoi(stopat)) { | |
10893 *pIndex = -1; | |
10894 return SECSuccess; | |
10895 } | |
10896 sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension); | |
10897 cf = PR_Open(cfn, PR_RDONLY, 0); | |
10898 if (!cf) { | |
10899 goto loser; | |
10900 } | |
10901 prStatus = PR_GetOpenFileInfo(cf, &info); | |
10902 if (prStatus != PR_SUCCESS) { | |
10903 PR_Close(cf); | |
10904 goto loser; | |
10905 } | |
10906 pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size); | |
10907 if (pCertItem) { | |
10908 numBytes = PR_Read(cf, pCertItem->data, info.size); | |
10909 } | |
10910 PR_Close(cf); | |
10911 if (numBytes != info.size) { | |
10912 SECITEM_FreeItem(pCertItem, PR_FALSE); | |
10913 PORT_SetError(SEC_ERROR_IO); | |
10914 goto loser; | |
10915 } | |
10916 fprintf(stderr, "using %s\n", cfn); | |
10917 return SECSuccess; | |
10918 | |
10919 loser: | |
10920 fprintf(stderr, "failed to use %s\n", cfn); | |
10921 *pIndex = -1; | |
10922 return SECFailure; | |
10923 } | |
10924 #endif | |
10925 | |
10926 /* | |
10927 * Used by both client and server. | |
10928 * Called from HandleServerHelloDone and from SendServerHelloSequence. | |
10929 */ | |
10930 SECStatus | |
10931 ssl3_SendCertificate(sslSocket *ss) | |
10932 { | |
10933 SECStatus rv; | |
10934 CERTCertificateList *certChain; | |
10935 int certChainLen = 0; | |
10936 int i; | |
10937 SSL3KEAType certIndex; | |
10938 #ifdef NISCC_TEST | |
10939 SECItem fakeCert; | |
10940 int ndex = -1; | |
10941 #endif | |
10942 PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3; | |
10943 unsigned int contextLen = 0; | |
10944 | |
10945 SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake", | |
10946 SSL_GETPID(), ss->fd)); | |
10947 | |
10948 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
10949 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
10950 | |
10951 if (ss->sec.localCert) | |
10952 CERT_DestroyCertificate(ss->sec.localCert); | |
10953 if (ss->sec.isServer) { | |
10954 sslServerCerts *sc = NULL; | |
10955 | |
10956 /* XXX SSLKEAType isn't really a good choice for | |
10957 * indexing certificates (it breaks when we deal | |
10958 * with (EC)DHE-* cipher suites. This hack ensures | |
10959 * the RSA cert is picked for (EC)DHE-RSA. | |
10960 * Revisit this when we add server side support | |
10961 * for ECDHE-ECDSA or client-side authentication | |
10962 * using EC certificates. | |
10963 */ | |
10964 if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || | |
10965 (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { | |
10966 certIndex = kt_rsa; | |
10967 } else { | |
10968 certIndex = ss->ssl3.hs.kea_def->exchKeyType; | |
10969 } | |
10970 sc = ss->serverCerts + certIndex; | |
10971 certChain = sc->serverCertChain; | |
10972 ss->sec.authKeyBits = sc->serverKeyBits; | |
10973 ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; | |
10974 ss->sec.localCert = CERT_DupCertificate(sc->serverCert); | |
10975 } else { | |
10976 certChain = ss->ssl3.clientCertChain; | |
10977 ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate); | |
10978 } | |
10979 | |
10980 #ifdef NISCC_TEST | |
10981 rv = get_fake_cert(&fakeCert, &ndex); | |
10982 #endif | |
10983 | |
10984 if (isTLS13) { | |
10985 contextLen = 1; /* Length of the context */ | |
10986 if (!ss->sec.isServer) { | |
10987 contextLen += ss->ssl3.hs.certReqContextLen; | |
10988 } | |
10989 } | |
10990 if (certChain) { | |
10991 for (i = 0; i < certChain->len; i++) { | |
10992 #ifdef NISCC_TEST | |
10993 if (fakeCert.len > 0 && i == ndex) { | |
10994 certChainLen += fakeCert.len + 3; | |
10995 } else { | |
10996 certChainLen += certChain->certs[i].len + 3; | |
10997 } | |
10998 #else | |
10999 certChainLen += certChain->certs[i].len + 3; | |
11000 #endif | |
11001 } | |
11002 } | |
11003 | |
11004 rv = ssl3_AppendHandshakeHeader(ss, certificate, | |
11005 contextLen + certChainLen + 3); | |
11006 if (rv != SECSuccess) { | |
11007 return rv; /* err set by AppendHandshake. */ | |
11008 } | |
11009 | |
11010 if (isTLS13) { | |
11011 if (ss->sec.isServer) { | |
11012 rv = ssl3_AppendHandshakeNumber(ss, 0, 1); | |
11013 } else { | |
11014 rv = ssl3_AppendHandshakeVariable(ss, | |
11015 ss->ssl3.hs.certReqContext, | |
11016 ss->ssl3.hs.certReqContextLen, 1); | |
11017 } | |
11018 if (rv != SECSuccess) { | |
11019 return rv; /* err set by AppendHandshake. */ | |
11020 } | |
11021 } | |
11022 | |
11023 rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3); | |
11024 if (rv != SECSuccess) { | |
11025 return rv; /* err set by AppendHandshake. */ | |
11026 } | |
11027 if (certChain) { | |
11028 for (i = 0; i < certChain->len; i++) { | |
11029 #ifdef NISCC_TEST | |
11030 if (fakeCert.len > 0 && i == ndex) { | |
11031 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data, | |
11032 fakeCert.len, 3); | |
11033 SECITEM_FreeItem(&fakeCert, PR_FALSE); | |
11034 } else { | |
11035 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, | |
11036 certChain->certs[i].len, 3); | |
11037 } | |
11038 #else | |
11039 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, | |
11040 certChain->certs[i].len, 3); | |
11041 #endif | |
11042 if (rv != SECSuccess) { | |
11043 return rv; /* err set by AppendHandshake. */ | |
11044 } | |
11045 } | |
11046 } | |
11047 | |
11048 return SECSuccess; | |
11049 } | |
11050 | |
11051 /* | |
11052 * Used by server only. | |
11053 * single-stapling, send only a single cert status | |
11054 */ | |
11055 SECStatus | |
11056 ssl3_SendCertificateStatus(sslSocket *ss) | |
11057 { | |
11058 SECStatus rv; | |
11059 int len = 0; | |
11060 SECItemArray *statusToSend = NULL; | |
11061 SSL3KEAType certIndex; | |
11062 | |
11063 SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake", | |
11064 SSL_GETPID(), ss->fd)); | |
11065 | |
11066 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
11067 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
11068 PORT_Assert(ss->sec.isServer); | |
11069 | |
11070 if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) | |
11071 return SECSuccess; | |
11072 | |
11073 /* Use certStatus based on the cert being used. */ | |
11074 if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || | |
11075 (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { | |
11076 certIndex = kt_rsa; | |
11077 } else { | |
11078 certIndex = ss->ssl3.hs.kea_def->exchKeyType; | |
11079 } | |
11080 if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) { | |
11081 statusToSend = ss->certStatusArray[certIndex]; | |
11082 } | |
11083 if (!statusToSend) | |
11084 return SECSuccess; | |
11085 | |
11086 /* Use the array's first item only (single stapling) */ | |
11087 len = 1 + statusToSend->items[0].len + 3; | |
11088 | |
11089 rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len); | |
11090 if (rv != SECSuccess) { | |
11091 return rv; /* err set by AppendHandshake. */ | |
11092 } | |
11093 rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1); | |
11094 if (rv != SECSuccess) | |
11095 return rv; /* err set by AppendHandshake. */ | |
11096 | |
11097 rv = ssl3_AppendHandshakeVariable(ss, | |
11098 statusToSend->items[0].data, | |
11099 statusToSend->items[0].len, | |
11100 3); | |
11101 if (rv != SECSuccess) | |
11102 return rv; /* err set by AppendHandshake. */ | |
11103 | |
11104 return SECSuccess; | |
11105 } | |
11106 | |
11107 /* This is used to delete the CA certificates in the peer certificate chain | |
11108 * from the cert database after they've been validated. | |
11109 */ | |
11110 static void | |
11111 ssl3_CleanupPeerCerts(sslSocket *ss) | |
11112 { | |
11113 PLArenaPool *arena = ss->ssl3.peerCertArena; | |
11114 ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain; | |
11115 | |
11116 for (; certs; certs = certs->next) { | |
11117 CERT_DestroyCertificate(certs->cert); | |
11118 } | |
11119 if (arena) | |
11120 PORT_FreeArena(arena, PR_FALSE); | |
11121 ss->ssl3.peerCertArena = NULL; | |
11122 ss->ssl3.peerCertChain = NULL; | |
11123 } | |
11124 | |
11125 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered | |
11126 * a complete ssl3 CertificateStatus message. | |
11127 * Caller must hold Handshake and RecvBuf locks. | |
11128 */ | |
11129 static SECStatus | |
11130 ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
11131 { | |
11132 if (ss->ssl3.hs.ws != wait_certificate_status) { | |
11133 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11134 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS); | |
11135 return SECFailure; | |
11136 } | |
11137 | |
11138 return ssl3_CompleteHandleCertificateStatus(ss, b, length); | |
11139 } | |
11140 | |
11141 /* Called from: | |
11142 * ssl3_HandleCertificateStatus | |
11143 * tls13_HandleCertificateStatus | |
11144 */ | |
11145 SECStatus | |
11146 ssl3_CompleteHandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, | |
11147 PRUint32 length) | |
11148 { | |
11149 PRInt32 status, len; | |
11150 | |
11151 PORT_Assert(!ss->sec.isServer); | |
11152 | |
11153 /* Consume the CertificateStatusType enum */ | |
11154 status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); | |
11155 if (status != 1 /* ocsp */) { | |
11156 goto format_loser; | |
11157 } | |
11158 | |
11159 len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); | |
11160 if (len != length) { | |
11161 goto format_loser; | |
11162 } | |
11163 | |
11164 #define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */ | |
11165 if (length > MAX_CERTSTATUS_LEN) | |
11166 goto format_loser; | |
11167 #undef MAX_CERTSTATUS_LEN | |
11168 | |
11169 /* Array size 1, because we currently implement single-stapling only */ | |
11170 SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1); | |
11171 if (!ss->sec.ci.sid->peerCertStatus.items) | |
11172 return SECFailure; | |
11173 | |
11174 ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length); | |
11175 | |
11176 if (!ss->sec.ci.sid->peerCertStatus.items[0].data) { | |
11177 SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE); | |
11178 return SECFailure; | |
11179 } | |
11180 | |
11181 PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length); | |
11182 ss->sec.ci.sid->peerCertStatus.items[0].len = length; | |
11183 ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer; | |
11184 | |
11185 return ssl3_AuthCertificate(ss); | |
11186 | |
11187 format_loser: | |
11188 return ssl3_DecodeError(ss); | |
11189 } | |
11190 | |
11191 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered | |
11192 * a complete ssl3 Certificate message. | |
11193 * Caller must hold Handshake and RecvBuf locks. | |
11194 */ | |
11195 static SECStatus | |
11196 ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
11197 { | |
11198 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake", | |
11199 SSL_GETPID(), ss->fd)); | |
11200 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
11201 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
11202 | |
11203 if ((ss->sec.isServer && ss->ssl3.hs.ws != wait_client_cert) || | |
11204 (!ss->sec.isServer && ss->ssl3.hs.ws != wait_server_cert)) { | |
11205 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
11206 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE); | |
11207 return SECFailure; | |
11208 } | |
11209 | |
11210 return ssl3_CompleteHandleCertificate(ss, b, length); | |
11211 } | |
11212 | |
11213 /* Called from ssl3_HandleCertificate | |
11214 */ | |
11215 SECStatus | |
11216 ssl3_CompleteHandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
11217 { | |
11218 ssl3CertNode *c; | |
11219 ssl3CertNode *lastCert = NULL; | |
11220 PRInt32 remaining = 0; | |
11221 PRInt32 size; | |
11222 SECStatus rv; | |
11223 PRBool isServer = (PRBool)(!!ss->sec.isServer); | |
11224 PRBool isTLS; | |
11225 SSL3AlertDescription desc; | |
11226 int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE; | |
11227 SECItem certItem; | |
11228 | |
11229 if (ss->sec.peerCert != NULL) { | |
11230 if (ss->sec.peerKey) { | |
11231 SECKEY_DestroyPublicKey(ss->sec.peerKey); | |
11232 ss->sec.peerKey = NULL; | |
11233 } | |
11234 CERT_DestroyCertificate(ss->sec.peerCert); | |
11235 ss->sec.peerCert = NULL; | |
11236 } | |
11237 | |
11238 ssl3_CleanupPeerCerts(ss); | |
11239 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); | |
11240 | |
11241 /* It is reported that some TLS client sends a Certificate message | |
11242 ** with a zero-length message body. We'll treat that case like a | |
11243 ** normal no_certificates message to maximize interoperability. | |
11244 */ | |
11245 if (length) { | |
11246 remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); | |
11247 if (remaining < 0) | |
11248 goto loser; /* fatal alert already sent by ConsumeHandshake. */ | |
11249 if ((PRUint32)remaining > length) | |
11250 goto decode_loser; | |
11251 } | |
11252 | |
11253 if (!remaining) { | |
11254 if (!(isTLS && isServer)) { | |
11255 desc = bad_certificate; | |
11256 goto alert_loser; | |
11257 } | |
11258 /* This is TLS's version of a no_certificate alert. */ | |
11259 /* I'm a server. I've requested a client cert. He hasn't got one. */ | |
11260 rv = ssl3_HandleNoCertificate(ss); | |
11261 if (rv != SECSuccess) { | |
11262 errCode = PORT_GetError(); | |
11263 goto loser; | |
11264 } | |
11265 | |
11266 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { | |
11267 ss->ssl3.hs.ws = wait_client_key; | |
11268 } else { | |
11269 TLS13_SET_HS_STATE(ss, wait_finished); | |
11270 } | |
11271 return SECSuccess; | |
11272 } | |
11273 | |
11274 ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); | |
11275 if (ss->ssl3.peerCertArena == NULL) { | |
11276 goto loser; /* don't send alerts on memory errors */ | |
11277 } | |
11278 | |
11279 /* First get the peer cert. */ | |
11280 remaining -= 3; | |
11281 if (remaining < 0) | |
11282 goto decode_loser; | |
11283 | |
11284 size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); | |
11285 if (size <= 0) | |
11286 goto loser; /* fatal alert already sent by ConsumeHandshake. */ | |
11287 | |
11288 if (remaining < size) | |
11289 goto decode_loser; | |
11290 | |
11291 certItem.data = b; | |
11292 certItem.len = size; | |
11293 b += size; | |
11294 length -= size; | |
11295 remaining -= size; | |
11296 | |
11297 ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, | |
11298 PR_FALSE, PR_TRUE); | |
11299 if (ss->sec.peerCert == NULL) { | |
11300 /* We should report an alert if the cert was bad, but not if the | |
11301 * problem was just some local problem, like memory error. | |
11302 */ | |
11303 goto ambiguous_err; | |
11304 } | |
11305 | |
11306 /* Now get all of the CA certs. */ | |
11307 while (remaining > 0) { | |
11308 remaining -= 3; | |
11309 if (remaining < 0) | |
11310 goto decode_loser; | |
11311 | |
11312 size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); | |
11313 if (size <= 0) | |
11314 goto loser; /* fatal alert already sent by ConsumeHandshake. */ | |
11315 | |
11316 if (remaining < size) | |
11317 goto decode_loser; | |
11318 | |
11319 certItem.data = b; | |
11320 certItem.len = size; | |
11321 b += size; | |
11322 length -= size; | |
11323 remaining -= size; | |
11324 | |
11325 c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode); | |
11326 if (c == NULL) { | |
11327 goto loser; /* don't send alerts on memory errors */ | |
11328 } | |
11329 | |
11330 c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, | |
11331 PR_FALSE, PR_TRUE); | |
11332 if (c->cert == NULL) { | |
11333 goto ambiguous_err; | |
11334 } | |
11335 | |
11336 c->next = NULL; | |
11337 if (lastCert) { | |
11338 lastCert->next = c; | |
11339 } else { | |
11340 ss->ssl3.peerCertChain = c; | |
11341 } | |
11342 lastCert = c; | |
11343 } | |
11344 | |
11345 if (remaining != 0) | |
11346 goto decode_loser; | |
11347 | |
11348 SECKEY_UpdateCertPQG(ss->sec.peerCert); | |
11349 | |
11350 if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) { | |
11351 ss->ssl3.hs.ws = wait_certificate_status; | |
11352 rv = SECSuccess; | |
11353 } else { | |
11354 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ | |
11355 } | |
11356 | |
11357 return rv; | |
11358 | |
11359 ambiguous_err: | |
11360 errCode = PORT_GetError(); | |
11361 switch (errCode) { | |
11362 case PR_OUT_OF_MEMORY_ERROR: | |
11363 case SEC_ERROR_BAD_DATABASE: | |
11364 case SEC_ERROR_NO_MEMORY: | |
11365 if (isTLS) { | |
11366 desc = internal_error; | |
11367 goto alert_loser; | |
11368 } | |
11369 goto loser; | |
11370 } | |
11371 ssl3_SendAlertForCertError(ss, errCode); | |
11372 goto loser; | |
11373 | |
11374 decode_loser: | |
11375 desc = isTLS ? decode_error : bad_certificate; | |
11376 | |
11377 alert_loser: | |
11378 (void)SSL3_SendAlert(ss, alert_fatal, desc); | |
11379 | |
11380 loser: | |
11381 (void)ssl_MapLowLevelError(errCode); | |
11382 return SECFailure; | |
11383 } | |
11384 | |
11385 static SECStatus | |
11386 ssl3_AuthCertificate(sslSocket *ss) | |
11387 { | |
11388 SECStatus rv; | |
11389 PRBool isServer = (PRBool)(!!ss->sec.isServer); | |
11390 int errCode; | |
11391 | |
11392 ss->ssl3.hs.authCertificatePending = PR_FALSE; | |
11393 | |
11394 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == | |
11395 ssl_preinfo_all); | |
11396 /* | |
11397 * Ask caller-supplied callback function to validate cert chain. | |
11398 */ | |
11399 rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd, | |
11400 PR_TRUE, isServer); | |
11401 if (rv != SECSuccess) { | |
11402 errCode = PORT_GetError(); | |
11403 if (rv != SECWouldBlock) { | |
11404 if (ss->handleBadCert) { | |
11405 rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd); | |
11406 } | |
11407 } | |
11408 | |
11409 if (rv == SECWouldBlock) { | |
11410 if (ss->sec.isServer) { | |
11411 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS; | |
11412 rv = SECFailure; | |
11413 goto loser; | |
11414 } | |
11415 /* TODO(ekr@rtfm.com): Reenable for TLS 1.3 */ | |
11416 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { | |
11417 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION; | |
11418 rv = SECFailure; | |
11419 goto loser; | |
11420 } | |
11421 | |
11422 ss->ssl3.hs.authCertificatePending = PR_TRUE; | |
11423 rv = SECSuccess; | |
11424 } | |
11425 | |
11426 if (rv != SECSuccess) { | |
11427 ssl3_SendAlertForCertError(ss, errCode); | |
11428 goto loser; | |
11429 } | |
11430 } | |
11431 | |
11432 ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert); | |
11433 ssl3_CopyPeerCertsToSID(ss->ssl3.peerCertChain, ss->sec.ci.sid); | |
11434 | |
11435 if (!ss->sec.isServer) { | |
11436 CERTCertificate *cert = ss->sec.peerCert; | |
11437 | |
11438 /* set the server authentication type and size from the value | |
11439 ** in the cert. */ | |
11440 SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(cert); | |
11441 ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; | |
11442 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; | |
11443 if (pubKey) { | |
11444 KeyType pubKeyType; | |
11445 PRInt32 minKey; | |
11446 /* This partly fixes Bug 124230 and may cause problems for | |
11447 * callers which depend on the old (wrong) behavior. */ | |
11448 ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(pubKey); | |
11449 pubKeyType = SECKEY_GetPublicKeyType(pubKey); | |
11450 minKey = ss->sec.authKeyBits; | |
11451 switch (pubKeyType) { | |
11452 case rsaKey: | |
11453 case rsaPssKey: | |
11454 case rsaOaepKey: | |
11455 rv = | |
11456 NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &minKey); | |
11457 if (rv != | |
11458 SECSuccess) { | |
11459 minKey = | |
11460 SSL_RSA_MIN_MODULUS_BITS; | |
11461 } | |
11462 break; | |
11463 case dsaKey: | |
11464 rv = | |
11465 NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &minKey); | |
11466 if (rv != | |
11467 SECSuccess) { | |
11468 minKey = | |
11469 SSL_DSA_MIN_P_BITS; | |
11470 } | |
11471 break; | |
11472 case dhKey: | |
11473 rv = | |
11474 NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minKey); | |
11475 if (rv != | |
11476 SECSuccess) { | |
11477 minKey = | |
11478 SSL_DH_MIN_P_BITS; | |
11479 } | |
11480 break; | |
11481 default: | |
11482 break; | |
11483 } | |
11484 | |
11485 /* Too small: not good enough. Send a fatal alert. */ | |
11486 /* We aren't checking EC here on the understanding that we only | |
11487 * support curves we like, a decision that might need revisiting. */ | |
11488 if (ss->sec.authKeyBits < minKey) { | |
11489 PORT_SetError(SSL_ERROR_WEAK_SERVER_CERT_KEY); | |
11490 (void)SSL3_SendAlert(ss, alert_fatal, | |
11491 ss->version >= SSL_LIBRARY_VERSION_TLS_1_0 | |
11492 ? insufficient_security | |
11493 : illegal_parameter); | |
11494 SECKEY_DestroyPublicKey(pubKey); | |
11495 return SECFailure; | |
11496 } | |
11497 SECKEY_DestroyPublicKey(pubKey); | |
11498 pubKey = NULL; | |
11499 } | |
11500 | |
11501 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { | |
11502 TLS13_SET_HS_STATE(ss, wait_cert_verify); | |
11503 } else { | |
11504 /* Ephemeral suites require ServerKeyExchange. Export cipher suites | |
11505 * with RSA key exchange also require ServerKeyExchange if the | |
11506 * authentication key exceeds the key size limit. */ | |
11507 if (ss->ssl3.hs.kea_def->ephemeral || | |
11508 (ss->ssl3.hs.kea_def->is_limited && | |
11509 ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_rsa && | |
11510 ss->sec.authKeyBits > ss->ssl3.hs.kea_def->key_size_limit)) { | |
11511 /* require server_key_exchange */ | |
11512 ss->ssl3.hs.ws = wait_server_key; | |
11513 } else { | |
11514 /* disallow server_key_exchange */ | |
11515 ss->ssl3.hs.ws = wait_cert_request; | |
11516 /* This is static RSA key exchange so set the key bits to | |
11517 * auth bits. */ | |
11518 ss->sec.keaKeyBits = ss->sec.authKeyBits; | |
11519 } | |
11520 } | |
11521 } else { | |
11522 /* Server */ | |
11523 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { | |
11524 ss->ssl3.hs.ws = wait_client_key; | |
11525 } else { | |
11526 TLS13_SET_HS_STATE(ss, wait_cert_verify); | |
11527 } | |
11528 } | |
11529 | |
11530 PORT_Assert(rv == SECSuccess); | |
11531 if (rv != SECSuccess) { | |
11532 errCode = SEC_ERROR_LIBRARY_FAILURE; | |
11533 rv = SECFailure; | |
11534 goto loser; | |
11535 } | |
11536 | |
11537 return rv; | |
11538 | |
11539 loser: | |
11540 (void)ssl_MapLowLevelError(errCode); | |
11541 return SECFailure; | |
11542 } | |
11543 | |
11544 static SECStatus ssl3_FinishHandshake(sslSocket *ss); | |
11545 | |
11546 static SECStatus | |
11547 ssl3_AlwaysFail(sslSocket *ss) | |
11548 { | |
11549 PORT_SetError(PR_INVALID_STATE_ERROR); | |
11550 return SECFailure; | |
11551 } | |
11552 | |
11553 /* Caller must hold 1stHandshakeLock. | |
11554 */ | |
11555 SECStatus | |
11556 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error) | |
11557 { | |
11558 SECStatus rv; | |
11559 | |
11560 PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); | |
11561 | |
11562 if (ss->sec.isServer) { | |
11563 PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS); | |
11564 return SECFailure; | |
11565 } | |
11566 | |
11567 ssl_GetRecvBufLock(ss); | |
11568 ssl_GetSSL3HandshakeLock(ss); | |
11569 | |
11570 if (!ss->ssl3.hs.authCertificatePending) { | |
11571 PORT_SetError(PR_INVALID_STATE_ERROR); | |
11572 rv = SECFailure; | |
11573 goto done; | |
11574 } | |
11575 | |
11576 ss->ssl3.hs.authCertificatePending = PR_FALSE; | |
11577 | |
11578 if (error != 0) { | |
11579 ss->ssl3.hs.restartTarget = ssl3_AlwaysFail; | |
11580 ssl3_SendAlertForCertError(ss, error); | |
11581 rv = SECSuccess; | |
11582 } else if (ss->ssl3.hs.restartTarget != NULL) { | |
11583 sslRestartTarget target = ss->ssl3.hs.restartTarget; | |
11584 ss->ssl3.hs.restartTarget = NULL; | |
11585 | |
11586 if (target == ssl3_FinishHandshake) { | |
11587 SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication lost the race" | |
11588 " with peer's finished message", | |
11589 SSL_GETPID(), ss->fd)); | |
11590 } | |
11591 | |
11592 rv = target(ss); | |
11593 /* Even if we blocked here, we have accomplished enough to claim | |
11594 * success. Any remaining work will be taken care of by subsequent | |
11595 * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc. | |
11596 */ | |
11597 if (rv == SECWouldBlock) { | |
11598 rv = SECSuccess; | |
11599 } | |
11600 } else { | |
11601 SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with" | |
11602 " peer's finished message", | |
11603 SSL_GETPID(), ss->fd)); | |
11604 | |
11605 PORT_Assert(!ss->ssl3.hs.isResuming); | |
11606 PORT_Assert(ss->ssl3.hs.ws != idle_handshake); | |
11607 | |
11608 if (ss->opt.enableFalseStart && | |
11609 !ss->firstHsDone && | |
11610 !ss->ssl3.hs.isResuming && | |
11611 ssl3_WaitingForServerSecondRound(ss)) { | |
11612 /* ssl3_SendClientSecondRound deferred the false start check because | |
11613 * certificate authentication was pending, so we do it now if we sti
ll | |
11614 * haven't received all of the server's second round yet. | |
11615 */ | |
11616 rv = ssl3_CheckFalseStart(ss); | |
11617 } else { | |
11618 rv = SECSuccess; | |
11619 } | |
11620 } | |
11621 | |
11622 done: | |
11623 ssl_ReleaseSSL3HandshakeLock(ss); | |
11624 ssl_ReleaseRecvBufLock(ss); | |
11625 | |
11626 return rv; | |
11627 } | |
11628 | |
11629 static SECStatus | |
11630 ssl3_ComputeTLSFinished(ssl3CipherSpec *spec, | |
11631 PRBool isServer, | |
11632 const SSL3Hashes *hashes, | |
11633 TLSFinished *tlsFinished) | |
11634 { | |
11635 SECStatus rv; | |
11636 CK_TLS_MAC_PARAMS tls_mac_params; | |
11637 SECItem param = { siBuffer, NULL, 0 }; | |
11638 PK11Context *prf_context; | |
11639 unsigned int retLen; | |
11640 | |
11641 if (!spec->master_secret || spec->bypassCiphers) { | |
11642 const char *label = isServer ? "server finished" : "client finished"; | |
11643 unsigned int len = 15; | |
11644 | |
11645 return ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw, | |
11646 hashes->len, tlsFinished->verify_data
, | |
11647 sizeof tlsFinished->verify_data); | |
11648 } | |
11649 | |
11650 if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) { | |
11651 tls_mac_params.prfMechanism = CKM_TLS_PRF; | |
11652 } else { | |
11653 tls_mac_params.prfMechanism = CKM_SHA256; | |
11654 } | |
11655 tls_mac_params.ulMacLength = 12; | |
11656 tls_mac_params.ulServerOrClient = isServer ? 1 : 2; | |
11657 param.data = (unsigned char *)&tls_mac_params; | |
11658 param.len = sizeof(tls_mac_params); | |
11659 prf_context = PK11_CreateContextBySymKey(CKM_TLS_MAC, CKA_SIGN, | |
11660 spec->master_secret, ¶m); | |
11661 if (!prf_context) | |
11662 return SECFailure; | |
11663 | |
11664 rv = PK11_DigestBegin(prf_context); | |
11665 rv |= PK11_DigestOp(prf_context, hashes->u.raw, hashes->len); | |
11666 rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data, &retLen, | |
11667 sizeof tlsFinished->verify_data); | |
11668 PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data); | |
11669 | |
11670 PK11_DestroyContext(prf_context, PR_TRUE); | |
11671 | |
11672 return rv; | |
11673 } | |
11674 | |
11675 /* The calling function must acquire and release the appropriate | |
11676 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for | |
11677 * ss->ssl3.crSpec). | |
11678 */ | |
11679 SECStatus | |
11680 ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label, | |
11681 unsigned int labelLen, const unsigned char *val, uns
igned int valLen, | |
11682 unsigned char *out, unsigned int outLen) | |
11683 { | |
11684 SECStatus rv = SECSuccess; | |
11685 | |
11686 if (spec->master_secret && !spec->bypassCiphers) { | |
11687 SECItem param = { siBuffer, NULL, 0 }; | |
11688 CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL; | |
11689 PK11Context *prf_context; | |
11690 unsigned int retLen; | |
11691 | |
11692 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
11693 mech = CKM_NSS_TLS_PRF_GENERAL_SHA256; | |
11694 } | |
11695 prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN, | |
11696 spec->master_secret, ¶m); | |
11697 if (!prf_context) | |
11698 return SECFailure; | |
11699 | |
11700 rv = PK11_DigestBegin(prf_context); | |
11701 rv |= PK11_DigestOp(prf_context, (unsigned char *)label, labelLen); | |
11702 rv |= PK11_DigestOp(prf_context, val, valLen); | |
11703 rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen); | |
11704 PORT_Assert(rv != SECSuccess || retLen == outLen); | |
11705 | |
11706 PK11_DestroyContext(prf_context, PR_TRUE); | |
11707 } else { | |
11708 /* bypass PKCS11 */ | |
11709 #ifdef NO_PKCS11_BYPASS | |
11710 PORT_Assert(spec->master_secret); | |
11711 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
11712 rv = SECFailure; | |
11713 #else | |
11714 SECItem inData = { siBuffer }; | |
11715 SECItem outData = { siBuffer }; | |
11716 PRBool isFIPS = PR_FALSE; | |
11717 | |
11718 inData.data = (unsigned char *)val; | |
11719 inData.len = valLen; | |
11720 outData.data = out; | |
11721 outData.len = outLen; | |
11722 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { | |
11723 rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData, | |
11724 &outData, isFIPS); | |
11725 } else { | |
11726 rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS); | |
11727 } | |
11728 PORT_Assert(rv != SECSuccess || outData.len == outLen); | |
11729 #endif | |
11730 } | |
11731 return rv; | |
11732 } | |
11733 | |
11734 /* called from ssl3_SendClientSecondRound | |
11735 * ssl3_HandleFinished | |
11736 */ | |
11737 static SECStatus | |
11738 ssl3_SendNextProto(sslSocket *ss) | |
11739 { | |
11740 SECStatus rv; | |
11741 int padding_len; | |
11742 static const unsigned char padding[32] = { 0 }; | |
11743 | |
11744 if (ss->ssl3.nextProto.len == 0 || | |
11745 ss->ssl3.nextProtoState == SSL_NEXT_PROTO_SELECTED) { | |
11746 return SECSuccess; | |
11747 } | |
11748 | |
11749 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
11750 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
11751 | |
11752 padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32); | |
11753 | |
11754 rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len + | |
11755 2 + | |
11756 padding_len); | |
11757 if (rv != SECSuccess) { | |
11758 return rv; /* error code set by AppendHandshakeHeader */ | |
11759 } | |
11760 rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data, | |
11761 ss->ssl3.nextProto.len, 1); | |
11762 if (rv != SECSuccess) { | |
11763 return rv; /* error code set by AppendHandshake */ | |
11764 } | |
11765 rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1); | |
11766 if (rv != SECSuccess) { | |
11767 return rv; /* error code set by AppendHandshake */ | |
11768 } | |
11769 return rv; | |
11770 } | |
11771 | |
11772 /* called from ssl3_SendFinished | |
11773 * | |
11774 * This function is simply a debugging aid and therefore does not return a | |
11775 * SECStatus. */ | |
11776 static void | |
11777 ssl3_RecordKeyLog(sslSocket *ss) | |
11778 { | |
11779 SECStatus rv; | |
11780 SECItem *keyData; | |
11781 char buf[14 /* "CLIENT_RANDOM " */ + | |
11782 SSL3_RANDOM_LENGTH * 2 /* client_random */ + | |
11783 1 /* " " */ + | |
11784 48 * 2 /* master secret */ + | |
11785 1 /* new line */]; | |
11786 unsigned int j; | |
11787 | |
11788 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
11789 | |
11790 if (!ssl_keylog_iob) | |
11791 return; | |
11792 | |
11793 rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret); | |
11794 if (rv != SECSuccess) | |
11795 return; | |
11796 | |
11797 ssl_GetSpecReadLock(ss); | |
11798 | |
11799 /* keyData does not need to be freed. */ | |
11800 keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret); | |
11801 if (!keyData || !keyData->data || keyData->len != 48) { | |
11802 ssl_ReleaseSpecReadLock(ss); | |
11803 return; | |
11804 } | |
11805 | |
11806 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ | |
11807 | |
11808 /* There could be multiple, concurrent writers to the | |
11809 * keylog, so we have to do everything in a single call to | |
11810 * fwrite. */ | |
11811 | |
11812 memcpy(buf, "CLIENT_RANDOM ", 14); | |
11813 j = 14; | |
11814 hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH); | |
11815 j += SSL3_RANDOM_LENGTH * 2; | |
11816 buf[j++] = ' '; | |
11817 hexEncode(buf + j, keyData->data, 48); | |
11818 j += 48 * 2; | |
11819 buf[j++] = '\n'; | |
11820 | |
11821 PORT_Assert(j == sizeof(buf)); | |
11822 | |
11823 ssl_ReleaseSpecReadLock(ss); | |
11824 | |
11825 if (fwrite(buf, sizeof(buf), 1, ssl_keylog_iob) != 1) | |
11826 return; | |
11827 fflush(ssl_keylog_iob); | |
11828 return; | |
11829 } | |
11830 | |
11831 /* called from ssl3_SendClientSecondRound | |
11832 * ssl3_HandleFinished | |
11833 */ | |
11834 static SECStatus | |
11835 ssl3_SendChannelIDEncryptedExtensions(sslSocket *ss) | |
11836 { | |
11837 static const char CHANNEL_ID_MAGIC[] = "TLS Channel ID signature"; | |
11838 static const char CHANNEL_ID_RESUMPTION_MAGIC[] = "Resumption"; | |
11839 /* This is the ASN.1 prefix for a P-256 public key. Specifically it's: | |
11840 * SEQUENCE | |
11841 * SEQUENCE | |
11842 * OID id-ecPublicKey | |
11843 * OID prime256v1 | |
11844 * BIT STRING, length 66, 0 trailing bits: 0x04 | |
11845 * | |
11846 * The 0x04 in the BIT STRING is the prefix for an uncompressed, X9.62 | |
11847 * public key. Following that are the two field elements as 32-byte, | |
11848 * big-endian numbers, as required by the Channel ID. */ | |
11849 static const unsigned char P256_SPKI_PREFIX[] = { | |
11850 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, | |
11851 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, | |
11852 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, | |
11853 0x42, 0x00, 0x04 | |
11854 }; | |
11855 /* ChannelIDs are always 128 bytes long: 64 bytes of P-256 public key and 64 | |
11856 * bytes of ECDSA signature. */ | |
11857 static const int CHANNEL_ID_PUBLIC_KEY_LENGTH = 64; | |
11858 static const int CHANNEL_ID_LENGTH = 128; | |
11859 | |
11860 SECStatus rv = SECFailure; | |
11861 SECItem *spki = NULL; | |
11862 SSL3Hashes hashes; | |
11863 const unsigned char *pub_bytes; | |
11864 unsigned char signed_data[sizeof(CHANNEL_ID_MAGIC) + | |
11865 sizeof(CHANNEL_ID_RESUMPTION_MAGIC) + | |
11866 sizeof(SSL3Hashes) * 2]; | |
11867 size_t signed_data_len; | |
11868 unsigned char digest[SHA256_LENGTH]; | |
11869 SECItem digest_item; | |
11870 unsigned char signature[64]; | |
11871 SECItem signature_item; | |
11872 | |
11873 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
11874 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
11875 | |
11876 if (ss->ssl3.channelID == NULL) | |
11877 return SECSuccess; | |
11878 | |
11879 PORT_Assert(ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)); | |
11880 | |
11881 if (SECKEY_GetPrivateKeyType(ss->ssl3.channelID) != ecKey || | |
11882 PK11_SignatureLen(ss->ssl3.channelID) != sizeof(signature)) { | |
11883 PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY); | |
11884 rv = SECFailure; | |
11885 goto loser; | |
11886 } | |
11887 | |
11888 ssl_GetSpecReadLock(ss); | |
11889 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0); | |
11890 ssl_ReleaseSpecReadLock(ss); | |
11891 | |
11892 if (rv != SECSuccess) | |
11893 goto loser; | |
11894 | |
11895 rv = ssl3_AppendHandshakeHeader(ss, channelid_encrypted_extensions, | |
11896 2 + 2 + CHANNEL_ID_LENGTH); | |
11897 if (rv != SECSuccess) | |
11898 goto loser; /* error code set by AppendHandshakeHeader */ | |
11899 rv = ssl3_AppendHandshakeNumber(ss, ssl_channel_id_xtn, 2); | |
11900 if (rv != SECSuccess) | |
11901 goto loser; /* error code set by AppendHandshake */ | |
11902 rv = ssl3_AppendHandshakeNumber(ss, CHANNEL_ID_LENGTH, 2); | |
11903 if (rv != SECSuccess) | |
11904 goto loser; /* error code set by AppendHandshake */ | |
11905 | |
11906 spki = SECKEY_EncodeDERSubjectPublicKeyInfo(ss->ssl3.channelIDPub); | |
11907 | |
11908 if (spki->len != sizeof(P256_SPKI_PREFIX) + CHANNEL_ID_PUBLIC_KEY_LENGTH || | |
11909 memcmp(spki->data, P256_SPKI_PREFIX, sizeof(P256_SPKI_PREFIX)) != 0) { | |
11910 PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY); | |
11911 rv = SECFailure; | |
11912 goto loser; | |
11913 } | |
11914 | |
11915 pub_bytes = spki->data + sizeof(P256_SPKI_PREFIX); | |
11916 | |
11917 signed_data_len = 0; | |
11918 memcpy(signed_data + signed_data_len, CHANNEL_ID_MAGIC, | |
11919 sizeof(CHANNEL_ID_MAGIC)); | |
11920 signed_data_len += sizeof(CHANNEL_ID_MAGIC); | |
11921 if (ss->ssl3.hs.isResuming) { | |
11922 SECItem *originalHandshakeHash = | |
11923 &ss->sec.ci.sid->u.ssl3.originalHandshakeHash; | |
11924 PORT_Assert(originalHandshakeHash->len > 0); | |
11925 | |
11926 memcpy(signed_data + signed_data_len, CHANNEL_ID_RESUMPTION_MAGIC, | |
11927 sizeof(CHANNEL_ID_RESUMPTION_MAGIC)); | |
11928 signed_data_len += sizeof(CHANNEL_ID_RESUMPTION_MAGIC); | |
11929 memcpy(signed_data + signed_data_len, originalHandshakeHash->data, | |
11930 originalHandshakeHash->len); | |
11931 signed_data_len += originalHandshakeHash->len; | |
11932 } | |
11933 memcpy(signed_data + signed_data_len, hashes.u.raw, hashes.len); | |
11934 signed_data_len += hashes.len; | |
11935 | |
11936 rv = PK11_HashBuf(SEC_OID_SHA256, digest, signed_data, signed_data_len); | |
11937 if (rv != SECSuccess) | |
11938 goto loser; | |
11939 | |
11940 digest_item.data = digest; | |
11941 digest_item.len = sizeof(digest); | |
11942 | |
11943 signature_item.data = signature; | |
11944 signature_item.len = sizeof(signature); | |
11945 | |
11946 rv = PK11_Sign(ss->ssl3.channelID, &signature_item, &digest_item); | |
11947 if (rv != SECSuccess) | |
11948 goto loser; | |
11949 | |
11950 rv = ssl3_AppendHandshake(ss, pub_bytes, CHANNEL_ID_PUBLIC_KEY_LENGTH); | |
11951 if (rv != SECSuccess) | |
11952 goto loser; | |
11953 rv = ssl3_AppendHandshake(ss, signature, sizeof(signature)); | |
11954 | |
11955 loser: | |
11956 if (spki) | |
11957 SECITEM_FreeItem(spki, PR_TRUE); | |
11958 if (ss->ssl3.channelID) { | |
11959 SECKEY_DestroyPrivateKey(ss->ssl3.channelID); | |
11960 ss->ssl3.channelID = NULL; | |
11961 } | |
11962 if (ss->ssl3.channelIDPub) { | |
11963 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub); | |
11964 ss->ssl3.channelIDPub = NULL; | |
11965 } | |
11966 | |
11967 return rv; | |
11968 } | |
11969 | |
11970 /* ssl3_RestartHandshakeAfterChannelIDReq is called to restart a handshake | |
11971 * after a ChannelID callback returned SECWouldBlock. At this point we have | |
11972 * processed the server's ServerHello but not yet any further messages. We will | |
11973 * always get a message from the server after a ServerHello so either they are | |
11974 * waiting in the buffer or we'll get network I/O. */ | |
11975 SECStatus | |
11976 ssl3_RestartHandshakeAfterChannelIDReq(sslSocket *ss, | |
11977 SECKEYPublicKey *channelIDPub, | |
11978 SECKEYPrivateKey *channelID) | |
11979 { | |
11980 if (ss->handshake == 0) { | |
11981 SECKEY_DestroyPublicKey(channelIDPub); | |
11982 SECKEY_DestroyPrivateKey(channelID); | |
11983 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
11984 return SECFailure; | |
11985 } | |
11986 | |
11987 if (channelIDPub == NULL || | |
11988 channelID == NULL) { | |
11989 if (channelIDPub) | |
11990 SECKEY_DestroyPublicKey(channelIDPub); | |
11991 if (channelID) | |
11992 SECKEY_DestroyPrivateKey(channelID); | |
11993 PORT_SetError(PR_INVALID_ARGUMENT_ERROR); | |
11994 return SECFailure; | |
11995 } | |
11996 | |
11997 if (ss->ssl3.channelID) | |
11998 SECKEY_DestroyPrivateKey(ss->ssl3.channelID); | |
11999 if (ss->ssl3.channelIDPub) | |
12000 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub); | |
12001 | |
12002 ss->handshake = ssl_GatherRecord1stHandshake; | |
12003 ss->ssl3.channelID = channelID; | |
12004 ss->ssl3.channelIDPub = channelIDPub; | |
12005 | |
12006 return SECSuccess; | |
12007 } | |
12008 | |
12009 /* called from ssl3_SendClientSecondRound | |
12010 * ssl3_HandleClientHello | |
12011 * ssl3_HandleFinished | |
12012 */ | |
12013 static SECStatus | |
12014 ssl3_SendFinished(sslSocket *ss, PRInt32 flags) | |
12015 { | |
12016 ssl3CipherSpec *cwSpec; | |
12017 PRBool isTLS; | |
12018 PRBool isServer = ss->sec.isServer; | |
12019 SECStatus rv; | |
12020 SSL3Sender sender = isServer ? sender_server : sender_client; | |
12021 SSL3Hashes hashes; | |
12022 TLSFinished tlsFinished; | |
12023 | |
12024 SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd)); | |
12025 | |
12026 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); | |
12027 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
12028 | |
12029 ssl_GetSpecReadLock(ss); | |
12030 cwSpec = ss->ssl3.cwSpec; | |
12031 isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
12032 rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender); | |
12033 if (isTLS && rv == SECSuccess) { | |
12034 rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished); | |
12035 } | |
12036 ssl_ReleaseSpecReadLock(ss); | |
12037 if (rv != SECSuccess) { | |
12038 goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */ | |
12039 } | |
12040 | |
12041 if (isTLS) { | |
12042 if (isServer) | |
12043 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; | |
12044 else | |
12045 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; | |
12046 ss->ssl3.hs.finishedBytes = sizeof tlsFinished; | |
12047 rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished); | |
12048 if (rv != SECSuccess) | |
12049 goto fail; /* err set by AppendHandshake. */ | |
12050 rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished); | |
12051 if (rv != SECSuccess) | |
12052 goto fail; /* err set by AppendHandshake. */ | |
12053 } else { | |
12054 if (isServer) | |
12055 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s; | |
12056 else | |
12057 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s; | |
12058 PORT_Assert(hashes.len == sizeof hashes.u.s); | |
12059 ss->ssl3.hs.finishedBytes = sizeof hashes.u.s; | |
12060 rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s); | |
12061 if (rv != SECSuccess) | |
12062 goto fail; /* err set by AppendHandshake. */ | |
12063 rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s); | |
12064 if (rv != SECSuccess) | |
12065 goto fail; /* err set by AppendHandshake. */ | |
12066 } | |
12067 rv = ssl3_FlushHandshake(ss, flags); | |
12068 if (rv != SECSuccess) { | |
12069 goto fail; /* error code set by ssl3_FlushHandshake */ | |
12070 } | |
12071 | |
12072 ssl3_RecordKeyLog(ss); | |
12073 | |
12074 return SECSuccess; | |
12075 | |
12076 fail: | |
12077 return rv; | |
12078 } | |
12079 | |
12080 /* wrap the master secret, and put it into the SID. | |
12081 * Caller holds the Spec read lock. | |
12082 */ | |
12083 SECStatus | |
12084 ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid, | |
12085 ssl3CipherSpec *spec, SSL3KEAType effectiveExchKey
Type) | |
12086 { | |
12087 PK11SymKey *wrappingKey = NULL; | |
12088 PK11SlotInfo *symKeySlot; | |
12089 void *pwArg = ss->pkcs11PinArg; | |
12090 SECStatus rv = SECFailure; | |
12091 PRBool isServer = ss->sec.isServer; | |
12092 CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM; | |
12093 symKeySlot = PK11_GetSlotFromKey(spec->master_secret); | |
12094 if (!isServer) { | |
12095 int wrapKeyIndex; | |
12096 int incarnation; | |
12097 | |
12098 /* these next few functions are mere accessors and don't fail. */ | |
12099 sid->u.ssl3.masterWrapIndex = wrapKeyIndex = | |
12100 PK11_GetCurrentWrapIndex(symKeySlot); | |
12101 PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */ | |
12102 | |
12103 sid->u.ssl3.masterWrapSeries = incarnation = | |
12104 PK11_GetSlotSeries(symKeySlot); | |
12105 sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot); | |
12106 sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot); | |
12107 sid->u.ssl3.masterValid = PR_TRUE; | |
12108 /* Get the default wrapping key, for wrapping the master secret before | |
12109 * placing it in the SID cache entry. */ | |
12110 wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex, | |
12111 CKM_INVALID_MECHANISM, incarnation, | |
12112 pwArg); | |
12113 if (wrappingKey) { | |
12114 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ | |
12115 } else { | |
12116 int keyLength; | |
12117 /* if the wrappingKey doesn't exist, attempt to create it. | |
12118 * Note: we intentionally ignore errors here. If we cannot | |
12119 * generate a wrapping key, it is not fatal to this SSL connection, | |
12120 * but we will not be able to restart this session. | |
12121 */ | |
12122 mechanism = PK11_GetBestWrapMechanism(symKeySlot); | |
12123 keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism); | |
12124 /* Zero length means fixed key length algorithm, or error. | |
12125 * It's ambiguous. | |
12126 */ | |
12127 wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL, | |
12128 keyLength, pwArg); | |
12129 if (wrappingKey) { | |
12130 PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey); | |
12131 } | |
12132 } | |
12133 } else { | |
12134 /* server socket using session cache. */ | |
12135 mechanism = PK11_GetBestWrapMechanism(symKeySlot); | |
12136 if (mechanism != CKM_INVALID_MECHANISM) { | |
12137 wrappingKey = | |
12138 getWrappingKey(ss, symKeySlot, effectiveExchKeyType, | |
12139 mechanism, pwArg); | |
12140 if (wrappingKey) { | |
12141 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ | |
12142 } | |
12143 } | |
12144 } | |
12145 | |
12146 sid->u.ssl3.masterWrapMech = mechanism; | |
12147 PK11_FreeSlot(symKeySlot); | |
12148 | |
12149 if (wrappingKey) { | |
12150 SECItem wmsItem; | |
12151 | |
12152 wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret; | |
12153 wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret; | |
12154 rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey, | |
12155 spec->master_secret, &wmsItem); | |
12156 /* rv is examined below. */ | |
12157 sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len; | |
12158 PK11_FreeSymKey(wrappingKey); | |
12159 } | |
12160 return rv; | |
12161 } | |
12162 | |
12163 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered | |
12164 * a complete ssl3 Finished message from the peer. | |
12165 * Caller must hold Handshake and RecvBuf locks. | |
12166 */ | |
12167 static SECStatus | |
12168 ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length, | |
12169 const SSL3Hashes *hashes) | |
12170 { | |
12171 sslSessionID *sid = ss->sec.ci.sid; | |
12172 SECStatus rv = SECSuccess; | |
12173 PRBool isServer = ss->sec.isServer; | |
12174 PRBool isTLS; | |
12175 SSL3KEAType effectiveExchKeyType; | |
12176 | |
12177 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
12178 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
12179 | |
12180 SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake", | |
12181 SSL_GETPID(), ss->fd)); | |
12182 | |
12183 if (ss->ssl3.hs.ws != wait_finished) { | |
12184 SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
12185 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED); | |
12186 return SECFailure; | |
12187 } | |
12188 | |
12189 if (!hashes) { | |
12190 PORT_Assert(0); | |
12191 SSL3_SendAlert(ss, alert_fatal, internal_error); | |
12192 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
12193 return SECFailure; | |
12194 } | |
12195 | |
12196 isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0); | |
12197 if (isTLS) { | |
12198 TLSFinished tlsFinished; | |
12199 | |
12200 if (length != sizeof tlsFinished) { | |
12201 (void)SSL3_SendAlert(ss, alert_fatal, decode_error); | |
12202 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); | |
12203 return SECFailure; | |
12204 } | |
12205 rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer, | |
12206 hashes, &tlsFinished); | |
12207 if (!isServer) | |
12208 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; | |
12209 else | |
12210 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; | |
12211 ss->ssl3.hs.finishedBytes = sizeof tlsFinished; | |
12212 if (rv != SECSuccess || | |
12213 0 != NSS_SecureMemcmp(&tlsFinished, b, length)) { | |
12214 (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error); | |
12215 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); | |
12216 return SECFailure; | |
12217 } | |
12218 } else { | |
12219 if (length != sizeof(SSL3Finished)) { | |
12220 (void)ssl3_IllegalParameter(ss); | |
12221 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); | |
12222 return SECFailure; | |
12223 } | |
12224 | |
12225 if (!isServer) | |
12226 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s; | |
12227 else | |
12228 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s; | |
12229 PORT_Assert(hashes->len == sizeof hashes->u.s); | |
12230 ss->ssl3.hs.finishedBytes = sizeof hashes->u.s; | |
12231 if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) { | |
12232 (void)ssl3_HandshakeFailure(ss); | |
12233 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); | |
12234 return SECFailure; | |
12235 } | |
12236 } | |
12237 | |
12238 ssl_GetXmitBufLock(ss); /*************************************/ | |
12239 | |
12240 if ((isServer && !ss->ssl3.hs.isResuming) || | |
12241 (!isServer && ss->ssl3.hs.isResuming)) { | |
12242 PRInt32 flags = 0; | |
12243 | |
12244 /* Send a NewSessionTicket message if the client sent us | |
12245 * either an empty session ticket, or one that did not verify. | |
12246 * (Note that if either of these conditions was met, then the | |
12247 * server has sent a SessionTicket extension in the | |
12248 * ServerHello message.) | |
12249 */ | |
12250 if (isServer && !ss->ssl3.hs.isResuming && | |
12251 ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && | |
12252 ssl3_KEAAllowsSessionTicket(ss->ssl3.hs.suite_def->key_exchange_alg)
) { | |
12253 /* RFC 5077 Section 3.3: "In the case of a full handshake, the | |
12254 * server MUST verify the client's Finished message before sending | |
12255 * the ticket." Presumably, this also means that the client's | |
12256 * certificate, if any, must be verified beforehand too. | |
12257 */ | |
12258 rv = ssl3_SendNewSessionTicket(ss); | |
12259 if (rv != SECSuccess) { | |
12260 goto xmit_loser; | |
12261 } | |
12262 } | |
12263 | |
12264 rv = ssl3_SendChangeCipherSpecs(ss); | |
12265 if (rv != SECSuccess) { | |
12266 goto xmit_loser; /* err is set. */ | |
12267 } | |
12268 /* If this thread is in SSL_SecureSend (trying to write some data) | |
12269 ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the | |
12270 ** last two handshake messages (change cipher spec and finished) | |
12271 ** will be sent in the same send/write call as the application data. | |
12272 */ | |
12273 if (ss->writerThread == PR_GetCurrentThread()) { | |
12274 flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER; | |
12275 } | |
12276 | |
12277 if (!isServer) { | |
12278 if (!ss->firstHsDone) { | |
12279 rv = ssl3_SendNextProto(ss); | |
12280 if (rv != SECSuccess) { | |
12281 goto xmit_loser; /* err code was set. */ | |
12282 } | |
12283 } | |
12284 rv = ssl3_SendChannelIDEncryptedExtensions(ss); | |
12285 if (rv != SECSuccess) | |
12286 goto xmit_loser; /* err code was set. */ | |
12287 } | |
12288 | |
12289 if (IS_DTLS(ss)) { | |
12290 flags |= ssl_SEND_FLAG_NO_RETRANSMIT; | |
12291 } | |
12292 | |
12293 rv = ssl3_SendFinished(ss, flags); | |
12294 if (rv != SECSuccess) { | |
12295 goto xmit_loser; /* err is set. */ | |
12296 } | |
12297 } | |
12298 | |
12299 xmit_loser: | |
12300 ssl_ReleaseXmitBufLock(ss); /*************************************/ | |
12301 if (rv != SECSuccess) { | |
12302 return rv; | |
12303 } | |
12304 | |
12305 if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa || | |
12306 ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) { | |
12307 effectiveExchKeyType = kt_rsa; | |
12308 } else { | |
12309 effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; | |
12310 } | |
12311 | |
12312 if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) { | |
12313 /* fill in the sid */ | |
12314 sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite; | |
12315 sid->u.ssl3.compression = ss->ssl3.hs.compression; | |
12316 sid->u.ssl3.policy = ss->ssl3.policy; | |
12317 #ifndef NSS_DISABLE_ECC | |
12318 sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves; | |
12319 #endif | |
12320 sid->u.ssl3.exchKeyType = effectiveExchKeyType; | |
12321 sid->version = ss->version; | |
12322 sid->authAlgorithm = ss->sec.authAlgorithm; | |
12323 sid->authKeyBits = ss->sec.authKeyBits; | |
12324 sid->keaType = ss->sec.keaType; | |
12325 sid->keaKeyBits = ss->sec.keaKeyBits; | |
12326 sid->lastAccessTime = sid->creationTime = ssl_Time(); | |
12327 sid->expirationTime = sid->creationTime + ssl3_sid_timeout; | |
12328 sid->localCert = CERT_DupCertificate(ss->sec.localCert); | |
12329 | |
12330 ssl_GetSpecReadLock(ss); /*************************************/ | |
12331 | |
12332 /* Copy the master secret (wrapped or unwrapped) into the sid */ | |
12333 if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) { | |
12334 sid->u.ssl3.keys.wrapped_master_secret_len = | |
12335 ss->ssl3.crSpec->msItem.len; | |
12336 memcpy(sid->u.ssl3.keys.wrapped_master_secret, | |
12337 ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len); | |
12338 sid->u.ssl3.masterValid = PR_TRUE; | |
12339 sid->u.ssl3.keys.msIsWrapped = PR_FALSE; | |
12340 rv = SECSuccess; | |
12341 } else { | |
12342 rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid, | |
12343 ss->ssl3.crSpec, | |
12344 effectiveExchKeyType); | |
12345 sid->u.ssl3.keys.msIsWrapped = PR_TRUE; | |
12346 } | |
12347 ssl_ReleaseSpecReadLock(ss); /*************************************/ | |
12348 | |
12349 /* If the wrap failed, we don't cache the sid. | |
12350 * The connection continues normally however. | |
12351 */ | |
12352 ss->ssl3.hs.cacheSID = rv == SECSuccess; | |
12353 } | |
12354 | |
12355 if (ss->ssl3.hs.authCertificatePending) { | |
12356 if (ss->ssl3.hs.restartTarget) { | |
12357 PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget"); | |
12358 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
12359 return SECFailure; | |
12360 } | |
12361 | |
12362 ss->ssl3.hs.restartTarget = ssl3_FinishHandshake; | |
12363 return SECWouldBlock; | |
12364 } | |
12365 | |
12366 rv = ssl3_FinishHandshake(ss); | |
12367 return rv; | |
12368 } | |
12369 | |
12370 /* The return type is SECStatus instead of void because this function needs | |
12371 * to have type sslRestartTarget. | |
12372 */ | |
12373 SECStatus | |
12374 ssl3_FinishHandshake(sslSocket *ss) | |
12375 { | |
12376 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
12377 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
12378 PORT_Assert(ss->ssl3.hs.restartTarget == NULL); | |
12379 | |
12380 /* The first handshake is now completed. */ | |
12381 ss->handshake = NULL; | |
12382 | |
12383 /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid | |
12384 * until it has verified the server's Finished message." When the server | |
12385 * sends a NewSessionTicket in a resumption handshake, we must wait until | |
12386 * the handshake is finished (we have verified the server's Finished | |
12387 * AND the server's certificate) before we update the ticket in the sid. | |
12388 * | |
12389 * This must be done before we call (*ss->sec.cache)(ss->sec.ci.sid) | |
12390 * because CacheSID requires the session ticket to already be set, and also | |
12391 * because of the lazy lock creation scheme used by CacheSID and | |
12392 * ssl3_SetSIDSessionTicket. | |
12393 */ | |
12394 if (ss->ssl3.hs.receivedNewSessionTicket) { | |
12395 PORT_Assert(!ss->sec.isServer); | |
12396 ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ss->ssl3.hs.newSessionTicket); | |
12397 /* The sid took over the ticket data */ | |
12398 PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); | |
12399 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; | |
12400 } | |
12401 | |
12402 if (ss->ssl3.hs.cacheSID && ss->sec.isServer) { | |
12403 PORT_Assert(ss->sec.ci.sid->cached == never_cached); | |
12404 (*ss->sec.cache)(ss->sec.ci.sid); | |
12405 ss->ssl3.hs.cacheSID = PR_FALSE; | |
12406 } | |
12407 | |
12408 ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */ | |
12409 ss->ssl3.hs.ws = idle_handshake; | |
12410 | |
12411 ssl_FinishHandshake(ss); | |
12412 | |
12413 return SECSuccess; | |
12414 } | |
12415 | |
12416 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3 | |
12417 * hanshake message. | |
12418 * Caller must hold Handshake and RecvBuf locks. | |
12419 */ | |
12420 SECStatus | |
12421 ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length) | |
12422 { | |
12423 SECStatus rv = SECSuccess; | |
12424 SSL3HandshakeType type = ss->ssl3.hs.msg_type; | |
12425 SSL3Hashes hashes; /* computed hashes are put here. */ | |
12426 SSL3Hashes *hashesPtr = NULL; /* Set when hashes are computed */ | |
12427 PRUint8 hdr[4]; | |
12428 PRUint8 dtlsData[8]; | |
12429 PRBool computeHashes = PR_FALSE; | |
12430 | |
12431 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
12432 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
12433 /* | |
12434 * We have to compute the hashes before we update them with the | |
12435 * current message. | |
12436 */ | |
12437 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { | |
12438 if (((type == finished) && (ss->ssl3.hs.ws == wait_finished)) || | |
12439 ((type == certificate_verify) && | |
12440 (ss->ssl3.hs.ws == wait_cert_verify))) { | |
12441 computeHashes = PR_TRUE; | |
12442 } | |
12443 } else { | |
12444 if (type == certificate_verify) { | |
12445 computeHashes = | |
12446 TLS13_IN_HS_STATE(ss, wait_cert_verify); | |
12447 } else if (type == finished) { | |
12448 computeHashes = | |
12449 TLS13_IN_HS_STATE(ss, wait_cert_request, wait_finished); | |
12450 } | |
12451 } | |
12452 | |
12453 ssl_GetSpecReadLock(ss); /************************************/ | |
12454 if (computeHashes) { | |
12455 SSL3Sender sender = (SSL3Sender)0; | |
12456 ssl3CipherSpec *rSpec = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 ? ss-
>ssl3.crSpec | |
12457 : ss-
>ssl3.prSpec; | |
12458 | |
12459 if (type == finished) { | |
12460 sender = ss->sec.isServer ? sender_client : sender_server; | |
12461 rSpec = ss->ssl3.crSpec; | |
12462 } | |
12463 rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender); | |
12464 if (rv == SECSuccess) { | |
12465 hashesPtr = &hashes; | |
12466 } | |
12467 } | |
12468 ssl_ReleaseSpecReadLock(ss); /************************************/ | |
12469 if (rv != SECSuccess) { | |
12470 return rv; /* error code was set by ssl3_ComputeHandshakeHashes*/ | |
12471 } | |
12472 SSL_TRC(30, ("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(), | |
12473 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type))); | |
12474 | |
12475 hdr[0] = (PRUint8)ss->ssl3.hs.msg_type; | |
12476 hdr[1] = (PRUint8)(length >> 16); | |
12477 hdr[2] = (PRUint8)(length >> 8); | |
12478 hdr[3] = (PRUint8)(length); | |
12479 | |
12480 /* Start new handshake hashes when we start a new handshake */ | |
12481 if (ss->ssl3.hs.msg_type == client_hello) { | |
12482 rv = ssl3_RestartHandshakeHashes(ss); | |
12483 if (rv != SECSuccess) { | |
12484 return rv; | |
12485 } | |
12486 } | |
12487 /* We should not include hello_request and hello_verify_request messages | |
12488 * in the handshake hashes */ | |
12489 if ((ss->ssl3.hs.msg_type != hello_request) && | |
12490 (ss->ssl3.hs.msg_type != hello_verify_request)) { | |
12491 rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char *)hdr, 4); | |
12492 if (rv != SECSuccess) | |
12493 return rv; /* err code already set. */ | |
12494 | |
12495 /* Extra data to simulate a complete DTLS handshake fragment */ | |
12496 if (IS_DTLS(ss)) { | |
12497 /* Sequence number */ | |
12498 dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq); | |
12499 dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq); | |
12500 | |
12501 /* Fragment offset */ | |
12502 dtlsData[2] = 0; | |
12503 dtlsData[3] = 0; | |
12504 dtlsData[4] = 0; | |
12505 | |
12506 /* Fragment length */ | |
12507 dtlsData[5] = (PRUint8)(length >> 16); | |
12508 dtlsData[6] = (PRUint8)(length >> 8); | |
12509 dtlsData[7] = (PRUint8)(length); | |
12510 | |
12511 rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char *)dtlsData, | |
12512 sizeof(dtlsData)); | |
12513 if (rv != SECSuccess) | |
12514 return rv; /* err code already set. */ | |
12515 } | |
12516 | |
12517 /* The message body */ | |
12518 rv = ssl3_UpdateHandshakeHashes(ss, b, length); | |
12519 if (rv != SECSuccess) | |
12520 return rv; /* err code already set. */ | |
12521 } | |
12522 | |
12523 PORT_SetError(0); /* each message starts with no error. */ | |
12524 | |
12525 if (ss->ssl3.hs.ws == wait_certificate_status && | |
12526 ss->ssl3.hs.msg_type != certificate_status) { | |
12527 /* If we negotiated the certificate_status extension then we deferred | |
12528 * certificate validation until we get the CertificateStatus messsage. | |
12529 * But the CertificateStatus message is optional. If the server did | |
12530 * not send it then we need to validate the certificate now. If the | |
12531 * server does send the CertificateStatus message then we will | |
12532 * authenticate the certificate in ssl3_HandleCertificateStatus. | |
12533 */ | |
12534 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ | |
12535 PORT_Assert(rv != SECWouldBlock); | |
12536 if (rv != SECSuccess) { | |
12537 return rv; | |
12538 } | |
12539 } | |
12540 | |
12541 switch (ss->ssl3.hs.msg_type) { | |
12542 case client_hello: | |
12543 if (!ss->sec.isServer) { | |
12544 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
12545 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO); | |
12546 return SECFailure; | |
12547 } | |
12548 rv = ssl3_HandleClientHello(ss, b, length); | |
12549 break; | |
12550 case server_hello: | |
12551 if (ss->sec.isServer) { | |
12552 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
12553 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO); | |
12554 return SECFailure; | |
12555 } | |
12556 rv = ssl3_HandleServerHello(ss, b, length); | |
12557 break; | |
12558 default: | |
12559 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { | |
12560 rv = ssl3_HandlePostHelloHandshakeMessage(ss, b, length, hashesP
tr); | |
12561 } else { | |
12562 rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length, | |
12563 hashesPtr); | |
12564 } | |
12565 break; | |
12566 } | |
12567 | |
12568 if (IS_DTLS(ss) && (rv != SECFailure)) { | |
12569 /* Increment the expected sequence number */ | |
12570 ss->ssl3.hs.recvMessageSeq++; | |
12571 } | |
12572 return rv; | |
12573 } | |
12574 | |
12575 static SECStatus | |
12576 ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, SSL3Opaque *b, | |
12577 PRUint32 length, SSL3Hashes *hashesPtr) | |
12578 { | |
12579 SECStatus rv; | |
12580 PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3); | |
12581 | |
12582 switch (ss->ssl3.hs.msg_type) { | |
12583 case hello_request: | |
12584 if (length != 0) { | |
12585 (void)ssl3_DecodeError(ss); | |
12586 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST); | |
12587 return SECFailure; | |
12588 } | |
12589 if (ss->sec.isServer) { | |
12590 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
12591 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); | |
12592 return SECFailure; | |
12593 } | |
12594 rv = ssl3_HandleHelloRequest(ss); | |
12595 break; | |
12596 case hello_verify_request: | |
12597 if (!IS_DTLS(ss) || ss->sec.isServer) { | |
12598 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
12599 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST); | |
12600 return SECFailure; | |
12601 } | |
12602 rv = dtls_HandleHelloVerifyRequest(ss, b, length); | |
12603 break; | |
12604 case certificate: | |
12605 rv = ssl3_HandleCertificate(ss, b, length); | |
12606 break; | |
12607 case certificate_status: | |
12608 rv = ssl3_HandleCertificateStatus(ss, b, length); | |
12609 break; | |
12610 case server_key_exchange: | |
12611 if (ss->sec.isServer) { | |
12612 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
12613 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH); | |
12614 return SECFailure; | |
12615 } | |
12616 rv = ssl3_HandleServerKeyExchange(ss, b, length); | |
12617 break; | |
12618 case certificate_request: | |
12619 if (ss->sec.isServer) { | |
12620 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
12621 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST); | |
12622 return SECFailure; | |
12623 } | |
12624 rv = ssl3_HandleCertificateRequest(ss, b, length); | |
12625 break; | |
12626 case server_hello_done: | |
12627 if (length != 0) { | |
12628 (void)ssl3_DecodeError(ss); | |
12629 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE); | |
12630 return SECFailure; | |
12631 } | |
12632 if (ss->sec.isServer) { | |
12633 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
12634 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); | |
12635 return SECFailure; | |
12636 } | |
12637 rv = ssl3_HandleServerHelloDone(ss); | |
12638 break; | |
12639 case certificate_verify: | |
12640 if (!ss->sec.isServer) { | |
12641 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
12642 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY); | |
12643 return SECFailure; | |
12644 } | |
12645 rv = ssl3_HandleCertificateVerify(ss, b, length, hashesPtr); | |
12646 break; | |
12647 case client_key_exchange: | |
12648 if (!ss->sec.isServer) { | |
12649 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
12650 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); | |
12651 return SECFailure; | |
12652 } | |
12653 rv = ssl3_HandleClientKeyExchange(ss, b, length); | |
12654 break; | |
12655 case new_session_ticket: | |
12656 if (ss->sec.isServer) { | |
12657 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
12658 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); | |
12659 return SECFailure; | |
12660 } | |
12661 rv = ssl3_HandleNewSessionTicket(ss, b, length); | |
12662 break; | |
12663 case finished: | |
12664 rv = ssl3_HandleFinished(ss, b, length, hashesPtr); | |
12665 break; | |
12666 default: | |
12667 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
12668 PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE); | |
12669 rv = SECFailure; | |
12670 } | |
12671 | |
12672 return rv; | |
12673 } | |
12674 | |
12675 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record. | |
12676 * origBuf is the decrypted ssl record content. | |
12677 * Caller must hold the handshake and RecvBuf locks. | |
12678 */ | |
12679 static SECStatus | |
12680 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) | |
12681 { | |
12682 /* | |
12683 * There may be a partial handshake message already in the handshake | |
12684 * state. The incoming buffer may contain another portion, or a | |
12685 * complete message or several messages followed by another portion. | |
12686 * | |
12687 * Each message is made contiguous before being passed to the actual | |
12688 * message parser. | |
12689 */ | |
12690 sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer p
ointer */ | |
12691 SECStatus rv; | |
12692 | |
12693 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
12694 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
12695 | |
12696 if (buf->buf == NULL) { | |
12697 *buf = *origBuf; | |
12698 } | |
12699 while (buf->len > 0) { | |
12700 if (ss->ssl3.hs.header_bytes < 4) { | |
12701 PRUint8 t; | |
12702 t = *(buf->buf++); | |
12703 buf->len--; | |
12704 if (ss->ssl3.hs.header_bytes++ == 0) | |
12705 ss->ssl3.hs.msg_type = (SSL3HandshakeType)t; | |
12706 else | |
12707 ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t; | |
12708 if (ss->ssl3.hs.header_bytes < 4) | |
12709 continue; | |
12710 | |
12711 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */ | |
12712 if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) { | |
12713 (void)ssl3_DecodeError(ss); | |
12714 PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE); | |
12715 return SECFailure; | |
12716 } | |
12717 #undef MAX_HANDSHAKE_MSG_LEN | |
12718 | |
12719 /* If msg_len is zero, be sure we fall through, | |
12720 ** even if buf->len is zero. | |
12721 */ | |
12722 if (ss->ssl3.hs.msg_len > 0) | |
12723 continue; | |
12724 } | |
12725 | |
12726 /* | |
12727 * Header has been gathered and there is at least one byte of new | |
12728 * data available for this message. If it can be done right out | |
12729 * of the original buffer, then use it from there. | |
12730 */ | |
12731 if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) { | |
12732 /* handle it from input buffer */ | |
12733 rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len); | |
12734 if (rv == SECFailure) { | |
12735 /* This test wants to fall through on either | |
12736 * SECSuccess or SECWouldBlock. | |
12737 * ssl3_HandleHandshakeMessage MUST set the error code. | |
12738 */ | |
12739 return rv; | |
12740 } | |
12741 buf->buf += ss->ssl3.hs.msg_len; | |
12742 buf->len -= ss->ssl3.hs.msg_len; | |
12743 ss->ssl3.hs.msg_len = 0; | |
12744 ss->ssl3.hs.header_bytes = 0; | |
12745 if (rv != SECSuccess) { /* return if SECWouldBlock. */ | |
12746 return rv; | |
12747 } | |
12748 } else { | |
12749 /* must be copied to msg_body and dealt with from there */ | |
12750 unsigned int bytes; | |
12751 | |
12752 PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len); | |
12753 bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.
len); | |
12754 | |
12755 /* Grow the buffer if needed */ | |
12756 rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len); | |
12757 if (rv != SECSuccess) { | |
12758 /* sslBuffer_Grow has set a memory error code. */ | |
12759 return SECFailure; | |
12760 } | |
12761 | |
12762 PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len, | |
12763 buf->buf, bytes); | |
12764 ss->ssl3.hs.msg_body.len += bytes; | |
12765 buf->buf += bytes; | |
12766 buf->len -= bytes; | |
12767 | |
12768 PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len); | |
12769 | |
12770 /* if we have a whole message, do it */ | |
12771 if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) { | |
12772 rv = ssl3_HandleHandshakeMessage( | |
12773 ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len); | |
12774 if (rv == SECFailure) { | |
12775 /* This test wants to fall through on either | |
12776 * SECSuccess or SECWouldBlock. | |
12777 * ssl3_HandleHandshakeMessage MUST set error code. | |
12778 */ | |
12779 return rv; | |
12780 } | |
12781 ss->ssl3.hs.msg_body.len = 0; | |
12782 ss->ssl3.hs.msg_len = 0; | |
12783 ss->ssl3.hs.header_bytes = 0; | |
12784 if (rv != SECSuccess) { /* return if SECWouldBlock. */ | |
12785 return rv; | |
12786 } | |
12787 } else { | |
12788 PORT_Assert(buf->len == 0); | |
12789 break; | |
12790 } | |
12791 } | |
12792 } /* end loop */ | |
12793 | |
12794 origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */ | |
12795 buf->buf = NULL; /* not a leak. */ | |
12796 return SECSuccess; | |
12797 } | |
12798 | |
12799 /* These macros return the given value with the MSB copied to all the other | |
12800 * bits. They use the fact that arithmetic shift shifts-in the sign bit. | |
12801 * However, this is not ensured by the C standard so you may need to replace | |
12802 * them with something else for odd compilers. */ | |
12803 #define DUPLICATE_MSB_TO_ALL(x) ((unsigned)((int)(x) >> (sizeof(int) * 8 - 1))) | |
12804 #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x))) | |
12805 | |
12806 /* SECStatusToMask returns, in constant time, a mask value of all ones if | |
12807 * rv == SECSuccess. Otherwise it returns zero. */ | |
12808 static unsigned int | |
12809 SECStatusToMask(SECStatus rv) | |
12810 { | |
12811 unsigned int good; | |
12812 /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results | |
12813 * in the MSB being set to one iff it was zero before. */ | |
12814 good = rv ^ SECSuccess; | |
12815 good--; | |
12816 return DUPLICATE_MSB_TO_ALL(good); | |
12817 } | |
12818 | |
12819 /* ssl_ConstantTimeGE returns 0xff if a>=b and 0x00 otherwise. */ | |
12820 static unsigned char | |
12821 ssl_ConstantTimeGE(unsigned int a, unsigned int b) | |
12822 { | |
12823 a -= b; | |
12824 return DUPLICATE_MSB_TO_ALL(~a); | |
12825 } | |
12826 | |
12827 /* ssl_ConstantTimeEQ8 returns 0xff if a==b and 0x00 otherwise. */ | |
12828 static unsigned char | |
12829 ssl_ConstantTimeEQ8(unsigned char a, unsigned char b) | |
12830 { | |
12831 unsigned int c = a ^ b; | |
12832 c--; | |
12833 return DUPLICATE_MSB_TO_ALL_8(c); | |
12834 } | |
12835 | |
12836 static SECStatus | |
12837 ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext, | |
12838 unsigned int blockSize, | |
12839 unsigned int macSize) | |
12840 { | |
12841 unsigned int paddingLength, good, t; | |
12842 const unsigned int overhead = 1 /* padding length byte */ + macSize; | |
12843 | |
12844 /* These lengths are all public so we can test them in non-constant | |
12845 * time. */ | |
12846 if (overhead > plaintext->len) { | |
12847 return SECFailure; | |
12848 } | |
12849 | |
12850 paddingLength = plaintext->buf[plaintext->len - 1]; | |
12851 /* SSLv3 padding bytes are random and cannot be checked. */ | |
12852 t = plaintext->len; | |
12853 t -= paddingLength + overhead; | |
12854 /* If len >= paddingLength+overhead then the MSB of t is zero. */ | |
12855 good = DUPLICATE_MSB_TO_ALL(~t); | |
12856 /* SSLv3 requires that the padding is minimal. */ | |
12857 t = blockSize - (paddingLength + 1); | |
12858 good &= DUPLICATE_MSB_TO_ALL(~t); | |
12859 plaintext->len -= good & (paddingLength + 1); | |
12860 return (good & SECSuccess) | (~good & SECFailure); | |
12861 } | |
12862 | |
12863 static SECStatus | |
12864 ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) | |
12865 { | |
12866 unsigned int paddingLength, good, t, toCheck, i; | |
12867 const unsigned int overhead = 1 /* padding length byte */ + macSize; | |
12868 | |
12869 /* These lengths are all public so we can test them in non-constant | |
12870 * time. */ | |
12871 if (overhead > plaintext->len) { | |
12872 return SECFailure; | |
12873 } | |
12874 | |
12875 paddingLength = plaintext->buf[plaintext->len - 1]; | |
12876 t = plaintext->len; | |
12877 t -= paddingLength + overhead; | |
12878 /* If len >= paddingLength+overhead then the MSB of t is zero. */ | |
12879 good = DUPLICATE_MSB_TO_ALL(~t); | |
12880 | |
12881 /* The padding consists of a length byte at the end of the record and then | |
12882 * that many bytes of padding, all with the same value as the length byte. | |
12883 * Thus, with the length byte included, there are paddingLength+1 bytes of | |
12884 * padding. | |
12885 * | |
12886 * We can't check just |paddingLength+1| bytes because that leaks | |
12887 * decrypted information. Therefore we always have to check the maximum | |
12888 * amount of padding possible. (Again, the length of the record is | |
12889 * public information so we can use it.) */ | |
12890 toCheck = 255; /* maximum amount of padding. */ | |
12891 if (toCheck > plaintext->len - 1) { | |
12892 toCheck = plaintext->len - 1; | |
12893 } | |
12894 | |
12895 for (i = 0; i < toCheck; i++) { | |
12896 unsigned int t = paddingLength - i; | |
12897 /* If i <= paddingLength then the MSB of t is zero and mask is | |
12898 * 0xff. Otherwise, mask is 0. */ | |
12899 unsigned char mask = DUPLICATE_MSB_TO_ALL(~t); | |
12900 unsigned char b = plaintext->buf[plaintext->len - 1 - i]; | |
12901 /* The final |paddingLength+1| bytes should all have the value | |
12902 * |paddingLength|. Therefore the XOR should be zero. */ | |
12903 good &= ~(mask & (paddingLength ^ b)); | |
12904 } | |
12905 | |
12906 /* If any of the final |paddingLength+1| bytes had the wrong value, | |
12907 * one or more of the lower eight bits of |good| will be cleared. We | |
12908 * AND the bottom 8 bits together and duplicate the result to all the | |
12909 * bits. */ | |
12910 good &= good >> 4; | |
12911 good &= good >> 2; | |
12912 good &= good >> 1; | |
12913 good <<= sizeof(good) * 8 - 1; | |
12914 good = DUPLICATE_MSB_TO_ALL(good); | |
12915 | |
12916 plaintext->len -= good & (paddingLength + 1); | |
12917 return (good & SECSuccess) | (~good & SECFailure); | |
12918 } | |
12919 | |
12920 /* On entry: | |
12921 * originalLength >= macSize | |
12922 * macSize <= MAX_MAC_LENGTH | |
12923 * plaintext->len >= macSize | |
12924 */ | |
12925 static void | |
12926 ssl_CBCExtractMAC(sslBuffer *plaintext, | |
12927 unsigned int originalLength, | |
12928 SSL3Opaque *out, | |
12929 unsigned int macSize) | |
12930 { | |
12931 unsigned char rotatedMac[MAX_MAC_LENGTH]; | |
12932 /* macEnd is the index of |plaintext->buf| just after the end of the | |
12933 * MAC. */ | |
12934 unsigned macEnd = plaintext->len; | |
12935 unsigned macStart = macEnd - macSize; | |
12936 /* scanStart contains the number of bytes that we can ignore because | |
12937 * the MAC's position can only vary by 255 bytes. */ | |
12938 unsigned scanStart = 0; | |
12939 unsigned i, j, divSpoiler; | |
12940 unsigned char rotateOffset; | |
12941 | |
12942 if (originalLength > macSize + 255 + 1) | |
12943 scanStart = originalLength - (macSize + 255 + 1); | |
12944 | |
12945 /* divSpoiler contains a multiple of macSize that is used to cause the | |
12946 * modulo operation to be constant time. Without this, the time varies | |
12947 * based on the amount of padding when running on Intel chips at least. | |
12948 * | |
12949 * The aim of right-shifting macSize is so that the compiler doesn't | |
12950 * figure out that it can remove divSpoiler as that would require it | |
12951 * to prove that macSize is always even, which I hope is beyond it. */ | |
12952 divSpoiler = macSize >> 1; | |
12953 divSpoiler <<= (sizeof(divSpoiler) - 1) * 8; | |
12954 rotateOffset = (divSpoiler + macStart - scanStart) % macSize; | |
12955 | |
12956 memset(rotatedMac, 0, macSize); | |
12957 for (i = scanStart; i < originalLength;) { | |
12958 for (j = 0; j < macSize && i < originalLength; i++, j++) { | |
12959 unsigned char macStarted = ssl_ConstantTimeGE(i, macStart); | |
12960 unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd); | |
12961 unsigned char b = 0; | |
12962 b = plaintext->buf[i]; | |
12963 rotatedMac[j] |= b & macStarted & ~macEnded; | |
12964 } | |
12965 } | |
12966 | |
12967 /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line | |
12968 * we could line-align |rotatedMac| and rotate in place. */ | |
12969 memset(out, 0, macSize); | |
12970 for (i = 0; i < macSize; i++) { | |
12971 unsigned char offset = | |
12972 (divSpoiler + macSize - rotateOffset + i) % macSize; | |
12973 for (j = 0; j < macSize; j++) { | |
12974 out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset); | |
12975 } | |
12976 } | |
12977 } | |
12978 | |
12979 /* Unprotect an SSL3 record and leave the result in plaintext. | |
12980 * | |
12981 * If SECFailure is returned, we: | |
12982 * 1. Set |*alert| to the alert to be sent. | |
12983 * 2. Call PORT_SetError() with an appropriate code. | |
12984 * | |
12985 * Called by ssl3_HandleRecord. Caller must hold the spec read lock. | |
12986 * Therefore, we MUST not call SSL3_SendAlert(). | |
12987 * | |
12988 */ | |
12989 static SECStatus | |
12990 ssl3_UnprotectRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *plaintext, | |
12991 SSL3AlertDescription *alert) | |
12992 { | |
12993 ssl3CipherSpec *crSpec = ss->ssl3.crSpec; | |
12994 const ssl3BulkCipherDef *cipher_def = crSpec->cipher_def; | |
12995 PRBool isTLS; | |
12996 unsigned int good; | |
12997 unsigned int ivLen = 0; | |
12998 SSL3ContentType rType; | |
12999 unsigned int minLength; | |
13000 unsigned int originalLen = 0; | |
13001 unsigned char header[13]; | |
13002 unsigned int headerLen; | |
13003 SSL3Opaque hash[MAX_MAC_LENGTH]; | |
13004 SSL3Opaque givenHashBuf[MAX_MAC_LENGTH]; | |
13005 SSL3Opaque *givenHash; | |
13006 unsigned int hashBytes = MAX_MAC_LENGTH + 1; | |
13007 SECStatus rv; | |
13008 | |
13009 good = ~0U; | |
13010 minLength = crSpec->mac_size; | |
13011 if (cipher_def->type == type_block) { | |
13012 /* CBC records have a padding length byte at the end. */ | |
13013 minLength++; | |
13014 if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { | |
13015 /* With >= TLS 1.1, CBC records have an explicit IV. */ | |
13016 minLength += cipher_def->iv_size; | |
13017 } | |
13018 } else if (cipher_def->type == type_aead) { | |
13019 minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size; | |
13020 } | |
13021 | |
13022 /* We can perform this test in variable time because the record's total | |
13023 * length and the ciphersuite are both public knowledge. */ | |
13024 if (cText->buf->len < minLength) { | |
13025 goto decrypt_loser; | |
13026 } | |
13027 | |
13028 if (cipher_def->type == type_block && | |
13029 crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { | |
13030 /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states | |
13031 * "The receiver decrypts the entire GenericBlockCipher structure and | |
13032 * then discards the first cipher block corresponding to the IV | |
13033 * component." Instead, we decrypt the first cipher block and then | |
13034 * discard it before decrypting the rest. | |
13035 */ | |
13036 SSL3Opaque iv[MAX_IV_LENGTH]; | |
13037 int decoded; | |
13038 | |
13039 ivLen = cipher_def->iv_size; | |
13040 if (ivLen < 8 || ivLen > sizeof(iv)) { | |
13041 *alert = internal_error; | |
13042 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); | |
13043 return SECFailure; | |
13044 } | |
13045 | |
13046 PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen)); | |
13047 | |
13048 /* The decryption result is garbage, but since we just throw away | |
13049 * the block it doesn't matter. The decryption of the next block | |
13050 * depends only on the ciphertext of the IV block. | |
13051 */ | |
13052 rv = crSpec->decode(crSpec->decodeContext, iv, &decoded, | |
13053 sizeof(iv), cText->buf->buf, ivLen); | |
13054 | |
13055 good &= SECStatusToMask(rv); | |
13056 } | |
13057 | |
13058 PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen, | |
13059 cText->buf->len - ivLen)); | |
13060 | |
13061 isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0); | |
13062 | |
13063 if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) { | |
13064 *alert = record_overflow; | |
13065 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); | |
13066 return SECFailure; | |
13067 } | |
13068 | |
13069 rType = cText->type; | |
13070 if (cipher_def->type == type_aead) { | |
13071 /* XXX For many AEAD ciphers, the plaintext is shorter than the | |
13072 * ciphertext by a fixed byte count, but it is not true in general. | |
13073 * Each AEAD cipher should provide a function that returns the | |
13074 * plaintext length for a given ciphertext. */ | |
13075 unsigned int decryptedLen = | |
13076 cText->buf->len - cipher_def->explicit_nonce_size - | |
13077 cipher_def->tag_size; | |
13078 headerLen = ssl3_BuildRecordPseudoHeader( | |
13079 header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, | |
13080 rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen); | |
13081 PORT_Assert(headerLen <= sizeof(header)); | |
13082 rv = crSpec->aead( | |
13083 ss->sec.isServer ? &crSpec->client : &crSpec->server, | |
13084 PR_TRUE, /* do decrypt */ | |
13085 plaintext->buf, /* out */ | |
13086 (int *)&plaintext->len, /* outlen */ | |
13087 plaintext->space, /* maxout */ | |
13088 cText->buf->buf, /* in */ | |
13089 cText->buf->len, /* inlen */ | |
13090 header, headerLen); | |
13091 if (rv != SECSuccess) { | |
13092 good = 0; | |
13093 } | |
13094 } else { | |
13095 if (cipher_def->type == type_block && | |
13096 ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) { | |
13097 goto decrypt_loser; | |
13098 } | |
13099 | |
13100 /* decrypt from cText buf to plaintext. */ | |
13101 rv = crSpec->decode( | |
13102 crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len, | |
13103 plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen); | |
13104 if (rv != SECSuccess) { | |
13105 goto decrypt_loser; | |
13106 } | |
13107 | |
13108 PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len)); | |
13109 | |
13110 originalLen = plaintext->len; | |
13111 | |
13112 /* If it's a block cipher, check and strip the padding. */ | |
13113 if (cipher_def->type == type_block) { | |
13114 const unsigned int blockSize = cipher_def->block_size; | |
13115 const unsigned int macSize = crSpec->mac_size; | |
13116 | |
13117 if (!isTLS) { | |
13118 good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( | |
13119 plaintext, blockSize, macSize)); | |
13120 } else { | |
13121 good &= SECStatusToMask(ssl_RemoveTLSCBCPadding( | |
13122 plaintext, macSize)); | |
13123 } | |
13124 } | |
13125 | |
13126 /* compute the MAC */ | |
13127 headerLen = ssl3_BuildRecordPseudoHeader( | |
13128 header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, | |
13129 rType, isTLS, cText->version, IS_DTLS(ss), | |
13130 plaintext->len - crSpec->mac_size); | |
13131 PORT_Assert(headerLen <= sizeof(header)); | |
13132 if (cipher_def->type == type_block) { | |
13133 rv = ssl3_ComputeRecordMACConstantTime( | |
13134 crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, | |
13135 plaintext->buf, plaintext->len, originalLen, | |
13136 hash, &hashBytes); | |
13137 | |
13138 ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf, | |
13139 crSpec->mac_size); | |
13140 givenHash = givenHashBuf; | |
13141 | |
13142 /* plaintext->len will always have enough space to remove the MAC | |
13143 * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust | |
13144 * plaintext->len if the result has enough space for the MAC and we | |
13145 * tested the unadjusted size against minLength, above. */ | |
13146 plaintext->len -= crSpec->mac_size; | |
13147 } else { | |
13148 /* This is safe because we checked the minLength above. */ | |
13149 plaintext->len -= crSpec->mac_size; | |
13150 | |
13151 rv = ssl3_ComputeRecordMAC( | |
13152 crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, | |
13153 plaintext->buf, plaintext->len, hash, &hashBytes); | |
13154 | |
13155 /* We can read the MAC directly from the record because its location | |
13156 * is public when a stream cipher is used. */ | |
13157 givenHash = plaintext->buf + plaintext->len; | |
13158 } | |
13159 | |
13160 good &= SECStatusToMask(rv); | |
13161 | |
13162 if (hashBytes != (unsigned)crSpec->mac_size || | |
13163 NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) { | |
13164 /* We're allowed to leak whether or not the MAC check was correct */ | |
13165 good = 0; | |
13166 } | |
13167 } | |
13168 | |
13169 if (good == 0) { | |
13170 decrypt_loser: | |
13171 /* always log mac error, in case attacker can read server logs. */ | |
13172 PORT_SetError(SSL_ERROR_BAD_MAC_READ); | |
13173 *alert = bad_record_mac; | |
13174 return SECFailure; | |
13175 } | |
13176 return SECSuccess; | |
13177 } | |
13178 | |
13179 /* if cText is non-null, then decipher, check MAC, and decompress the | |
13180 * SSL record from cText->buf (typically gs->inbuf) | |
13181 * into databuf (typically gs->buf), and any previous contents of databuf | |
13182 * is lost. Then handle databuf according to its SSL record type, | |
13183 * unless it's an application record. | |
13184 * | |
13185 * If cText is NULL, then the ciphertext has previously been deciphered and | |
13186 * checked, and is already sitting in databuf. It is processed as an SSL | |
13187 * Handshake message. | |
13188 * | |
13189 * DOES NOT process the decrypted/decompressed application data. | |
13190 * On return, databuf contains the decrypted/decompressed record. | |
13191 * | |
13192 * Called from ssl3_GatherCompleteHandshake | |
13193 * ssl3_RestartHandshakeAfterCertReq | |
13194 * | |
13195 * Caller must hold the RecvBufLock. | |
13196 * | |
13197 * This function aquires and releases the SSL3Handshake Lock, holding the | |
13198 * lock around any calls to functions that handle records other than | |
13199 * Application Data records. | |
13200 */ | |
13201 SECStatus | |
13202 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) | |
13203 { | |
13204 SECStatus rv; | |
13205 PRBool isTLS; | |
13206 PRUint64 dtls_seq_num = 0; | |
13207 ssl3CipherSpec *crSpec; | |
13208 SSL3ContentType rType; | |
13209 sslBuffer *plaintext; | |
13210 sslBuffer temp_buf; | |
13211 SSL3AlertDescription alert; | |
13212 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); | |
13213 | |
13214 if (!ss->ssl3.initialized) { | |
13215 ssl_GetSSL3HandshakeLock(ss); | |
13216 rv = ssl3_InitState(ss); | |
13217 ssl_ReleaseSSL3HandshakeLock(ss); | |
13218 if (rv != SECSuccess) { | |
13219 return rv; /* ssl3_InitState has set the error code. */ | |
13220 } | |
13221 } | |
13222 | |
13223 /* check for Token Presence */ | |
13224 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { | |
13225 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); | |
13226 return SECFailure; | |
13227 } | |
13228 | |
13229 /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX(). | |
13230 * This implies that databuf holds a previously deciphered SSL Handshake | |
13231 * message. | |
13232 */ | |
13233 if (cText == NULL) { | |
13234 SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake", | |
13235 SSL_GETPID(), ss->fd)); | |
13236 rType = content_handshake; | |
13237 goto process_it; | |
13238 } | |
13239 | |
13240 ssl_GetSpecReadLock(ss); /******************************************/ | |
13241 crSpec = ss->ssl3.crSpec; | |
13242 isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0); | |
13243 | |
13244 if (IS_DTLS(ss)) { | |
13245 if (!dtls_IsRelevant(ss, crSpec, cText, &dtls_seq_num)) { | |
13246 ssl_ReleaseSpecReadLock(ss); | |
13247 /* Silently drop the packet */ | |
13248 databuf->len = 0; /* Needed to ensure data not left around */ | |
13249 return SECSuccess; | |
13250 } | |
13251 } | |
13252 | |
13253 /* If we will be decompressing the buffer we need to decrypt somewhere | |
13254 * other than into databuf */ | |
13255 if (crSpec->decompressor) { | |
13256 temp_buf.buf = NULL; | |
13257 temp_buf.space = 0; | |
13258 plaintext = &temp_buf; | |
13259 } else { | |
13260 plaintext = databuf; | |
13261 } | |
13262 | |
13263 plaintext->len = 0; /* filled in by Unprotect call below. */ | |
13264 if (plaintext->space < MAX_FRAGMENT_LENGTH) { | |
13265 rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048); | |
13266 if (rv != SECSuccess) { | |
13267 ssl_ReleaseSpecReadLock(ss); | |
13268 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", | |
13269 SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048)); | |
13270 /* sslBuffer_Grow has set a memory error code. */ | |
13271 /* Perhaps we should send an alert. (but we have no memory!) */ | |
13272 return SECFailure; | |
13273 } | |
13274 } | |
13275 | |
13276 /* IMPORTANT: Unprotect functions MUST NOT send alerts | |
13277 * because we still hold the spec read lock. Instead, if they | |
13278 * return SECFailure, they set *alert to the alert to be sent. */ | |
13279 if (crSpec->version < SSL_LIBRARY_VERSION_TLS_1_3 || | |
13280 crSpec->cipher_def->calg == ssl_calg_null) { | |
13281 /* Unencrypted TLS 1.3 records use the pre-TLS 1.3 format. */ | |
13282 rv = ssl3_UnprotectRecord(ss, cText, plaintext, &alert); | |
13283 } else { | |
13284 rv = tls13_UnprotectRecord(ss, cText, plaintext, &alert); | |
13285 } | |
13286 | |
13287 if (rv != SECSuccess) { | |
13288 ssl_ReleaseSpecReadLock(ss); | |
13289 | |
13290 SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd)); | |
13291 | |
13292 if (!IS_DTLS(ss)) { | |
13293 int errCode = PORT_GetError(); | |
13294 SSL3_SendAlert(ss, alert_fatal, alert); | |
13295 /* Reset the error code in case SSL3_SendAlert called | |
13296 * PORT_SetError(). */ | |
13297 PORT_SetError(errCode); | |
13298 return SECFailure; | |
13299 } else { | |
13300 /* Silently drop the packet */ | |
13301 databuf->len = 0; /* Needed to ensure data not left around */ | |
13302 return SECSuccess; | |
13303 } | |
13304 } | |
13305 | |
13306 /* SECSuccess */ | |
13307 if (!IS_DTLS(ss)) { | |
13308 ssl3_BumpSequenceNumber(&crSpec->read_seq_num); | |
13309 } else { | |
13310 dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num); | |
13311 } | |
13312 | |
13313 ssl_ReleaseSpecReadLock(ss); /*****************************************/ | |
13314 | |
13315 /* | |
13316 * The decrypted data is now in plaintext. | |
13317 */ | |
13318 rType = cText->type; /* This must go after decryption because TLS 1.3 | |
13319 * has encrypted content types. */ | |
13320 | |
13321 /* possibly decompress the record. If we aren't using compression then | |
13322 * plaintext == databuf and so the uncompressed data is already in | |
13323 * databuf. */ | |
13324 if (crSpec->decompressor) { | |
13325 if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) { | |
13326 rv = sslBuffer_Grow( | |
13327 databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION); | |
13328 if (rv != SECSuccess) { | |
13329 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", | |
13330 SSL_GETPID(), ss->fd, | |
13331 plaintext->len + | |
13332 SSL3_COMPRESSION_MAX_EXPANSION)); | |
13333 /* sslBuffer_Grow has set a memory error code. */ | |
13334 /* Perhaps we should send an alert. (but we have no memory!) */ | |
13335 PORT_Free(plaintext->buf); | |
13336 return SECFailure; | |
13337 } | |
13338 } | |
13339 | |
13340 rv = crSpec->decompressor(crSpec->decompressContext, | |
13341 databuf->buf, | |
13342 (int *)&databuf->len, | |
13343 databuf->space, | |
13344 plaintext->buf, | |
13345 plaintext->len); | |
13346 | |
13347 if (rv != SECSuccess) { | |
13348 int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE); | |
13349 SSL3_SendAlert(ss, alert_fatal, | |
13350 isTLS ? decompression_failure | |
13351 : bad_record_mac); | |
13352 | |
13353 /* There appears to be a bug with (at least) Apache + OpenSSL where | |
13354 * resumed SSLv3 connections don't actually use compression. See | |
13355 * comments 93-95 of | |
13356 * https://bugzilla.mozilla.org/show_bug.cgi?id=275744 | |
13357 * | |
13358 * So, if we get a decompression error, and the record appears to | |
13359 * be already uncompressed, then we return a more specific error | |
13360 * code to hopefully save somebody some debugging time in the | |
13361 * future. | |
13362 */ | |
13363 if (plaintext->len >= 4) { | |
13364 unsigned int len = ((unsigned int)plaintext->buf[1] << 16) | | |
13365 ((unsigned int)plaintext->buf[2] << 8) | | |
13366 (unsigned int)plaintext->buf[3]; | |
13367 if (len == plaintext->len - 4) { | |
13368 /* This appears to be uncompressed already */ | |
13369 err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD; | |
13370 } | |
13371 } | |
13372 | |
13373 PORT_Free(plaintext->buf); | |
13374 PORT_SetError(err); | |
13375 return SECFailure; | |
13376 } | |
13377 | |
13378 PORT_Free(plaintext->buf); | |
13379 } | |
13380 | |
13381 /* | |
13382 ** Having completed the decompression, check the length again. | |
13383 */ | |
13384 if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) { | |
13385 SSL3_SendAlert(ss, alert_fatal, record_overflow); | |
13386 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); | |
13387 return SECFailure; | |
13388 } | |
13389 | |
13390 /* Application data records are processed by the caller of this | |
13391 ** function, not by this function. | |
13392 */ | |
13393 if (rType == content_application_data) { | |
13394 if (ss->firstHsDone) | |
13395 return SECSuccess; | |
13396 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); | |
13397 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA); | |
13398 return SECFailure; | |
13399 } | |
13400 | |
13401 /* It's a record that must be handled by ssl itself, not the application. | |
13402 */ | |
13403 process_it: | |
13404 /* XXX Get the xmit lock here. Odds are very high that we'll be xmiting | |
13405 * data ang getting the xmit lock here prevents deadlocks. | |
13406 */ | |
13407 ssl_GetSSL3HandshakeLock(ss); | |
13408 | |
13409 /* All the functions called in this switch MUST set error code if | |
13410 ** they return SECFailure or SECWouldBlock. | |
13411 */ | |
13412 switch (rType) { | |
13413 case content_change_cipher_spec: | |
13414 rv = ssl3_HandleChangeCipherSpecs(ss, databuf); | |
13415 break; | |
13416 case content_alert: | |
13417 rv = ssl3_HandleAlert(ss, databuf); | |
13418 break; | |
13419 case content_handshake: | |
13420 if (!IS_DTLS(ss)) { | |
13421 rv = ssl3_HandleHandshake(ss, databuf); | |
13422 } else { | |
13423 rv = dtls_HandleHandshake(ss, databuf); | |
13424 } | |
13425 break; | |
13426 /* | |
13427 case content_application_data is handled before this switch | |
13428 */ | |
13429 default: | |
13430 SSL_DBG(("%d: SSL3[%d]: bogus content type=%d", | |
13431 SSL_GETPID(), ss->fd, cText->type)); | |
13432 /* XXX Send an alert ??? */ | |
13433 PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE); | |
13434 rv = SECFailure; | |
13435 break; | |
13436 } | |
13437 | |
13438 ssl_ReleaseSSL3HandshakeLock(ss); | |
13439 return rv; | |
13440 } | |
13441 | |
13442 /* | |
13443 * Initialization functions | |
13444 */ | |
13445 | |
13446 /* Called from ssl3_InitState, immediately below. */ | |
13447 /* Caller must hold the SpecWriteLock. */ | |
13448 static void | |
13449 ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec) | |
13450 { | |
13451 spec->cipher_def = &bulk_cipher_defs[cipher_null]; | |
13452 PORT_Assert(spec->cipher_def->cipher == cipher_null); | |
13453 spec->mac_def = &mac_defs[mac_null]; | |
13454 PORT_Assert(spec->mac_def->mac == mac_null); | |
13455 spec->encode = Null_Cipher; | |
13456 spec->decode = Null_Cipher; | |
13457 spec->destroy = NULL; | |
13458 spec->compressor = NULL; | |
13459 spec->decompressor = NULL; | |
13460 spec->destroyCompressContext = NULL; | |
13461 spec->destroyDecompressContext = NULL; | |
13462 spec->mac_size = 0; | |
13463 spec->master_secret = NULL; | |
13464 spec->bypassCiphers = PR_FALSE; | |
13465 | |
13466 spec->msItem.data = NULL; | |
13467 spec->msItem.len = 0; | |
13468 | |
13469 spec->client.write_key = NULL; | |
13470 spec->client.write_mac_key = NULL; | |
13471 spec->client.write_mac_context = NULL; | |
13472 | |
13473 spec->server.write_key = NULL; | |
13474 spec->server.write_mac_key = NULL; | |
13475 spec->server.write_mac_context = NULL; | |
13476 | |
13477 spec->write_seq_num.high = 0; | |
13478 spec->write_seq_num.low = 0; | |
13479 | |
13480 spec->read_seq_num.high = 0; | |
13481 spec->read_seq_num.low = 0; | |
13482 | |
13483 spec->epoch = 0; | |
13484 dtls_InitRecvdRecords(&spec->recvdRecords); | |
13485 | |
13486 spec->version = ss->vrange.max; | |
13487 } | |
13488 | |
13489 /* Called from: ssl3_SendRecord | |
13490 ** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake() | |
13491 ** ssl3_SendClientHello() | |
13492 ** ssl3_HandleV2ClientHello() | |
13493 ** ssl3_HandleRecord() | |
13494 ** | |
13495 ** This function should perhaps acquire and release the SpecWriteLock. | |
13496 ** | |
13497 ** | |
13498 */ | |
13499 static SECStatus | |
13500 ssl3_InitState(sslSocket *ss) | |
13501 { | |
13502 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
13503 | |
13504 if (ss->ssl3.initialized) | |
13505 return SECSuccess; /* Function should be idempotent */ | |
13506 | |
13507 ss->ssl3.policy = SSL_ALLOWED; | |
13508 | |
13509 ssl_GetSpecWriteLock(ss); | |
13510 ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0]; | |
13511 ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1]; | |
13512 ss->ssl3.hs.sendingSCSV = PR_FALSE; | |
13513 ssl3_InitCipherSpec(ss, ss->ssl3.crSpec); | |
13514 ssl3_InitCipherSpec(ss, ss->ssl3.prSpec); | |
13515 ss->ssl3.hs.preliminaryInfo = 0; | |
13516 | |
13517 ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello; | |
13518 #ifndef NSS_DISABLE_ECC | |
13519 ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss); | |
13520 #endif | |
13521 ssl_ReleaseSpecWriteLock(ss); | |
13522 | |
13523 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); | |
13524 | |
13525 if (IS_DTLS(ss)) { | |
13526 ss->ssl3.hs.sendMessageSeq = 0; | |
13527 ss->ssl3.hs.recvMessageSeq = 0; | |
13528 ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS; | |
13529 ss->ssl3.hs.rtRetries = 0; | |
13530 ss->ssl3.hs.recvdHighWater = -1; | |
13531 PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight); | |
13532 dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */ | |
13533 } | |
13534 | |
13535 PR_INIT_CLIST(&ss->ssl3.hs.remoteKeyShares); | |
13536 ss->ssl3.hs.xSS = NULL; | |
13537 ss->ssl3.hs.xES = NULL; | |
13538 ss->ssl3.hs.trafficSecret = NULL; | |
13539 ss->ssl3.hs.clientFinishedSecret = NULL; | |
13540 ss->ssl3.hs.serverFinishedSecret = NULL; | |
13541 ss->ssl3.hs.certReqContextLen = 0; | |
13542 | |
13543 PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space); | |
13544 ss->ssl3.hs.messages.buf = NULL; | |
13545 ss->ssl3.hs.messages.space = 0; | |
13546 | |
13547 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; | |
13548 PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0, | |
13549 sizeof(ss->ssl3.hs.newSessionTicket)); | |
13550 | |
13551 ss->ssl3.initialized = PR_TRUE; | |
13552 return SECSuccess; | |
13553 } | |
13554 | |
13555 /* Returns a reference counted object that contains a key pair. | |
13556 * Or NULL on failure. Initial ref count is 1. | |
13557 * Uses the keys in the pair as input. | |
13558 */ | |
13559 ssl3KeyPair * | |
13560 ssl3_NewKeyPair(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey) | |
13561 { | |
13562 ssl3KeyPair *pair; | |
13563 | |
13564 if (!privKey || !pubKey) { | |
13565 PORT_SetError(PR_INVALID_ARGUMENT_ERROR); | |
13566 return NULL; | |
13567 } | |
13568 pair = PORT_ZNew(ssl3KeyPair); | |
13569 if (!pair) | |
13570 return NULL; /* error code is set. */ | |
13571 pair->refCount = 1; | |
13572 pair->privKey = privKey; | |
13573 pair->pubKey = pubKey; | |
13574 return pair; /* success */ | |
13575 } | |
13576 | |
13577 ssl3KeyPair * | |
13578 ssl3_GetKeyPairRef(ssl3KeyPair *keyPair) | |
13579 { | |
13580 PR_ATOMIC_INCREMENT(&keyPair->refCount); | |
13581 return keyPair; | |
13582 } | |
13583 | |
13584 void | |
13585 ssl3_FreeKeyPair(ssl3KeyPair *keyPair) | |
13586 { | |
13587 PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount); | |
13588 if (!newCount) { | |
13589 if (keyPair->privKey) | |
13590 SECKEY_DestroyPrivateKey(keyPair->privKey); | |
13591 if (keyPair->pubKey) | |
13592 SECKEY_DestroyPublicKey(keyPair->pubKey); | |
13593 PORT_Free(keyPair); | |
13594 } | |
13595 } | |
13596 | |
13597 /* | |
13598 * Creates the public and private RSA keys for SSL Step down. | |
13599 * Called from SSL_ConfigSecureServer in sslsecur.c | |
13600 */ | |
13601 SECStatus | |
13602 ssl3_CreateRSAStepDownKeys(sslSocket *ss) | |
13603 { | |
13604 SECStatus rv = SECSuccess; | |
13605 SECKEYPrivateKey *privKey; /* RSA step down key */ | |
13606 SECKEYPublicKey *pubKey; /* RSA step down key */ | |
13607 | |
13608 if (ss->stepDownKeyPair) | |
13609 ssl3_FreeKeyPair(ss->stepDownKeyPair); | |
13610 ss->stepDownKeyPair = NULL; | |
13611 #ifndef HACKED_EXPORT_SERVER | |
13612 /* Sigh, should have a get key strength call for private keys */ | |
13613 if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) > | |
13614 EXPORT_RSA_KEY_LENGTH) { | |
13615 /* need to ask for the key size in bits */ | |
13616 privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB, | |
13617 &pubKey, NULL); | |
13618 if (!privKey || !pubKey || | |
13619 !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) { | |
13620 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); | |
13621 rv = SECFailure; | |
13622 } | |
13623 } | |
13624 #endif | |
13625 return rv; | |
13626 } | |
13627 | |
13628 /* record the export policy for this cipher suite */ | |
13629 SECStatus | |
13630 ssl3_SetPolicy(ssl3CipherSuite which, int policy) | |
13631 { | |
13632 ssl3CipherSuiteCfg *suite; | |
13633 | |
13634 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); | |
13635 if (suite == NULL) { | |
13636 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ | |
13637 } | |
13638 suite->policy = policy; | |
13639 | |
13640 return SECSuccess; | |
13641 } | |
13642 | |
13643 SECStatus | |
13644 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy) | |
13645 { | |
13646 ssl3CipherSuiteCfg *suite; | |
13647 PRInt32 policy; | |
13648 SECStatus rv; | |
13649 | |
13650 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); | |
13651 if (suite) { | |
13652 policy = suite->policy; | |
13653 rv = SECSuccess; | |
13654 } else { | |
13655 policy = SSL_NOT_ALLOWED; | |
13656 rv = SECFailure; /* err code was set by Lookup. */ | |
13657 } | |
13658 *oPolicy = policy; | |
13659 return rv; | |
13660 } | |
13661 | |
13662 /* record the user preference for this suite */ | |
13663 SECStatus | |
13664 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled) | |
13665 { | |
13666 ssl3CipherSuiteCfg *suite; | |
13667 | |
13668 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); | |
13669 if (suite == NULL) { | |
13670 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ | |
13671 } | |
13672 suite->enabled = enabled; | |
13673 return SECSuccess; | |
13674 } | |
13675 | |
13676 /* return the user preference for this suite */ | |
13677 SECStatus | |
13678 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled) | |
13679 { | |
13680 ssl3CipherSuiteCfg *suite; | |
13681 PRBool pref; | |
13682 SECStatus rv; | |
13683 | |
13684 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); | |
13685 if (suite) { | |
13686 pref = suite->enabled; | |
13687 rv = SECSuccess; | |
13688 } else { | |
13689 pref = SSL_NOT_ALLOWED; | |
13690 rv = SECFailure; /* err code was set by Lookup. */ | |
13691 } | |
13692 *enabled = pref; | |
13693 return rv; | |
13694 } | |
13695 | |
13696 SECStatus | |
13697 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled) | |
13698 { | |
13699 ssl3CipherSuiteCfg *suite; | |
13700 | |
13701 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); | |
13702 if (suite == NULL) { | |
13703 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ | |
13704 } | |
13705 suite->enabled = enabled; | |
13706 return SECSuccess; | |
13707 } | |
13708 | |
13709 SECStatus | |
13710 ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled) | |
13711 { | |
13712 ssl3CipherSuiteCfg *suite; | |
13713 PRBool pref; | |
13714 SECStatus rv; | |
13715 | |
13716 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); | |
13717 if (suite) { | |
13718 pref = suite->enabled; | |
13719 rv = SECSuccess; | |
13720 } else { | |
13721 pref = SSL_NOT_ALLOWED; | |
13722 rv = SECFailure; /* err code was set by Lookup. */ | |
13723 } | |
13724 *enabled = pref; | |
13725 return rv; | |
13726 } | |
13727 | |
13728 SECStatus | |
13729 SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms, | |
13730 unsigned int count) | |
13731 { | |
13732 sslSocket *ss; | |
13733 unsigned int i; | |
13734 | |
13735 ss = ssl_FindSocket(fd); | |
13736 if (!ss) { | |
13737 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignaturePrefSet", | |
13738 SSL_GETPID(), fd)); | |
13739 PORT_SetError(SEC_ERROR_INVALID_ARGS); | |
13740 return SECFailure; | |
13741 } | |
13742 | |
13743 if (!count || count > MAX_SIGNATURE_ALGORITHMS) { | |
13744 PORT_SetError(SEC_ERROR_INVALID_ARGS); | |
13745 return SECFailure; | |
13746 } | |
13747 | |
13748 ss->ssl3.signatureAlgorithmCount = 0; | |
13749 for (i = 0; i < count; ++i) { | |
13750 if (!ssl3_IsSupportedSignatureAlgorithm(&algorithms[i])) { | |
13751 SSL_DBG(("%d: SSL[%d]: invalid signature algorithm set %d/%d", | |
13752 SSL_GETPID(), fd, algorithms[i].sigAlg, | |
13753 algorithms[i].hashAlg)); | |
13754 continue; | |
13755 } | |
13756 | |
13757 ss->ssl3.signatureAlgorithms[ss->ssl3.signatureAlgorithmCount++] = | |
13758 algorithms[i]; | |
13759 } | |
13760 | |
13761 if (ss->ssl3.signatureAlgorithmCount == 0) { | |
13762 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); | |
13763 return SECFailure; | |
13764 } | |
13765 return SECSuccess; | |
13766 } | |
13767 | |
13768 SECStatus | |
13769 SSL_SignaturePrefGet(PRFileDesc *fd, SSLSignatureAndHashAlg *algorithms, | |
13770 unsigned int *count, unsigned int maxCount) | |
13771 { | |
13772 sslSocket *ss; | |
13773 unsigned int requiredSpace; | |
13774 | |
13775 ss = ssl_FindSocket(fd); | |
13776 if (!ss) { | |
13777 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignaturePrefGet", | |
13778 SSL_GETPID(), fd)); | |
13779 PORT_SetError(SEC_ERROR_INVALID_ARGS); | |
13780 return SECFailure; | |
13781 } | |
13782 | |
13783 if (!algorithms || !count || | |
13784 maxCount < ss->ssl3.signatureAlgorithmCount) { | |
13785 PORT_SetError(SEC_ERROR_INVALID_ARGS); | |
13786 return SECFailure; | |
13787 } | |
13788 | |
13789 requiredSpace = | |
13790 ss->ssl3.signatureAlgorithmCount * sizeof(SSLSignatureAndHashAlg); | |
13791 PORT_Memcpy(algorithms, ss->ssl3.signatureAlgorithms, requiredSpace); | |
13792 *count = ss->ssl3.signatureAlgorithmCount; | |
13793 return SECSuccess; | |
13794 } | |
13795 | |
13796 unsigned int | |
13797 SSL_SignatureMaxCount() | |
13798 { | |
13799 return MAX_SIGNATURE_ALGORITHMS; | |
13800 } | |
13801 | |
13802 SECStatus | |
13803 ssl3_CipherOrderSet(sslSocket *ss, const ssl3CipherSuite *ciphers, unsigned int
len) | |
13804 { | |
13805 /* |i| iterates over |ciphers| while |done| and |j| iterate over | |
13806 * |ss->cipherSuites|. */ | |
13807 unsigned int i, done; | |
13808 | |
13809 for (i = done = 0; i < len; i++) { | |
13810 PRUint16 id = ciphers[i]; | |
13811 unsigned int existingIndex, j; | |
13812 PRBool found = PR_FALSE; | |
13813 | |
13814 for (j = done; j < ssl_V3_SUITES_IMPLEMENTED; j++) { | |
13815 if (ss->cipherSuites[j].cipher_suite == id) { | |
13816 existingIndex = j; | |
13817 found = PR_TRUE; | |
13818 break; | |
13819 } | |
13820 } | |
13821 | |
13822 if (!found) { | |
13823 continue; | |
13824 } | |
13825 | |
13826 if (existingIndex != done) { | |
13827 const ssl3CipherSuiteCfg temp = ss->cipherSuites[done]; | |
13828 ss->cipherSuites[done] = ss->cipherSuites[existingIndex]; | |
13829 ss->cipherSuites[existingIndex] = temp; | |
13830 } | |
13831 done++; | |
13832 } | |
13833 | |
13834 /* Disable all cipher suites that weren't included. */ | |
13835 for (; done < ssl_V3_SUITES_IMPLEMENTED; done++) { | |
13836 ss->cipherSuites[done].enabled = 0; | |
13837 } | |
13838 | |
13839 return SECSuccess; | |
13840 } | |
13841 | |
13842 /* copy global default policy into socket. */ | |
13843 void | |
13844 ssl3_InitSocketPolicy(sslSocket *ss) | |
13845 { | |
13846 PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites); | |
13847 PORT_Memcpy(ss->ssl3.signatureAlgorithms, defaultSignatureAlgorithms, | |
13848 sizeof(defaultSignatureAlgorithms)); | |
13849 ss->ssl3.signatureAlgorithmCount = PR_ARRAY_SIZE(defaultSignatureAlgorithms)
; | |
13850 } | |
13851 | |
13852 SECStatus | |
13853 ssl3_GetTLSUniqueChannelBinding(sslSocket *ss, | |
13854 unsigned char *out, | |
13855 unsigned int *outLen, | |
13856 unsigned int outLenMax) | |
13857 { | |
13858 PRBool isTLS; | |
13859 int index = 0; | |
13860 unsigned int len; | |
13861 SECStatus rv = SECFailure; | |
13862 | |
13863 *outLen = 0; | |
13864 | |
13865 ssl_GetSSL3HandshakeLock(ss); | |
13866 | |
13867 ssl_GetSpecReadLock(ss); | |
13868 isTLS = (PRBool)(ss->ssl3.cwSpec->version > SSL_LIBRARY_VERSION_3_0); | |
13869 ssl_ReleaseSpecReadLock(ss); | |
13870 | |
13871 /* The tls-unique channel binding is the first Finished structure in the | |
13872 * handshake. In the case of a resumption, that's the server's Finished. | |
13873 * Otherwise, it's the client's Finished. */ | |
13874 len = ss->ssl3.hs.finishedBytes; | |
13875 | |
13876 /* Sending or receiving a Finished message will set finishedBytes to a | |
13877 * non-zero value. */ | |
13878 if (len == 0) { | |
13879 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); | |
13880 goto loser; | |
13881 } | |
13882 | |
13883 /* If we are in the middle of a renegotiation then the channel binding | |
13884 * value is poorly defined and depends on the direction that it will be | |
13885 * used on. Therefore we simply return an error in this case. */ | |
13886 if (ss->firstHsDone && ss->ssl3.hs.ws != idle_handshake) { | |
13887 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); | |
13888 goto loser; | |
13889 } | |
13890 | |
13891 /* If resuming, then we want the second Finished value in the array, which | |
13892 * is the server's */ | |
13893 if (ss->ssl3.hs.isResuming) | |
13894 index = 1; | |
13895 | |
13896 *outLen = len; | |
13897 if (outLenMax < len) { | |
13898 PORT_SetError(SEC_ERROR_OUTPUT_LEN); | |
13899 goto loser; | |
13900 } | |
13901 | |
13902 if (isTLS) { | |
13903 memcpy(out, &ss->ssl3.hs.finishedMsgs.tFinished[index], len); | |
13904 } else { | |
13905 memcpy(out, &ss->ssl3.hs.finishedMsgs.sFinished[index], len); | |
13906 } | |
13907 | |
13908 rv = SECSuccess; | |
13909 | |
13910 loser: | |
13911 ssl_ReleaseSSL3HandshakeLock(ss); | |
13912 return rv; | |
13913 } | |
13914 | |
13915 /* ssl3_config_match_init must have already been called by | |
13916 * the caller of this function. | |
13917 */ | |
13918 SECStatus | |
13919 ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size) | |
13920 { | |
13921 int i, count = 0; | |
13922 | |
13923 PORT_Assert(ss != 0); | |
13924 if (!ss) { | |
13925 PORT_SetError(PR_INVALID_ARGUMENT_ERROR); | |
13926 return SECFailure; | |
13927 } | |
13928 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { | |
13929 *size = 0; | |
13930 return SECSuccess; | |
13931 } | |
13932 if (cs == NULL) { | |
13933 *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE); | |
13934 return SECSuccess; | |
13935 } | |
13936 | |
13937 /* ssl3_config_match_init was called by the caller of this function. */ | |
13938 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { | |
13939 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; | |
13940 if (config_match(suite, SSL_ALLOWED, PR_TRUE, &ss->vrange, ss)) { | |
13941 if (cs != NULL) { | |
13942 *cs++ = 0x00; | |
13943 *cs++ = (suite->cipher_suite >> 8) & 0xFF; | |
13944 *cs++ = suite->cipher_suite & 0xFF; | |
13945 } | |
13946 count++; | |
13947 } | |
13948 } | |
13949 *size = count; | |
13950 return SECSuccess; | |
13951 } | |
13952 | |
13953 /* | |
13954 ** If ssl3 socket has completed the first handshake, and is in idle state, | |
13955 ** then start a new handshake. | |
13956 ** If flushCache is true, the SID cache will be flushed first, forcing a | |
13957 ** "Full" handshake (not a session restart handshake), to be done. | |
13958 ** | |
13959 ** called from SSL_RedoHandshake(), which already holds the handshake locks. | |
13960 */ | |
13961 SECStatus | |
13962 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache) | |
13963 { | |
13964 sslSessionID *sid = ss->sec.ci.sid; | |
13965 SECStatus rv; | |
13966 | |
13967 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); | |
13968 | |
13969 if (!ss->firstHsDone || | |
13970 ((ss->version >= SSL_LIBRARY_VERSION_3_0) && | |
13971 ss->ssl3.initialized && | |
13972 (ss->ssl3.hs.ws != idle_handshake))) { | |
13973 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); | |
13974 return SECFailure; | |
13975 } | |
13976 | |
13977 if (IS_DTLS(ss)) { | |
13978 dtls_RehandshakeCleanup(ss); | |
13979 } | |
13980 | |
13981 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { | |
13982 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); | |
13983 return SECFailure; | |
13984 } | |
13985 if (sid && flushCache) { | |
13986 if (ss->sec.uncache) | |
13987 ss->sec.uncache(sid); /* remove it from whichever cache it's in. */ | |
13988 ssl_FreeSID(sid); /* dec ref count and free if zero. */ | |
13989 ss->sec.ci.sid = NULL; | |
13990 } | |
13991 | |
13992 ssl_GetXmitBufLock(ss); /**************************************/ | |
13993 | |
13994 /* start off a new handshake. */ | |
13995 rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss) | |
13996 : ssl3_SendClientHello(ss, PR_FALSE); | |
13997 | |
13998 ssl_ReleaseXmitBufLock(ss); /**************************************/ | |
13999 return rv; | |
14000 } | |
14001 | |
14002 /* Called from ssl_DestroySocketContents() in sslsock.c */ | |
14003 void | |
14004 ssl3_DestroySSL3Info(sslSocket *ss) | |
14005 { | |
14006 | |
14007 if (ss->ssl3.clientCertificate != NULL) | |
14008 CERT_DestroyCertificate(ss->ssl3.clientCertificate); | |
14009 | |
14010 if (ss->ssl3.clientPrivateKey != NULL) | |
14011 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); | |
14012 | |
14013 if (ss->ssl3.channelID) | |
14014 SECKEY_DestroyPrivateKey(ss->ssl3.channelID); | |
14015 if (ss->ssl3.channelIDPub) | |
14016 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub); | |
14017 | |
14018 if (ss->ssl3.peerCertArena != NULL) | |
14019 ssl3_CleanupPeerCerts(ss); | |
14020 | |
14021 if (ss->ssl3.clientCertChain != NULL) { | |
14022 CERT_DestroyCertificateList(ss->ssl3.clientCertChain); | |
14023 ss->ssl3.clientCertChain = NULL; | |
14024 } | |
14025 | |
14026 /* clean up handshake */ | |
14027 #ifndef NO_PKCS11_BYPASS | |
14028 if (ss->opt.bypassPKCS11) { | |
14029 if (ss->ssl3.hs.hashType == handshake_hash_combo) { | |
14030 SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE); | |
14031 MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE); | |
14032 } else if (ss->ssl3.hs.hashType == handshake_hash_single) { | |
14033 ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE); | |
14034 } | |
14035 } | |
14036 #endif | |
14037 if (ss->ssl3.hs.md5) { | |
14038 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); | |
14039 } | |
14040 if (ss->ssl3.hs.sha) { | |
14041 PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE); | |
14042 } | |
14043 if (ss->ssl3.hs.clientSigAndHash) { | |
14044 PORT_Free(ss->ssl3.hs.clientSigAndHash); | |
14045 } | |
14046 if (ss->ssl3.hs.messages.buf) { | |
14047 PORT_Free(ss->ssl3.hs.messages.buf); | |
14048 ss->ssl3.hs.messages.buf = NULL; | |
14049 ss->ssl3.hs.messages.len = 0; | |
14050 ss->ssl3.hs.messages.space = 0; | |
14051 } | |
14052 | |
14053 /* free the SSL3Buffer (msg_body) */ | |
14054 PORT_Free(ss->ssl3.hs.msg_body.buf); | |
14055 | |
14056 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); | |
14057 | |
14058 /* free up the CipherSpecs */ | |
14059 ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE /*freeSrvName*/); | |
14060 ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE /*freeSrvName*/); | |
14061 | |
14062 /* Destroy the DTLS data */ | |
14063 if (IS_DTLS(ss)) { | |
14064 dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight); | |
14065 if (ss->ssl3.hs.recvdFragments.buf) { | |
14066 PORT_Free(ss->ssl3.hs.recvdFragments.buf); | |
14067 } | |
14068 } | |
14069 | |
14070 /* Destroy TLS 1.3 handshake shares */ | |
14071 tls13_DestroyKeyShares(&ss->ssl3.hs.remoteKeyShares); | |
14072 | |
14073 /* Destroy TLS 1.3 keys */ | |
14074 if (ss->ssl3.hs.xSS) | |
14075 PK11_FreeSymKey(ss->ssl3.hs.xSS); | |
14076 if (ss->ssl3.hs.xES) | |
14077 PK11_FreeSymKey(ss->ssl3.hs.xES); | |
14078 if (ss->ssl3.hs.trafficSecret) | |
14079 PK11_FreeSymKey(ss->ssl3.hs.trafficSecret); | |
14080 if (ss->ssl3.hs.clientFinishedSecret) | |
14081 PK11_FreeSymKey(ss->ssl3.hs.clientFinishedSecret); | |
14082 if (ss->ssl3.hs.serverFinishedSecret) | |
14083 PK11_FreeSymKey(ss->ssl3.hs.serverFinishedSecret); | |
14084 | |
14085 if (ss->ssl3.dheGroups) { | |
14086 PORT_Free(ss->ssl3.dheGroups); | |
14087 } | |
14088 | |
14089 ss->ssl3.initialized = PR_FALSE; | |
14090 | |
14091 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE); | |
14092 } | |
14093 | |
14094 #define MAP_NULL(x) (((x) != 0) ? (x) : SEC_OID_NULL_CIPHER) | |
14095 | |
14096 SECStatus | |
14097 ssl3_ApplyNSSPolicy(void) | |
14098 { | |
14099 unsigned i; | |
14100 SECStatus rv; | |
14101 PRUint32 policy = 0; | |
14102 | |
14103 rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy); | |
14104 if (rv != SECSuccess || !(policy & NSS_USE_POLICY_IN_SSL)) { | |
14105 return SECSuccess; /* do nothing */ | |
14106 } | |
14107 | |
14108 /* disable every ciphersuite */ | |
14109 for (i = 1; i < PR_ARRAY_SIZE(cipher_suite_defs); ++i) { | |
14110 const ssl3CipherSuiteDef *suite = &cipher_suite_defs[i]; | |
14111 SECOidTag policyOid; | |
14112 | |
14113 policyOid = MAP_NULL(kea_defs[suite->key_exchange_alg].oid); | |
14114 rv = NSS_GetAlgorithmPolicy(policyOid, &policy); | |
14115 if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL_KX)) { | |
14116 ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); | |
14117 ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED); | |
14118 continue; | |
14119 } | |
14120 | |
14121 policyOid = MAP_NULL(bulk_cipher_defs[suite->bulk_cipher_alg].oid); | |
14122 rv = NSS_GetAlgorithmPolicy(policyOid, &policy); | |
14123 if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL)) { | |
14124 ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); | |
14125 ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED); | |
14126 continue; | |
14127 } | |
14128 | |
14129 if (bulk_cipher_defs[suite->bulk_cipher_alg].type != type_aead) { | |
14130 policyOid = MAP_NULL(mac_defs[suite->mac_alg].oid); | |
14131 rv = NSS_GetAlgorithmPolicy(policyOid, &policy); | |
14132 if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL)) { | |
14133 ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); | |
14134 ssl_CipherPolicySet(suite->cipher_suite, | |
14135 SSL_NOT_ALLOWED); | |
14136 continue; | |
14137 } | |
14138 } | |
14139 } | |
14140 | |
14141 rv = ssl3_ConstrainRangeByPolicy(); | |
14142 | |
14143 return rv; | |
14144 } | |
14145 | |
14146 /* End of ssl3con.c */ | |
OLD | NEW |