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 "ssl3ext.h"
23 #include "ssl3exthandle.h"
24 #include "tls13ech.h"
25 #include "tls13exthandle.h"
26 #include "tls13psk.h"
27 #include "tls13subcerts.h"
28 #include "prtime.h"
29 #include "prinrval.h"
30 #include "prerror.h"
31 #include "pratom.h"
32 #include "prthread.h"
33 #include "nss.h"
34 #include "nssoptions.h"
35
36 #include "pk11func.h"
37 #include "secmod.h"
38 #include "blapi.h"
39
40 #include <stdio.h>
41
42 static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
43 PK11SlotInfo *serverKeySlot);
44 static SECStatus ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
45 PK11SymKey **msp);
46 static SECStatus ssl3_DeriveConnectionKeys(sslSocket *ss,
47 PK11SymKey *masterSecret);
48 static SECStatus ssl3_HandshakeFailure(sslSocket *ss);
49 static SECStatus ssl3_SendCertificate(sslSocket *ss);
50 static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
51 static SECStatus ssl3_SendNextProto(sslSocket *ss);
52 static SECStatus ssl3_SendFinished(sslSocket *ss, PRInt32 flags);
53 static SECStatus ssl3_SendServerHelloDone(sslSocket *ss);
54 static SECStatus ssl3_SendServerKeyExchange(sslSocket *ss);
55 static SECStatus ssl3_HandleClientHelloPart2(sslSocket *ss,
56 SECItem *suites,
57 sslSessionID *sid,
58 const PRUint8 *msg,
59 unsigned int len);
60 static SECStatus ssl3_HandleServerHelloPart2(sslSocket *ss,
61 const SECItem *sidBytes,
62 int *retErrCode);
63 static SECStatus ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss,
64 PRUint8 *b,
65 PRUint32 length);
66 static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
67 static CK_MECHANISM_TYPE ssl3_GetHashMechanismByHashType(SSLHashType hashType);
68 static CK_MECHANISM_TYPE ssl3_GetMgfMechanismByHashType(SSLHashType hash);
69 PRBool ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme);
70 PRBool ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme);
71 PRBool ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme);
72 PRBool ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme);
73 static SECStatus ssl3_UpdateDefaultHandshakeHashes(sslSocket *ss,
74 const unsigned char *b,
75 unsigned int l);
76 const PRUint32 kSSLSigSchemePolicy =
77 NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_ANY_SIGNATURE;
78
79 const PRUint8 ssl_hello_retry_random[] = {
80 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
81 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
82 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
83 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
84 };
85 PR_STATIC_ASSERT(PR_ARRAY_SIZE(ssl_hello_retry_random) == SSL3_RANDOM_LENGTH);
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 /* Special TLS 1.3 suites. */
99 { TLS_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE },
100 { TLS_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE },
101 { TLS_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE },
102
103 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
104 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
105 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
106 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
107 { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE},
108 { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE},
109 /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around
110 * bug 946147.
111 */
112 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
113 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
114 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
115 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
116 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
117 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
118 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE},
119 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE},
120 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
121 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
122 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
123 { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
124
125 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
126 { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,SSL_ALLOWED,PR_TRUE, PR_FALSE},
127 { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
128 { TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE},
129 { TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE},
130 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
131 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
132 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
133 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
134 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
135 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
136 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
137 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
138 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
139 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
140 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
141 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
142 { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
143 { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
144 { TLS_DHE_DSS_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
145
146 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
147 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
148 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
149 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
150 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
151 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
152 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
153 { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
154
155 /* RSA */
156 { TLS_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
157 { TLS_RSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE},
158 { TLS_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
159 { TLS_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
160 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
161 { TLS_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
162 { TLS_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
163 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
164 { TLS_RSA_WITH_SEED_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
165 { TLS_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
166 { TLS_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
167 { TLS_RSA_WITH_RC4_128_MD5, SSL_ALLOWED, PR_TRUE, PR_FALSE},
168
169 /* 56-bit DES "domestic" cipher suites */
170 { TLS_DHE_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
171 { TLS_DHE_DSS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
172 { TLS_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
173
174 /* ciphersuites with no encryption */
175 { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
176 { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
177 { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
178 { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
179 { TLS_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
180 { TLS_RSA_WITH_NULL_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
181 { TLS_RSA_WITH_NULL_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE},
182 };
183 /* clang-format on */
184
185 /* This is the default supported set of signature schemes. The order of the
186 * hashes here is all that is important, since that will (sometimes) determine
187 * which hash we use. The key pair (i.e., cert) is the primary thing that
188 * determines what we use and this doesn't affect how we select key pairs. The
189 * order of signature types is based on the same rules for ordering we use for
190 * cipher suites just for consistency.
191 */
192 static const SSLSignatureScheme defaultSignatureSchemes[] = {
193 ssl_sig_ecdsa_secp256r1_sha256,
194 ssl_sig_ecdsa_secp384r1_sha384,
195 ssl_sig_ecdsa_secp521r1_sha512,
196 ssl_sig_ecdsa_sha1,
197 ssl_sig_rsa_pss_rsae_sha256,
198 ssl_sig_rsa_pss_rsae_sha384,
199 ssl_sig_rsa_pss_rsae_sha512,
200 ssl_sig_rsa_pkcs1_sha256,
201 ssl_sig_rsa_pkcs1_sha384,
202 ssl_sig_rsa_pkcs1_sha512,
203 ssl_sig_rsa_pkcs1_sha1,
204 ssl_sig_dsa_sha256,
205 ssl_sig_dsa_sha384,
206 ssl_sig_dsa_sha512,
207 ssl_sig_dsa_sha1
208 };
209 PR_STATIC_ASSERT(PR_ARRAY_SIZE(defaultSignatureSchemes) <=
210 MAX_SIGNATURE_SCHEMES);
211
212 /* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order.
213 */
214 #ifdef DEBUG
215 void
ssl3_CheckCipherSuiteOrderConsistency()216 ssl3_CheckCipherSuiteOrderConsistency()
217 {
218 unsigned int i;
219
220 PORT_Assert(SSL_NumImplementedCiphers == PR_ARRAY_SIZE(cipherSuites));
221
222 for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) {
223 PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite);
224 }
225 }
226 #endif
227
228 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types[] = {
229 ct_RSA_sign,
230 ct_ECDSA_sign,
231 ct_DSS_sign,
232 };
233
234 static SSL3Statistics ssl3stats;
235
236 static const ssl3KEADef kea_defs[] =
237 {
238 /* indexed by SSL3KeyExchangeAlgorithm */
239 /* kea exchKeyType signKeyType authKeyType ephemeral oid */
240 { kea_null, ssl_kea_null, nullKey, ssl_auth_null, PR_FALSE, 0 },
241 { kea_rsa, ssl_kea_rsa, nullKey, ssl_auth_rsa_decrypt, PR_FALSE, SEC_OID_TLS_RSA },
242 { kea_dh_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_FALSE, SEC_OID_TLS_DH_DSS },
243 { kea_dh_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_FALSE, SEC_OID_TLS_DH_RSA },
244 { kea_dhe_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_TRUE, SEC_OID_TLS_DHE_DSS },
245 { kea_dhe_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_DHE_RSA },
246 { kea_dh_anon, ssl_kea_dh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_DH_ANON },
247 { kea_ecdh_ecdsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_ecdsa, PR_FALSE, SEC_OID_TLS_ECDH_ECDSA },
248 { kea_ecdhe_ecdsa, ssl_kea_ecdh, ecKey, ssl_auth_ecdsa, PR_TRUE, SEC_OID_TLS_ECDHE_ECDSA },
249 { kea_ecdh_rsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_rsa, PR_FALSE, SEC_OID_TLS_ECDH_RSA },
250 { kea_ecdhe_rsa, ssl_kea_ecdh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_ECDHE_RSA },
251 { kea_ecdh_anon, ssl_kea_ecdh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_ECDH_ANON },
252 { kea_ecdhe_psk, ssl_kea_ecdh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_ECDHE_PSK },
253 { kea_dhe_psk, ssl_kea_dh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_DHE_PSK },
254 { kea_tls13_any, ssl_kea_tls13_any, nullKey, ssl_auth_tls13_any, PR_TRUE, SEC_OID_TLS13_KEA_ANY },
255 };
256
257 /* must use ssl_LookupCipherSuiteDef to access */
258 static const ssl3CipherSuiteDef cipher_suite_defs[] =
259 {
260 /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg prf_hash */
261 /* Note that the prf_hash_alg is the hash function used by the PRF, see sslimpl.h. */
262
263 { TLS_NULL_WITH_NULL_NULL, cipher_null, ssl_mac_null, kea_null, ssl_hash_none },
264 { TLS_RSA_WITH_NULL_MD5, cipher_null, ssl_mac_md5, kea_rsa, ssl_hash_none },
265 { TLS_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_rsa, ssl_hash_none },
266 { TLS_RSA_WITH_NULL_SHA256, cipher_null, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
267 { TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, ssl_mac_md5, kea_rsa, ssl_hash_none },
268 { TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_rsa, ssl_hash_none },
269 { TLS_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_rsa, ssl_hash_none },
270 { TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_rsa, ssl_hash_none },
271 { TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
272 { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
273 cipher_3des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
274 { TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
275 { TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
276 { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
277 cipher_3des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
278
279 /* New TLS cipher suites */
280 { TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
281 { TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
282 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
283 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
284 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
285 { TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
286 { TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
287 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
288 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
289 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
290 { TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha384 },
291
292 { TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, ssl_mac_sha, kea_rsa, ssl_hash_none },
293
294 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
295 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
296 cipher_camellia_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
297 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
298 cipher_camellia_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
299 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
300 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
301 cipher_camellia_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
302 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
303 cipher_camellia_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
304
305 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
306 { TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha256 },
307
308 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
309 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
310 { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha384 },
311 { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha384 },
312 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_ecdsa, ssl_hash_sha384 },
313 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_rsa, ssl_hash_sha384 },
314 { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha256 },
315 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
316 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
317 { TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha384 },
318 { TLS_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha384 },
319
320 { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
321
322 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
323 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
324
325 { TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
326 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
327 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
328 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
329 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
330
331 { TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
332 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
333 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
334 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
335 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_ecdsa, ssl_hash_sha256 },
336 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
337
338 { TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
339 { TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
340 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
341 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
342 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
343
344 { TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
345 { TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
346 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
347 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
348 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_rsa, ssl_hash_sha256 },
349 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
350
351 { TLS_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
352 { TLS_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
353 { TLS_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha384 },
354 };
355
356 static const CK_MECHANISM_TYPE auth_alg_defs[] = {
357 CKM_INVALID_MECHANISM, /* ssl_auth_null */
358 CKM_RSA_PKCS, /* ssl_auth_rsa_decrypt */
359 CKM_DSA, /* ? _SHA1 */ /* ssl_auth_dsa */
360 CKM_INVALID_MECHANISM, /* ssl_auth_kea (unused) */
361 CKM_ECDSA, /* ssl_auth_ecdsa */
362 CKM_ECDH1_DERIVE, /* ssl_auth_ecdh_rsa */
363 CKM_ECDH1_DERIVE, /* ssl_auth_ecdh_ecdsa */
364 CKM_RSA_PKCS, /* ssl_auth_rsa_sign */
365 CKM_RSA_PKCS_PSS, /* ssl_auth_rsa_pss */
366 CKM_NSS_HKDF_SHA256, /* ssl_auth_psk (just check for HKDF) */
367 CKM_INVALID_MECHANISM /* ssl_auth_tls13_any */
368 };
369 PR_STATIC_ASSERT(PR_ARRAY_SIZE(auth_alg_defs) == ssl_auth_size);
370
371 static const CK_MECHANISM_TYPE kea_alg_defs[] = {
372 CKM_INVALID_MECHANISM, /* ssl_kea_null */
373 CKM_RSA_PKCS, /* ssl_kea_rsa */
374 CKM_DH_PKCS_DERIVE, /* ssl_kea_dh */
375 CKM_INVALID_MECHANISM, /* ssl_kea_fortezza (unused) */
376 CKM_ECDH1_DERIVE, /* ssl_kea_ecdh */
377 CKM_ECDH1_DERIVE, /* ssl_kea_ecdh_psk */
378 CKM_DH_PKCS_DERIVE, /* ssl_kea_dh_psk */
379 CKM_INVALID_MECHANISM, /* ssl_kea_tls13_any */
380 };
381 PR_STATIC_ASSERT(PR_ARRAY_SIZE(kea_alg_defs) == ssl_kea_size);
382
383 typedef struct SSLCipher2MechStr {
384 SSLCipherAlgorithm calg;
385 CK_MECHANISM_TYPE cmech;
386 } SSLCipher2Mech;
387
388 /* indexed by type SSLCipherAlgorithm */
389 static const SSLCipher2Mech alg2Mech[] = {
390 /* calg, cmech */
391 { ssl_calg_null, CKM_INVALID_MECHANISM },
392 { ssl_calg_rc4, CKM_RC4 },
393 { ssl_calg_rc2, CKM_RC2_CBC },
394 { ssl_calg_des, CKM_DES_CBC },
395 { ssl_calg_3des, CKM_DES3_CBC },
396 { ssl_calg_idea, CKM_IDEA_CBC },
397 { ssl_calg_fortezza, CKM_SKIPJACK_CBC64 },
398 { ssl_calg_aes, CKM_AES_CBC },
399 { ssl_calg_camellia, CKM_CAMELLIA_CBC },
400 { ssl_calg_seed, CKM_SEED_CBC },
401 { ssl_calg_aes_gcm, CKM_AES_GCM },
402 { ssl_calg_chacha20, CKM_CHACHA20_POLY1305 },
403 };
404
405 const PRUint8 tls12_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
406 0x47, 0x52, 0x44, 0x01 };
407 const PRUint8 tls1_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
408 0x47, 0x52, 0x44, 0x00 };
409 PR_STATIC_ASSERT(sizeof(tls12_downgrade_random) ==
410 sizeof(tls1_downgrade_random));
411
412 /* The ECCWrappedKeyInfo structure defines how various pieces of
413 * information are laid out within wrappedSymmetricWrappingkey
414 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
415 * a 512-byte buffer (see sslimpl.h), the variable length field
416 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
417 *
418 * XXX For now, NSS only supports named elliptic curves of size 571 bits
419 * or smaller. The public value will fit within 145 bytes and EC params
420 * will fit within 12 bytes. We'll need to revisit this when NSS
421 * supports arbitrary curves.
422 */
423 #define MAX_EC_WRAPPED_KEY_BUFLEN 504
424
425 typedef struct ECCWrappedKeyInfoStr {
426 PRUint16 size; /* EC public key size in bits */
427 PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */
428 PRUint16 pubValueLen; /* length (in bytes) of EC public value */
429 PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */
430 PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
431 /* EC public-key params, the EC public value and the wrapped key */
432 } ECCWrappedKeyInfo;
433
434 CK_MECHANISM_TYPE
ssl3_Alg2Mech(SSLCipherAlgorithm calg)435 ssl3_Alg2Mech(SSLCipherAlgorithm calg)
436 {
437 PORT_Assert(alg2Mech[calg].calg == calg);
438 return alg2Mech[calg].cmech;
439 }
440
441 #if defined(TRACE)
442
443 static char *
ssl3_DecodeHandshakeType(int msgType)444 ssl3_DecodeHandshakeType(int msgType)
445 {
446 char *rv;
447 static char line[40];
448
449 switch (msgType) {
450 case ssl_hs_hello_request:
451 rv = "hello_request (0)";
452 break;
453 case ssl_hs_client_hello:
454 rv = "client_hello (1)";
455 break;
456 case ssl_hs_server_hello:
457 rv = "server_hello (2)";
458 break;
459 case ssl_hs_hello_verify_request:
460 rv = "hello_verify_request (3)";
461 break;
462 case ssl_hs_new_session_ticket:
463 rv = "new_session_ticket (4)";
464 break;
465 case ssl_hs_end_of_early_data:
466 rv = "end_of_early_data (5)";
467 break;
468 case ssl_hs_hello_retry_request:
469 rv = "hello_retry_request (6)";
470 break;
471 case ssl_hs_encrypted_extensions:
472 rv = "encrypted_extensions (8)";
473 break;
474 case ssl_hs_certificate:
475 rv = "certificate (11)";
476 break;
477 case ssl_hs_server_key_exchange:
478 rv = "server_key_exchange (12)";
479 break;
480 case ssl_hs_certificate_request:
481 rv = "certificate_request (13)";
482 break;
483 case ssl_hs_server_hello_done:
484 rv = "server_hello_done (14)";
485 break;
486 case ssl_hs_certificate_verify:
487 rv = "certificate_verify (15)";
488 break;
489 case ssl_hs_client_key_exchange:
490 rv = "client_key_exchange (16)";
491 break;
492 case ssl_hs_finished:
493 rv = "finished (20)";
494 break;
495 case ssl_hs_certificate_status:
496 rv = "certificate_status (22)";
497 break;
498 case ssl_hs_key_update:
499 rv = "key_update (24)";
500 break;
501 default:
502 sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType);
503 rv = line;
504 }
505 return rv;
506 }
507
508 static char *
ssl3_DecodeContentType(int msgType)509 ssl3_DecodeContentType(int msgType)
510 {
511 char *rv;
512 static char line[40];
513
514 switch (msgType) {
515 case ssl_ct_change_cipher_spec:
516 rv = "change_cipher_spec (20)";
517 break;
518 case ssl_ct_alert:
519 rv = "alert (21)";
520 break;
521 case ssl_ct_handshake:
522 rv = "handshake (22)";
523 break;
524 case ssl_ct_application_data:
525 rv = "application_data (23)";
526 break;
527 case ssl_ct_ack:
528 rv = "ack (26)";
529 break;
530 default:
531 sprintf(line, "*UNKNOWN* record type! (%d)", msgType);
532 rv = line;
533 }
534 return rv;
535 }
536
537 #endif
538
539 SSL3Statistics *
SSL_GetStatistics(void)540 SSL_GetStatistics(void)
541 {
542 return &ssl3stats;
543 }
544
545 typedef struct tooLongStr {
546 #if defined(IS_LITTLE_ENDIAN)
547 PRInt32 low;
548 PRInt32 high;
549 #else
550 PRInt32 high;
551 PRInt32 low;
552 #endif
553 } tooLong;
554
555 void
SSL_AtomicIncrementLong(long * x)556 SSL_AtomicIncrementLong(long *x)
557 {
558 if ((sizeof *x) == sizeof(PRInt32)) {
559 PR_ATOMIC_INCREMENT((PRInt32 *)x);
560 } else {
561 tooLong *tl = (tooLong *)x;
562 if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
563 PR_ATOMIC_INCREMENT(&tl->high);
564 }
565 }
566
567 PRBool
ssl3_CipherSuiteAllowedForVersionRange(ssl3CipherSuite cipherSuite,const SSLVersionRange * vrange)568 ssl3_CipherSuiteAllowedForVersionRange(ssl3CipherSuite cipherSuite,
569 const SSLVersionRange *vrange)
570 {
571 switch (cipherSuite) {
572 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
573 case TLS_RSA_WITH_AES_256_CBC_SHA256:
574 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
575 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
576 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
577 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
578 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
579 case TLS_RSA_WITH_AES_128_CBC_SHA256:
580 case TLS_RSA_WITH_AES_128_GCM_SHA256:
581 case TLS_RSA_WITH_AES_256_GCM_SHA384:
582 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
583 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
584 case TLS_RSA_WITH_NULL_SHA256:
585 case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
586 case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
587 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
588 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
589 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
590 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
591 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
592 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
593 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
594 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
595 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
596 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2 &&
597 vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
598
599 /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and
600 * point formats.*/
601 case TLS_ECDH_ECDSA_WITH_NULL_SHA:
602 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
603 case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
604 case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
605 case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
606 case TLS_ECDHE_ECDSA_WITH_NULL_SHA:
607 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
608 case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
609 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
610 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
611 case TLS_ECDH_RSA_WITH_NULL_SHA:
612 case TLS_ECDH_RSA_WITH_RC4_128_SHA:
613 case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
614 case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
615 case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
616 case TLS_ECDHE_RSA_WITH_NULL_SHA:
617 case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
618 case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
619 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
620 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
621 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0 &&
622 vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
623
624 case TLS_AES_128_GCM_SHA256:
625 case TLS_AES_256_GCM_SHA384:
626 case TLS_CHACHA20_POLY1305_SHA256:
627 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_3;
628
629 default:
630 return vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
631 }
632 }
633
634 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */
635 /* XXX This does a linear search. A binary search would be better. */
636 const ssl3CipherSuiteDef *
ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)637 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
638 {
639 int cipher_suite_def_len =
640 sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
641 int i;
642
643 for (i = 0; i < cipher_suite_def_len; i++) {
644 if (cipher_suite_defs[i].cipher_suite == suite)
645 return &cipher_suite_defs[i];
646 }
647 PORT_Assert(PR_FALSE); /* We should never get here. */
648 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
649 return NULL;
650 }
651
652 /* Find the cipher configuration struct associate with suite */
653 /* XXX This does a linear search. A binary search would be better. */
654 static ssl3CipherSuiteCfg *
ssl_LookupCipherSuiteCfgMutable(ssl3CipherSuite suite,ssl3CipherSuiteCfg * suites)655 ssl_LookupCipherSuiteCfgMutable(ssl3CipherSuite suite,
656 ssl3CipherSuiteCfg *suites)
657 {
658 int i;
659
660 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
661 if (suites[i].cipher_suite == suite)
662 return &suites[i];
663 }
664 /* return NULL and let the caller handle it. */
665 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
666 return NULL;
667 }
668
669 const ssl3CipherSuiteCfg *
ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite,const ssl3CipherSuiteCfg * suites)670 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, const ssl3CipherSuiteCfg *suites)
671 {
672 return ssl_LookupCipherSuiteCfgMutable(suite,
673 CONST_CAST(ssl3CipherSuiteCfg, suites));
674 }
675
676 static PRBool
ssl_NamedGroupTypeEnabled(const sslSocket * ss,SSLKEAType keaType)677 ssl_NamedGroupTypeEnabled(const sslSocket *ss, SSLKEAType keaType)
678 {
679 unsigned int i;
680 for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
681 if (ss->namedGroupPreferences[i] &&
682 ss->namedGroupPreferences[i]->keaType == keaType) {
683 return PR_TRUE;
684 }
685 }
686 return PR_FALSE;
687 }
688
689 static PRBool
ssl_KEAEnabled(const sslSocket * ss,SSLKEAType keaType)690 ssl_KEAEnabled(const sslSocket *ss, SSLKEAType keaType)
691 {
692 switch (keaType) {
693 case ssl_kea_rsa:
694 return PR_TRUE;
695
696 case ssl_kea_dh:
697 case ssl_kea_dh_psk: {
698 if (ss->sec.isServer && !ss->opt.enableServerDhe) {
699 return PR_FALSE;
700 }
701
702 if (ss->sec.isServer) {
703 /* If the server requires named FFDHE groups, then the client
704 * must have included an FFDHE group. peerSupportsFfdheGroups
705 * is set to true in ssl_HandleSupportedGroupsXtn(). */
706 if (ss->opt.requireDHENamedGroups &&
707 !ss->xtnData.peerSupportsFfdheGroups) {
708 return PR_FALSE;
709 }
710
711 /* We can use the weak DH group if all of these are true:
712 * 1. We don't require named groups.
713 * 2. The peer doesn't support named groups.
714 * 3. This isn't TLS 1.3.
715 * 4. The weak group is enabled. */
716 if (!ss->opt.requireDHENamedGroups &&
717 !ss->xtnData.peerSupportsFfdheGroups &&
718 ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
719 ss->ssl3.dheWeakGroupEnabled) {
720 return PR_TRUE;
721 }
722 } else {
723 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
724 !ss->opt.requireDHENamedGroups) {
725 /* The client enables DHE cipher suites even if no DHE groups
726 * are enabled. Only if this isn't TLS 1.3 and named groups
727 * are not required. */
728 return PR_TRUE;
729 }
730 }
731 return ssl_NamedGroupTypeEnabled(ss, ssl_kea_dh);
732 }
733
734 case ssl_kea_ecdh:
735 case ssl_kea_ecdh_psk:
736 return ssl_NamedGroupTypeEnabled(ss, ssl_kea_ecdh);
737
738 case ssl_kea_tls13_any:
739 return PR_TRUE;
740
741 case ssl_kea_fortezza:
742 default:
743 PORT_Assert(0);
744 }
745 return PR_FALSE;
746 }
747
748 static PRBool
ssl_HasCert(const sslSocket * ss,PRUint16 maxVersion,SSLAuthType authType)749 ssl_HasCert(const sslSocket *ss, PRUint16 maxVersion, SSLAuthType authType)
750 {
751 PRCList *cursor;
752 if (authType == ssl_auth_null || authType == ssl_auth_psk || authType == ssl_auth_tls13_any) {
753 return PR_TRUE;
754 }
755 for (cursor = PR_NEXT_LINK(&ss->serverCerts);
756 cursor != &ss->serverCerts;
757 cursor = PR_NEXT_LINK(cursor)) {
758 sslServerCert *cert = (sslServerCert *)cursor;
759 if (!cert->serverKeyPair ||
760 !cert->serverKeyPair->privKey ||
761 !cert->serverCertChain ||
762 !SSL_CERT_IS(cert, authType)) {
763 continue;
764 }
765 /* When called from ssl3_config_match_init(), all the EC curves will be
766 * enabled, so this will essentially do nothing (unless we implement
767 * curve configuration). However, once we have seen the
768 * supported_groups extension and this is called from config_match(),
769 * this will filter out certificates with an unsupported curve.
770 *
771 * If we might negotiate TLS 1.3, skip this test as group configuration
772 * doesn't affect choices in TLS 1.3.
773 */
774 if (maxVersion < SSL_LIBRARY_VERSION_TLS_1_3 &&
775 (authType == ssl_auth_ecdsa ||
776 authType == ssl_auth_ecdh_ecdsa ||
777 authType == ssl_auth_ecdh_rsa) &&
778 !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
779 continue;
780 }
781 return PR_TRUE;
782 }
783 if (authType == ssl_auth_rsa_sign) {
784 return ssl_HasCert(ss, maxVersion, ssl_auth_rsa_pss);
785 }
786 return PR_FALSE;
787 }
788
789 /* return true if the scheme is allowed by policy, This prevents
790 * failures later when our actual signatures are rejected by
791 * policy by either ssl code, or lower level NSS code */
792 static PRBool
ssl_SchemePolicyOK(SSLSignatureScheme scheme,PRUint32 require)793 ssl_SchemePolicyOK(SSLSignatureScheme scheme, PRUint32 require)
794 {
795 /* Hash policy. */
796 PRUint32 policy;
797 SECOidTag hashOID = ssl3_HashTypeToOID(ssl_SignatureSchemeToHashType(scheme));
798 SECOidTag sigOID;
799
800 /* policy bits needed to enable a SignatureScheme */
801 SECStatus rv = NSS_GetAlgorithmPolicy(hashOID, &policy);
802 if (rv == SECSuccess &&
803 (policy & require) != require) {
804 return PR_FALSE;
805 }
806
807 /* ssl_SignatureSchemeToAuthType reports rsa for rsa_pss_rsae, but we
808 * actually implement pss signatures when we sign, so just use RSA_PSS
809 * for all RSA PSS Siganture schemes */
810 if (ssl_IsRsaPssSignatureScheme(scheme)) {
811 sigOID = SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
812 } else {
813 sigOID = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme));
814 }
815 /* Signature Policy. */
816 rv = NSS_GetAlgorithmPolicy(sigOID, &policy);
817 if (rv == SECSuccess &&
818 (policy & require) != require) {
819 return PR_FALSE;
820 }
821 return PR_TRUE;
822 }
823
824 /* Check that a signature scheme is accepted.
825 * Both by policy and by having a token that supports it. */
826 static PRBool
ssl_SignatureSchemeAccepted(PRUint16 minVersion,SSLSignatureScheme scheme,PRBool forCert)827 ssl_SignatureSchemeAccepted(PRUint16 minVersion,
828 SSLSignatureScheme scheme,
829 PRBool forCert)
830 {
831 /* Disable RSA-PSS schemes if there are no tokens to verify them. */
832 if (ssl_IsRsaPssSignatureScheme(scheme)) {
833 if (!PK11_TokenExists(auth_alg_defs[ssl_auth_rsa_pss])) {
834 return PR_FALSE;
835 }
836 } else if (!forCert && ssl_IsRsaPkcs1SignatureScheme(scheme)) {
837 /* Disable PKCS#1 signatures if we are limited to TLS 1.3.
838 * We still need to advertise PKCS#1 signatures in CH and CR
839 * for certificate signatures.
840 */
841 if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_3) {
842 return PR_FALSE;
843 }
844 } else if (ssl_IsDsaSignatureScheme(scheme)) {
845 /* DSA: not in TLS 1.3, and check policy. */
846 if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_3) {
847 return PR_FALSE;
848 }
849 }
850
851 return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy);
852 }
853
854 static SECStatus
ssl_CheckSignatureSchemes(sslSocket * ss)855 ssl_CheckSignatureSchemes(sslSocket *ss)
856 {
857 if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_2) {
858 return SECSuccess;
859 }
860
861 /* If this is a server using TLS 1.3, we just need to have one signature
862 * scheme for which we have a usable certificate.
863 *
864 * Note: Certificates for earlier TLS versions are checked along with the
865 * cipher suite in ssl3_config_match_init. */
866 if (ss->sec.isServer && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
867 PRBool foundCert = PR_FALSE;
868 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
869 SSLAuthType authType =
870 ssl_SignatureSchemeToAuthType(ss->ssl3.signatureSchemes[i]);
871 if (ssl_HasCert(ss, ss->vrange.max, authType)) {
872 foundCert = PR_TRUE;
873 break;
874 }
875 }
876 if (!foundCert) {
877 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
878 return SECFailure;
879 }
880 }
881
882 /* Ensure that there is a signature scheme that can be accepted.*/
883 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
884 if (ssl_SignatureSchemeAccepted(ss->vrange.min,
885 ss->ssl3.signatureSchemes[i],
886 PR_FALSE /* forCert */)) {
887 return SECSuccess;
888 }
889 }
890 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
891 return SECFailure;
892 }
893
894 /* For a server, check that a signature scheme that can be used with the
895 * provided authType is both enabled and usable. */
896 static PRBool
ssl_HasSignatureScheme(const sslSocket * ss,SSLAuthType authType)897 ssl_HasSignatureScheme(const sslSocket *ss, SSLAuthType authType)
898 {
899 PORT_Assert(ss->sec.isServer);
900 PORT_Assert(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version);
901 PORT_Assert(authType != ssl_auth_null);
902 PORT_Assert(authType != ssl_auth_tls13_any);
903 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2 ||
904 authType == ssl_auth_rsa_decrypt ||
905 authType == ssl_auth_ecdh_rsa ||
906 authType == ssl_auth_ecdh_ecdsa) {
907 return PR_TRUE;
908 }
909 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
910 SSLSignatureScheme scheme = ss->ssl3.signatureSchemes[i];
911 SSLAuthType schemeAuthType = ssl_SignatureSchemeToAuthType(scheme);
912 PRBool acceptable = authType == schemeAuthType ||
913 (schemeAuthType == ssl_auth_rsa_pss &&
914 authType == ssl_auth_rsa_sign);
915 if (acceptable && ssl_SignatureSchemeAccepted(ss->version, scheme, PR_FALSE /* forCert */)) {
916 return PR_TRUE;
917 }
918 }
919 return PR_FALSE;
920 }
921
922 /* Initialize the suite->isPresent value for config_match
923 * Returns count of enabled ciphers supported by extant tokens,
924 * regardless of policy or user preference.
925 * If this returns zero, the user cannot do SSL v3.
926 */
927 unsigned int
ssl3_config_match_init(sslSocket * ss)928 ssl3_config_match_init(sslSocket *ss)
929 {
930 ssl3CipherSuiteCfg *suite;
931 const ssl3CipherSuiteDef *cipher_def;
932 SSLCipherAlgorithm cipher_alg;
933 CK_MECHANISM_TYPE cipher_mech;
934 SSLAuthType authType;
935 SSLKEAType keaType;
936 unsigned int i;
937 unsigned int numPresent = 0;
938 unsigned int numEnabled = 0;
939
940 PORT_Assert(ss);
941 if (!ss) {
942 PORT_SetError(SEC_ERROR_INVALID_ARGS);
943 return 0;
944 }
945 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
946 return 0;
947 }
948 if (ss->sec.isServer && ss->psk &&
949 PR_CLIST_IS_EMPTY(&ss->serverCerts) &&
950 (ss->opt.requestCertificate || ss->opt.requireCertificate)) {
951 /* PSK and certificate auth cannot be combined. */
952 PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
953 return 0;
954 }
955 if (ssl_CheckSignatureSchemes(ss) != SECSuccess) {
956 return 0; /* Code already set. */
957 }
958
959 ssl_FilterSupportedGroups(ss);
960 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
961 suite = &ss->cipherSuites[i];
962 if (suite->enabled) {
963 ++numEnabled;
964 /* We need the cipher defs to see if we have a token that can handle
965 * this cipher. It isn't part of the static definition.
966 */
967 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
968 if (!cipher_def) {
969 suite->isPresent = PR_FALSE;
970 continue;
971 }
972 cipher_alg = ssl_GetBulkCipherDef(cipher_def)->calg;
973 cipher_mech = ssl3_Alg2Mech(cipher_alg);
974
975 /* Mark the suites that are backed by real tokens, certs and keys */
976 suite->isPresent = PR_TRUE;
977
978 authType = kea_defs[cipher_def->key_exchange_alg].authKeyType;
979 if (authType != ssl_auth_null && authType != ssl_auth_tls13_any) {
980 if (ss->sec.isServer &&
981 !(ssl_HasCert(ss, ss->vrange.max, authType) &&
982 ssl_HasSignatureScheme(ss, authType))) {
983 suite->isPresent = PR_FALSE;
984 } else if (!PK11_TokenExists(auth_alg_defs[authType])) {
985 suite->isPresent = PR_FALSE;
986 }
987 }
988
989 keaType = kea_defs[cipher_def->key_exchange_alg].exchKeyType;
990 if (keaType != ssl_kea_null &&
991 keaType != ssl_kea_tls13_any &&
992 !PK11_TokenExists(kea_alg_defs[keaType])) {
993 suite->isPresent = PR_FALSE;
994 }
995
996 if (cipher_alg != ssl_calg_null &&
997 !PK11_TokenExists(cipher_mech)) {
998 suite->isPresent = PR_FALSE;
999 }
1000
1001 if (suite->isPresent) {
1002 ++numPresent;
1003 }
1004 }
1005 }
1006 PORT_Assert(numPresent > 0 || numEnabled == 0);
1007 if (numPresent == 0) {
1008 PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
1009 }
1010 return numPresent;
1011 }
1012
1013 /* Return PR_TRUE if suite is usable. This if the suite is permitted by policy,
1014 * enabled, has a certificate (as needed), has a viable key agreement method, is
1015 * usable with the negotiated TLS version, and is otherwise usable. */
1016 PRBool
ssl3_config_match(const ssl3CipherSuiteCfg * suite,PRUint8 policy,const SSLVersionRange * vrange,const sslSocket * ss)1017 ssl3_config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy,
1018 const SSLVersionRange *vrange, const sslSocket *ss)
1019 {
1020 const ssl3CipherSuiteDef *cipher_def;
1021 const ssl3KEADef *kea_def;
1022
1023 if (!suite) {
1024 PORT_Assert(suite);
1025 return PR_FALSE;
1026 }
1027
1028 PORT_Assert(policy != SSL_NOT_ALLOWED);
1029 if (policy == SSL_NOT_ALLOWED)
1030 return PR_FALSE;
1031
1032 if (!suite->enabled || !suite->isPresent)
1033 return PR_FALSE;
1034
1035 if ((suite->policy == SSL_NOT_ALLOWED) ||
1036 (suite->policy > policy))
1037 return PR_FALSE;
1038
1039 PORT_Assert(ss != NULL);
1040 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
1041 PORT_Assert(cipher_def != NULL);
1042 kea_def = &kea_defs[cipher_def->key_exchange_alg];
1043 PORT_Assert(kea_def != NULL);
1044 if (!ssl_KEAEnabled(ss, kea_def->exchKeyType)) {
1045 return PR_FALSE;
1046 }
1047
1048 if (ss->sec.isServer && !ssl_HasCert(ss, vrange->max, kea_def->authKeyType)) {
1049 return PR_FALSE;
1050 }
1051
1052 /* If a PSK is selected, disable suites that use a different hash than
1053 * the PSK. We advertise non-PSK-compatible suites in the CH, as we could
1054 * fallback to certificate auth. The client handler will check hash
1055 * compatibility before committing to use the PSK. */
1056 if (ss->xtnData.selectedPsk) {
1057 if (ss->xtnData.selectedPsk->hash != cipher_def->prf_hash) {
1058 return PR_FALSE;
1059 }
1060 }
1061
1062 return ssl3_CipherSuiteAllowedForVersionRange(suite->cipher_suite, vrange);
1063 }
1064
1065 /* For TLS 1.3, when resuming, check for a ciphersuite that is both compatible
1066 * with the identified ciphersuite and enabled. */
1067 static PRBool
tls13_ResumptionCompatible(sslSocket * ss,ssl3CipherSuite suite)1068 tls13_ResumptionCompatible(sslSocket *ss, ssl3CipherSuite suite)
1069 {
1070 SSLVersionRange vrange = { SSL_LIBRARY_VERSION_TLS_1_3,
1071 SSL_LIBRARY_VERSION_TLS_1_3 };
1072 SSLHashType hash = tls13_GetHashForCipherSuite(suite);
1073 for (unsigned int i = 0; i < PR_ARRAY_SIZE(cipher_suite_defs); i++) {
1074 if (cipher_suite_defs[i].prf_hash == hash) {
1075 const ssl3CipherSuiteCfg *suiteCfg =
1076 ssl_LookupCipherSuiteCfg(cipher_suite_defs[i].cipher_suite,
1077 ss->cipherSuites);
1078 if (suite && ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) {
1079 return PR_TRUE;
1080 }
1081 }
1082 }
1083 return PR_FALSE;
1084 }
1085
1086 /*
1087 * Null compression, mac and encryption functions
1088 */
1089 SECStatus
Null_Cipher(void * ctx,unsigned char * output,unsigned int * outputLen,unsigned int maxOutputLen,const unsigned char * input,unsigned int inputLen)1090 Null_Cipher(void *ctx, unsigned char *output, unsigned int *outputLen, unsigned int maxOutputLen,
1091 const unsigned char *input, unsigned int inputLen)
1092 {
1093 if (inputLen > maxOutputLen) {
1094 *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */
1095 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
1096 return SECFailure;
1097 }
1098 *outputLen = inputLen;
1099 if (inputLen > 0 && input != output) {
1100 PORT_Memcpy(output, input, inputLen);
1101 }
1102 return SECSuccess;
1103 }
1104
1105 /*
1106 * SSL3 Utility functions
1107 */
1108
1109 static void
ssl_SetSpecVersions(sslSocket * ss,ssl3CipherSpec * spec)1110 ssl_SetSpecVersions(sslSocket *ss, ssl3CipherSpec *spec)
1111 {
1112 spec->version = ss->version;
1113 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
1114 tls13_SetSpecRecordVersion(ss, spec);
1115 } else if (IS_DTLS(ss)) {
1116 spec->recordVersion = dtls_TLSVersionToDTLSVersion(ss->version);
1117 } else {
1118 spec->recordVersion = ss->version;
1119 }
1120 }
1121
1122 /* allowLargerPeerVersion controls whether the function will select the
1123 * highest enabled SSL version or fail when peerVersion is greater than the
1124 * highest enabled version.
1125 *
1126 * If allowLargerPeerVersion is true, peerVersion is the peer's highest
1127 * enabled version rather than the peer's selected version.
1128 */
1129 SECStatus
ssl3_NegotiateVersion(sslSocket * ss,SSL3ProtocolVersion peerVersion,PRBool allowLargerPeerVersion)1130 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
1131 PRBool allowLargerPeerVersion)
1132 {
1133 SSL3ProtocolVersion negotiated;
1134
1135 /* Prevent negotiating to a lower version in response to a TLS 1.3 HRR. */
1136 if (ss->ssl3.hs.helloRetry) {
1137 PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
1138 return SECFailure;
1139 }
1140
1141 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
1142 PORT_SetError(SSL_ERROR_SSL_DISABLED);
1143 return SECFailure;
1144 }
1145
1146 if (peerVersion < ss->vrange.min ||
1147 (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
1148 PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
1149 return SECFailure;
1150 }
1151
1152 negotiated = PR_MIN(peerVersion, ss->vrange.max);
1153 PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, negotiated));
1154 if (ss->firstHsDone && ss->version != negotiated) {
1155 PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
1156 return SECFailure;
1157 }
1158
1159 ss->version = negotiated;
1160 return SECSuccess;
1161 }
1162
1163 /* Used by the client when the server produces a version number.
1164 * This reads, validates, and normalizes the value. */
1165 SECStatus
ssl_ClientReadVersion(sslSocket * ss,PRUint8 ** b,unsigned int * len,SSL3ProtocolVersion * version)1166 ssl_ClientReadVersion(sslSocket *ss, PRUint8 **b, unsigned int *len,
1167 SSL3ProtocolVersion *version)
1168 {
1169 SSL3ProtocolVersion v;
1170 PRUint32 temp;
1171 SECStatus rv;
1172
1173 rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, b, len);
1174 if (rv != SECSuccess) {
1175 return SECFailure; /* alert has been sent */
1176 }
1177 v = (SSL3ProtocolVersion)temp;
1178
1179 if (IS_DTLS(ss)) {
1180 v = dtls_DTLSVersionToTLSVersion(v);
1181 /* Check for failure. */
1182 if (!v || v > SSL_LIBRARY_VERSION_MAX_SUPPORTED) {
1183 SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
1184 return SECFailure;
1185 }
1186 }
1187
1188 /* You can't negotiate TLS 1.3 this way. */
1189 if (v >= SSL_LIBRARY_VERSION_TLS_1_3) {
1190 SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
1191 return SECFailure;
1192 }
1193 *version = v;
1194 return SECSuccess;
1195 }
1196
1197 SECStatus
ssl3_GetNewRandom(SSL3Random random)1198 ssl3_GetNewRandom(SSL3Random random)
1199 {
1200 SECStatus rv;
1201
1202 rv = PK11_GenerateRandom(random, SSL3_RANDOM_LENGTH);
1203 if (rv != SECSuccess) {
1204 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
1205 }
1206 return rv;
1207 }
1208
1209 SECStatus
ssl3_SignHashesWithPrivKey(SSL3Hashes * hash,SECKEYPrivateKey * key,SSLSignatureScheme scheme,PRBool isTls,SECItem * buf)1210 ssl3_SignHashesWithPrivKey(SSL3Hashes *hash, SECKEYPrivateKey *key,
1211 SSLSignatureScheme scheme, PRBool isTls, SECItem *buf)
1212 {
1213 SECStatus rv = SECFailure;
1214 PRBool doDerEncode = PR_FALSE;
1215 PRBool useRsaPss = ssl_IsRsaPssSignatureScheme(scheme);
1216 SECItem hashItem;
1217
1218 buf->data = NULL;
1219
1220 switch (SECKEY_GetPrivateKeyType(key)) {
1221 case rsaKey:
1222 hashItem.data = hash->u.raw;
1223 hashItem.len = hash->len;
1224 break;
1225 case dsaKey:
1226 doDerEncode = isTls;
1227 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1228 * In that case, we use just the SHA1 part. */
1229 if (hash->hashAlg == ssl_hash_none) {
1230 hashItem.data = hash->u.s.sha;
1231 hashItem.len = sizeof(hash->u.s.sha);
1232 } else {
1233 hashItem.data = hash->u.raw;
1234 hashItem.len = hash->len;
1235 }
1236 break;
1237 case ecKey:
1238 doDerEncode = PR_TRUE;
1239 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1240 * In that case, we use just the SHA1 part. */
1241 if (hash->hashAlg == ssl_hash_none) {
1242 hashItem.data = hash->u.s.sha;
1243 hashItem.len = sizeof(hash->u.s.sha);
1244 } else {
1245 hashItem.data = hash->u.raw;
1246 hashItem.len = hash->len;
1247 }
1248 break;
1249 default:
1250 PORT_SetError(SEC_ERROR_INVALID_KEY);
1251 goto done;
1252 }
1253 PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
1254
1255 if (useRsaPss || hash->hashAlg == ssl_hash_none) {
1256 CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1257 int signatureLen = PK11_SignatureLen(key);
1258
1259 SECItem *params = NULL;
1260 CK_RSA_PKCS_PSS_PARAMS pssParams;
1261 SECItem pssParamsItem = { siBuffer,
1262 (unsigned char *)&pssParams,
1263 sizeof(pssParams) };
1264
1265 if (signatureLen <= 0) {
1266 PORT_SetError(SEC_ERROR_INVALID_KEY);
1267 goto done;
1268 }
1269
1270 buf->len = (unsigned)signatureLen;
1271 buf->data = (unsigned char *)PORT_Alloc(signatureLen);
1272 if (!buf->data)
1273 goto done; /* error code was set. */
1274
1275 if (useRsaPss) {
1276 pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1277 pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1278 pssParams.sLen = hashItem.len;
1279 params = &pssParamsItem;
1280 mech = CKM_RSA_PKCS_PSS;
1281 }
1282
1283 rv = PK11_SignWithMechanism(key, mech, params, buf, &hashItem);
1284 } else {
1285 SECOidTag hashOID = ssl3_HashTypeToOID(hash->hashAlg);
1286 rv = SGN_Digest(key, hashOID, buf, &hashItem);
1287 }
1288 if (rv != SECSuccess) {
1289 ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
1290 } else if (doDerEncode) {
1291 SECItem derSig = { siBuffer, NULL, 0 };
1292
1293 /* This also works for an ECDSA signature */
1294 rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
1295 if (rv == SECSuccess) {
1296 PORT_Free(buf->data); /* discard unencoded signature. */
1297 *buf = derSig; /* give caller encoded signature. */
1298 } else if (derSig.data) {
1299 PORT_Free(derSig.data);
1300 }
1301 }
1302
1303 PRINT_BUF(60, (NULL, "signed hashes", (unsigned char *)buf->data, buf->len));
1304 done:
1305 if (rv != SECSuccess && buf->data) {
1306 PORT_Free(buf->data);
1307 buf->data = NULL;
1308 }
1309 return rv;
1310 }
1311
1312 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
1313 SECStatus
ssl3_SignHashes(sslSocket * ss,SSL3Hashes * hash,SECKEYPrivateKey * key,SECItem * buf)1314 ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash, SECKEYPrivateKey *key,
1315 SECItem *buf)
1316 {
1317 SECStatus rv = SECFailure;
1318 PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
1319 SSLSignatureScheme scheme = ss->ssl3.hs.signatureScheme;
1320
1321 rv = ssl3_SignHashesWithPrivKey(hash, key, scheme, isTLS, buf);
1322 if (rv != SECSuccess) {
1323 return SECFailure;
1324 }
1325
1326 if (ss->sec.isServer) {
1327 ss->sec.signatureScheme = scheme;
1328 ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
1329 }
1330
1331 return SECSuccess;
1332 }
1333
1334 /* Called from ssl3_VerifySignedHashes and tls13_HandleCertificateVerify. */
1335 SECStatus
ssl_VerifySignedHashesWithPubKey(sslSocket * ss,SECKEYPublicKey * key,SSLSignatureScheme scheme,SSL3Hashes * hash,SECItem * buf)1336 ssl_VerifySignedHashesWithPubKey(sslSocket *ss, SECKEYPublicKey *key,
1337 SSLSignatureScheme scheme,
1338 SSL3Hashes *hash, SECItem *buf)
1339 {
1340 SECItem *signature = NULL;
1341 SECStatus rv = SECFailure;
1342 SECItem hashItem;
1343 SECOidTag encAlg;
1344 SECOidTag hashAlg;
1345 void *pwArg = ss->pkcs11PinArg;
1346 PRBool isRsaPssScheme = ssl_IsRsaPssSignatureScheme(scheme);
1347
1348 PRINT_BUF(60, (NULL, "check signed hashes", buf->data, buf->len));
1349
1350 hashAlg = ssl3_HashTypeToOID(hash->hashAlg);
1351 switch (SECKEY_GetPublicKeyType(key)) {
1352 case rsaKey:
1353 encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
1354 hashItem.data = hash->u.raw;
1355 hashItem.len = hash->len;
1356 if (scheme == ssl_sig_none) {
1357 scheme = ssl_sig_rsa_pkcs1_sha1md5;
1358 }
1359 break;
1360 case dsaKey:
1361 encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
1362 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1363 * In that case, we use just the SHA1 part. */
1364 if (hash->hashAlg == ssl_hash_none) {
1365 hashItem.data = hash->u.s.sha;
1366 hashItem.len = sizeof(hash->u.s.sha);
1367 } else {
1368 hashItem.data = hash->u.raw;
1369 hashItem.len = hash->len;
1370 }
1371 /* Allow DER encoded DSA signatures in SSL 3.0 */
1372 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0 ||
1373 buf->len != SECKEY_SignatureLen(key)) {
1374 signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key));
1375 if (!signature) {
1376 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1377 goto loser;
1378 }
1379 buf = signature;
1380 }
1381 if (scheme == ssl_sig_none) {
1382 scheme = ssl_sig_dsa_sha1;
1383 }
1384 break;
1385
1386 case ecKey:
1387 encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
1388 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1389 * In that case, we use just the SHA1 part.
1390 * ECDSA signatures always encode the integers r and s using ASN.1
1391 * (unlike DSA where ASN.1 encoding is used with TLS but not with
1392 * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
1393 */
1394 if (hash->hashAlg == ssl_hash_none) {
1395 hashAlg = SEC_OID_SHA1;
1396 hashItem.data = hash->u.s.sha;
1397 hashItem.len = sizeof(hash->u.s.sha);
1398 } else {
1399 hashItem.data = hash->u.raw;
1400 hashItem.len = hash->len;
1401 }
1402 if (scheme == ssl_sig_none) {
1403 scheme = ssl_sig_ecdsa_sha1;
1404 }
1405 break;
1406
1407 default:
1408 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
1409 goto loser;
1410 }
1411
1412 PRINT_BUF(60, (NULL, "hash(es) to be verified",
1413 hashItem.data, hashItem.len));
1414
1415 if (isRsaPssScheme ||
1416 hashAlg == SEC_OID_UNKNOWN ||
1417 SECKEY_GetPublicKeyType(key) == dsaKey) {
1418 /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1419 * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1420 * above always removes the DER encoding of DSA signatures when
1421 * present. Thus DSA signatures are always verified with PK11_Verify.
1422 */
1423 CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1424
1425 SECItem *params = NULL;
1426 CK_RSA_PKCS_PSS_PARAMS pssParams;
1427 SECItem pssParamsItem = { siBuffer,
1428 (unsigned char *)&pssParams,
1429 sizeof(pssParams) };
1430
1431 if (isRsaPssScheme) {
1432 pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1433 pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1434 pssParams.sLen = hashItem.len;
1435 params = &pssParamsItem;
1436 mech = CKM_RSA_PKCS_PSS;
1437 }
1438
1439 rv = PK11_VerifyWithMechanism(key, mech, params, buf, &hashItem, pwArg);
1440 } else {
1441 rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
1442 pwArg);
1443 }
1444 if (signature) {
1445 SECITEM_FreeItem(signature, PR_TRUE);
1446 }
1447 if (rv != SECSuccess) {
1448 ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1449 }
1450 if (!ss->sec.isServer) {
1451 ss->sec.signatureScheme = scheme;
1452 ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
1453 }
1454
1455 loser:
1456 #ifdef UNSAFE_FUZZER_MODE
1457 rv = SECSuccess;
1458 PORT_SetError(0);
1459 #endif
1460 return rv;
1461 }
1462
1463 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
1464 SECStatus
ssl3_VerifySignedHashes(sslSocket * ss,SSLSignatureScheme scheme,SSL3Hashes * hash,SECItem * buf)1465 ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme, SSL3Hashes *hash,
1466 SECItem *buf)
1467 {
1468 SECKEYPublicKey *pubKey =
1469 SECKEY_ExtractPublicKey(&ss->sec.peerCert->subjectPublicKeyInfo);
1470 if (pubKey == NULL) {
1471 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
1472 return SECFailure;
1473 }
1474 SECStatus rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, scheme,
1475 hash, buf);
1476 SECKEY_DestroyPublicKey(pubKey);
1477 return rv;
1478 }
1479
1480 /* Caller must set hiLevel error code. */
1481 /* Called from ssl3_ComputeDHKeyHash
1482 * which are called from ssl3_HandleServerKeyExchange.
1483 *
1484 * hashAlg: ssl_hash_none indicates the pre-1.2, MD5/SHA1 combination hash.
1485 */
1486 SECStatus
ssl3_ComputeCommonKeyHash(SSLHashType hashAlg,PRUint8 * hashBuf,unsigned int bufLen,SSL3Hashes * hashes)1487 ssl3_ComputeCommonKeyHash(SSLHashType hashAlg,
1488 PRUint8 *hashBuf, unsigned int bufLen,
1489 SSL3Hashes *hashes)
1490 {
1491 SECStatus rv;
1492 SECOidTag hashOID;
1493 PRUint32 policy;
1494
1495 if (hashAlg == ssl_hash_none) {
1496 if ((NSS_GetAlgorithmPolicy(SEC_OID_SHA1, &policy) == SECSuccess) &&
1497 !(policy & NSS_USE_ALG_IN_SSL_KX)) {
1498 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1499 return SECFailure;
1500 }
1501 rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen);
1502 if (rv != SECSuccess) {
1503 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
1504 return rv;
1505 }
1506 rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen);
1507 if (rv != SECSuccess) {
1508 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
1509 return rv;
1510 }
1511 hashes->len = MD5_LENGTH + SHA1_LENGTH;
1512 } else {
1513 hashOID = ssl3_HashTypeToOID(hashAlg);
1514 if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) &&
1515 !(policy & NSS_USE_ALG_IN_SSL_KX)) {
1516 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1517 return SECFailure;
1518 }
1519 hashes->len = HASH_ResultLenByOidTag(hashOID);
1520 if (hashes->len == 0 || hashes->len > sizeof(hashes->u.raw)) {
1521 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1522 return SECFailure;
1523 }
1524 rv = PK11_HashBuf(hashOID, hashes->u.raw, hashBuf, bufLen);
1525 if (rv != SECSuccess) {
1526 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
1527 return rv;
1528 }
1529 }
1530 hashes->hashAlg = hashAlg;
1531 return SECSuccess;
1532 }
1533
1534 /* Caller must set hiLevel error code. */
1535 /* Called from ssl3_HandleServerKeyExchange. */
1536 static SECStatus
ssl3_ComputeDHKeyHash(sslSocket * ss,SSLHashType hashAlg,SSL3Hashes * hashes,SECItem dh_p,SECItem dh_g,SECItem dh_Ys,PRBool padY)1537 ssl3_ComputeDHKeyHash(sslSocket *ss, SSLHashType hashAlg, SSL3Hashes *hashes,
1538 SECItem dh_p, SECItem dh_g, SECItem dh_Ys, PRBool padY)
1539 {
1540 sslBuffer buf = SSL_BUFFER_EMPTY;
1541 SECStatus rv;
1542 unsigned int yLen;
1543 unsigned int i;
1544
1545 PORT_Assert(dh_p.data);
1546 PORT_Assert(dh_g.data);
1547 PORT_Assert(dh_Ys.data);
1548
1549 rv = sslBuffer_Append(&buf, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
1550 if (rv != SECSuccess) {
1551 goto loser;
1552 }
1553 rv = sslBuffer_Append(&buf, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
1554 if (rv != SECSuccess) {
1555 goto loser;
1556 }
1557 /* p */
1558 rv = sslBuffer_AppendVariable(&buf, dh_p.data, dh_p.len, 2);
1559 if (rv != SECSuccess) {
1560 goto loser;
1561 }
1562 /* g */
1563 rv = sslBuffer_AppendVariable(&buf, dh_g.data, dh_g.len, 2);
1564 if (rv != SECSuccess) {
1565 goto loser;
1566 }
1567 /* y - complicated by padding */
1568 yLen = padY ? dh_p.len : dh_Ys.len;
1569 rv = sslBuffer_AppendNumber(&buf, yLen, 2);
1570 if (rv != SECSuccess) {
1571 goto loser;
1572 }
1573 /* If we're padding Y, dh_Ys can't be longer than dh_p. */
1574 PORT_Assert(!padY || dh_p.len >= dh_Ys.len);
1575 for (i = dh_Ys.len; i < yLen; ++i) {
1576 rv = sslBuffer_AppendNumber(&buf, 0, 1);
1577 if (rv != SECSuccess) {
1578 goto loser;
1579 }
1580 }
1581 rv = sslBuffer_Append(&buf, dh_Ys.data, dh_Ys.len);
1582 if (rv != SECSuccess) {
1583 goto loser;
1584 }
1585
1586 rv = ssl3_ComputeCommonKeyHash(hashAlg, SSL_BUFFER_BASE(&buf),
1587 SSL_BUFFER_LEN(&buf), hashes);
1588 if (rv != SECSuccess) {
1589 goto loser;
1590 }
1591
1592 PRINT_BUF(95, (NULL, "DHkey hash: ", SSL_BUFFER_BASE(&buf),
1593 SSL_BUFFER_LEN(&buf)));
1594 if (hashAlg == ssl_hash_none) {
1595 PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",
1596 hashes->u.s.md5, MD5_LENGTH));
1597 PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",
1598 hashes->u.s.sha, SHA1_LENGTH));
1599 } else {
1600 PRINT_BUF(95, (NULL, "DHkey hash: result",
1601 hashes->u.raw, hashes->len));
1602 }
1603
1604 sslBuffer_Clear(&buf);
1605 return SECSuccess;
1606
1607 loser:
1608 sslBuffer_Clear(&buf);
1609 return SECFailure;
1610 }
1611
1612 static SECStatus
ssl3_SetupPendingCipherSpec(sslSocket * ss,SSLSecretDirection direction,const ssl3CipherSuiteDef * suiteDef,ssl3CipherSpec ** specp)1613 ssl3_SetupPendingCipherSpec(sslSocket *ss, SSLSecretDirection direction,
1614 const ssl3CipherSuiteDef *suiteDef,
1615 ssl3CipherSpec **specp)
1616 {
1617 ssl3CipherSpec *spec;
1618 const ssl3CipherSpec *prev;
1619
1620 prev = (direction == ssl_secret_write) ? ss->ssl3.cwSpec : ss->ssl3.crSpec;
1621 if (prev->epoch == PR_UINT16_MAX) {
1622 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
1623 return SECFailure;
1624 }
1625
1626 spec = ssl_CreateCipherSpec(ss, direction);
1627 if (!spec) {
1628 return SECFailure;
1629 }
1630
1631 spec->cipherDef = ssl_GetBulkCipherDef(suiteDef);
1632 spec->macDef = ssl_GetMacDef(ss, suiteDef);
1633
1634 spec->epoch = prev->epoch + 1;
1635 spec->nextSeqNum = 0;
1636 if (IS_DTLS(ss) && direction == ssl_secret_read) {
1637 dtls_InitRecvdRecords(&spec->recvdRecords);
1638 }
1639 ssl_SetSpecVersions(ss, spec);
1640
1641 ssl_SaveCipherSpec(ss, spec);
1642 *specp = spec;
1643 return SECSuccess;
1644 }
1645
1646 /* Fill in the pending cipher spec with info from the selected ciphersuite.
1647 ** This is as much initialization as we can do without having key material.
1648 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1649 ** Caller must hold the ssl3 handshake lock.
1650 ** Acquires & releases SpecWriteLock.
1651 */
1652 SECStatus
ssl3_SetupBothPendingCipherSpecs(sslSocket * ss)1653 ssl3_SetupBothPendingCipherSpecs(sslSocket *ss)
1654 {
1655 ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
1656 SSL3KeyExchangeAlgorithm kea;
1657 const ssl3CipherSuiteDef *suiteDef;
1658 SECStatus rv;
1659
1660 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1661 PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
1662
1663 ssl_GetSpecWriteLock(ss); /*******************************/
1664
1665 /* This hack provides maximal interoperability with SSL 3 servers. */
1666 if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
1667 /* SSL records are not being MACed. */
1668 ss->ssl3.cwSpec->version = ss->version;
1669 }
1670
1671 SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1672 SSL_GETPID(), ss->fd, suite));
1673
1674 suiteDef = ssl_LookupCipherSuiteDef(suite);
1675 if (suiteDef == NULL) {
1676 goto loser;
1677 }
1678
1679 if (IS_DTLS(ss)) {
1680 /* Double-check that we did not pick an RC4 suite */
1681 PORT_Assert(suiteDef->bulk_cipher_alg != cipher_rc4);
1682 }
1683
1684 ss->ssl3.hs.suite_def = suiteDef;
1685
1686 kea = suiteDef->key_exchange_alg;
1687 ss->ssl3.hs.kea_def = &kea_defs[kea];
1688 PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
1689
1690 rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_read, suiteDef,
1691 &ss->ssl3.prSpec);
1692 if (rv != SECSuccess) {
1693 goto loser;
1694 }
1695 rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_write, suiteDef,
1696 &ss->ssl3.pwSpec);
1697 if (rv != SECSuccess) {
1698 goto loser;
1699 }
1700
1701 if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) {
1702 ss->ssl3.prSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,
1703 ss->opt.recordSizeLimit);
1704 ss->ssl3.pwSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,
1705 ss->xtnData.recordSizeLimit);
1706 }
1707
1708 ssl_ReleaseSpecWriteLock(ss); /*******************************/
1709 return SECSuccess;
1710
1711 loser:
1712 ssl_ReleaseSpecWriteLock(ss);
1713 return SECFailure;
1714 }
1715
1716 /* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data which
1717 * is included in the MAC or AEAD additional data) to |buf|. See
1718 * https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the definition of the
1719 * AEAD additional data.
1720 *
1721 * TLS pseudo-header includes the record's version field, SSL's doesn't. Which
1722 * pseudo-header definition to use should be decided based on the version of
1723 * the protocol that was negotiated when the cipher spec became current, NOT
1724 * based on the version value in the record itself, and the decision is passed
1725 * to this function as the |includesVersion| argument. But, the |version|
1726 * argument should be the record's version value.
1727 */
1728 static SECStatus
ssl3_BuildRecordPseudoHeader(DTLSEpoch epoch,sslSequenceNumber seqNum,SSLContentType ct,PRBool includesVersion,SSL3ProtocolVersion version,PRBool isDTLS,int length,sslBuffer * buf)1729 ssl3_BuildRecordPseudoHeader(DTLSEpoch epoch,
1730 sslSequenceNumber seqNum,
1731 SSLContentType ct,
1732 PRBool includesVersion,
1733 SSL3ProtocolVersion version,
1734 PRBool isDTLS,
1735 int length,
1736 sslBuffer *buf)
1737 {
1738 SECStatus rv;
1739 if (isDTLS) {
1740 rv = sslBuffer_AppendNumber(buf, epoch, 2);
1741 if (rv != SECSuccess) {
1742 return SECFailure;
1743 }
1744 rv = sslBuffer_AppendNumber(buf, seqNum, 6);
1745 } else {
1746 rv = sslBuffer_AppendNumber(buf, seqNum, 8);
1747 }
1748 if (rv != SECSuccess) {
1749 return SECFailure;
1750 }
1751 rv = sslBuffer_AppendNumber(buf, ct, 1);
1752 if (rv != SECSuccess) {
1753 return SECFailure;
1754 }
1755
1756 /* SSL3 MAC doesn't include the record's version field. */
1757 if (includesVersion) {
1758 /* TLS MAC and AEAD additional data include version. */
1759 rv = sslBuffer_AppendNumber(buf, version, 2);
1760 if (rv != SECSuccess) {
1761 return SECFailure;
1762 }
1763 }
1764 rv = sslBuffer_AppendNumber(buf, length, 2);
1765 if (rv != SECSuccess) {
1766 return SECFailure;
1767 }
1768
1769 return SECSuccess;
1770 }
1771
1772 /* Initialize encryption and MAC contexts for pending spec.
1773 * Master Secret already is derived.
1774 * Caller holds Spec write lock.
1775 */
1776 static SECStatus
ssl3_InitPendingContexts(sslSocket * ss,ssl3CipherSpec * spec)1777 ssl3_InitPendingContexts(sslSocket *ss, ssl3CipherSpec *spec)
1778 {
1779 CK_MECHANISM_TYPE encMechanism;
1780 CK_ATTRIBUTE_TYPE encMode;
1781 SECItem macParam;
1782 CK_ULONG macLength;
1783 SECItem iv;
1784 SSLCipherAlgorithm calg;
1785
1786 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1787 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1788
1789 calg = spec->cipherDef->calg;
1790 PORT_Assert(alg2Mech[calg].calg == calg);
1791
1792 if (spec->cipherDef->type != type_aead) {
1793 macLength = spec->macDef->mac_size;
1794
1795 /*
1796 ** Now setup the MAC contexts,
1797 ** crypto contexts are setup below.
1798 */
1799 macParam.data = (unsigned char *)&macLength;
1800 macParam.len = sizeof(macLength);
1801 macParam.type = siBuffer;
1802
1803 spec->keyMaterial.macContext = PK11_CreateContextBySymKey(
1804 spec->macDef->mmech, CKA_SIGN, spec->keyMaterial.macKey, &macParam);
1805 if (!spec->keyMaterial.macContext) {
1806 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1807 return SECFailure;
1808 }
1809 }
1810
1811 /*
1812 ** Now setup the crypto contexts.
1813 */
1814 if (calg == ssl_calg_null) {
1815 spec->cipher = Null_Cipher;
1816 return SECSuccess;
1817 }
1818
1819 encMechanism = ssl3_Alg2Mech(calg);
1820 encMode = (spec->direction == ssl_secret_write) ? CKA_ENCRYPT : CKA_DECRYPT;
1821 if (spec->cipherDef->type == type_aead) {
1822 encMode |= CKA_NSS_MESSAGE;
1823 iv.data = NULL;
1824 iv.len = 0;
1825 } else {
1826 spec->cipher = (SSLCipher)PK11_CipherOp;
1827 iv.data = spec->keyMaterial.iv;
1828 iv.len = spec->cipherDef->iv_size;
1829 }
1830
1831 /*
1832 * build the context
1833 */
1834 spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode,
1835 spec->keyMaterial.key,
1836 &iv);
1837 if (!spec->cipherContext) {
1838 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1839 return SECFailure;
1840 }
1841
1842 return SECSuccess;
1843 }
1844
1845 /* Complete the initialization of all keys, ciphers, MACs and their contexts
1846 * for the pending Cipher Spec.
1847 * Called from: ssl3_SendClientKeyExchange (for Full handshake)
1848 * ssl3_HandleRSAClientKeyExchange (for Full handshake)
1849 * ssl3_HandleServerHello (for session restart)
1850 * ssl3_HandleClientHello (for session restart)
1851 * Sets error code, but caller probably should override to disambiguate.
1852 *
1853 * If |secret| is a master secret from a previous connection is reused, |derive|
1854 * is PR_FALSE. If the secret is a pre-master secret, then |derive| is PR_TRUE
1855 * and the master secret is derived from |secret|.
1856 */
1857 SECStatus
ssl3_InitPendingCipherSpecs(sslSocket * ss,PK11SymKey * secret,PRBool derive)1858 ssl3_InitPendingCipherSpecs(sslSocket *ss, PK11SymKey *secret, PRBool derive)
1859 {
1860 PK11SymKey *masterSecret;
1861 ssl3CipherSpec *pwSpec;
1862 ssl3CipherSpec *prSpec;
1863 SECStatus rv;
1864
1865 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1866 PORT_Assert(secret);
1867
1868 ssl_GetSpecWriteLock(ss); /**************************************/
1869
1870 PORT_Assert(ss->ssl3.pwSpec);
1871 PORT_Assert(ss->ssl3.cwSpec->epoch == ss->ssl3.crSpec->epoch);
1872 prSpec = ss->ssl3.prSpec;
1873 pwSpec = ss->ssl3.pwSpec;
1874
1875 if (ss->ssl3.cwSpec->epoch == PR_UINT16_MAX) {
1876 /* The problem here is that we have rehandshaked too many
1877 * times (you are not allowed to wrap the epoch). The
1878 * spec says you should be discarding the connection
1879 * and start over, so not much we can do here. */
1880 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1881 goto loser;
1882 }
1883
1884 if (derive) {
1885 rv = ssl3_ComputeMasterSecret(ss, secret, &masterSecret);
1886 if (rv != SECSuccess) {
1887 goto loser;
1888 }
1889 } else {
1890 masterSecret = secret;
1891 }
1892
1893 PORT_Assert(masterSecret);
1894 rv = ssl3_DeriveConnectionKeys(ss, masterSecret);
1895 if (rv != SECSuccess) {
1896 if (derive) {
1897 /* masterSecret was created here. */
1898 PK11_FreeSymKey(masterSecret);
1899 }
1900 goto loser;
1901 }
1902
1903 /* Both cipher specs maintain a reference to the master secret, since each
1904 * is managed and freed independently. */
1905 prSpec->masterSecret = masterSecret;
1906 pwSpec->masterSecret = PK11_ReferenceSymKey(masterSecret);
1907 rv = ssl3_InitPendingContexts(ss, ss->ssl3.prSpec);
1908 if (rv != SECSuccess) {
1909 goto loser;
1910 }
1911
1912 rv = ssl3_InitPendingContexts(ss, ss->ssl3.pwSpec);
1913 if (rv != SECSuccess) {
1914 goto loser;
1915 }
1916
1917 ssl_ReleaseSpecWriteLock(ss); /******************************/
1918 return SECSuccess;
1919
1920 loser:
1921 ssl_ReleaseSpecWriteLock(ss); /******************************/
1922 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
1923 return SECFailure;
1924 }
1925
1926 /*
1927 * 60 bytes is 3 times the maximum length MAC size that is supported.
1928 */
1929 static const unsigned char mac_pad_1[60] = {
1930 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1931 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1932 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1933 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1934 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1935 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1936 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1937 0x36, 0x36, 0x36, 0x36
1938 };
1939 static const unsigned char mac_pad_2[60] = {
1940 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1941 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1942 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1943 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1944 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1945 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1946 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1947 0x5c, 0x5c, 0x5c, 0x5c
1948 };
1949
1950 /* Called from: ssl3_SendRecord()
1951 ** Caller must already hold the SpecReadLock. (wish we could assert that!)
1952 */
1953 static SECStatus
ssl3_ComputeRecordMAC(ssl3CipherSpec * spec,const unsigned char * header,unsigned int headerLen,const PRUint8 * input,int inputLen,unsigned char * outbuf,unsigned int * outLen)1954 ssl3_ComputeRecordMAC(
1955 ssl3CipherSpec *spec,
1956 const unsigned char *header,
1957 unsigned int headerLen,
1958 const PRUint8 *input,
1959 int inputLen,
1960 unsigned char *outbuf,
1961 unsigned int *outLen)
1962 {
1963 PK11Context *context;
1964 int macSize = spec->macDef->mac_size;
1965 SECStatus rv;
1966
1967 PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen));
1968 PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLen));
1969
1970 if (spec->macDef->mac == ssl_mac_null) {
1971 *outLen = 0;
1972 return SECSuccess;
1973 }
1974
1975 context = spec->keyMaterial.macContext;
1976 rv = PK11_DigestBegin(context);
1977 rv |= PK11_DigestOp(context, header, headerLen);
1978 rv |= PK11_DigestOp(context, input, inputLen);
1979 rv |= PK11_DigestFinal(context, outbuf, outLen, macSize);
1980 PORT_Assert(rv != SECSuccess || *outLen == (unsigned)macSize);
1981
1982 PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLen));
1983
1984 if (rv != SECSuccess) {
1985 rv = SECFailure;
1986 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
1987 }
1988 return rv;
1989 }
1990
1991 /* Called from: ssl3_HandleRecord()
1992 * Caller must already hold the SpecReadLock. (wish we could assert that!)
1993 *
1994 * On entry:
1995 * originalLen >= inputLen >= MAC size
1996 */
1997 static SECStatus
ssl3_ComputeRecordMACConstantTime(ssl3CipherSpec * spec,const unsigned char * header,unsigned int headerLen,const PRUint8 * input,int inputLen,int originalLen,unsigned char * outbuf,unsigned int * outLen)1998 ssl3_ComputeRecordMACConstantTime(
1999 ssl3CipherSpec *spec,
2000 const unsigned char *header,
2001 unsigned int headerLen,
2002 const PRUint8 *input,
2003 int inputLen,
2004 int originalLen,
2005 unsigned char *outbuf,
2006 unsigned int *outLen)
2007 {
2008 CK_MECHANISM_TYPE macType;
2009 CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
2010 SECItem param, inputItem, outputItem;
2011 int macSize = spec->macDef->mac_size;
2012 SECStatus rv;
2013
2014 PORT_Assert(inputLen >= spec->macDef->mac_size);
2015 PORT_Assert(originalLen >= inputLen);
2016
2017 if (spec->macDef->mac == ssl_mac_null) {
2018 *outLen = 0;
2019 return SECSuccess;
2020 }
2021
2022 macType = CKM_NSS_HMAC_CONSTANT_TIME;
2023 if (spec->version == SSL_LIBRARY_VERSION_3_0) {
2024 macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME;
2025 }
2026
2027 params.macAlg = spec->macDef->mmech;
2028 params.ulBodyTotalLen = originalLen;
2029 params.pHeader = (unsigned char *)header; /* const cast */
2030 params.ulHeaderLen = headerLen;
2031
2032 param.data = (unsigned char *)¶ms;
2033 param.len = sizeof(params);
2034 param.type = 0;
2035
2036 inputItem.data = (unsigned char *)input;
2037 inputItem.len = inputLen;
2038 inputItem.type = 0;
2039
2040 outputItem.data = outbuf;
2041 outputItem.len = *outLen;
2042 outputItem.type = 0;
2043
2044 rv = PK11_SignWithSymKey(spec->keyMaterial.macKey, macType, ¶m,
2045 &outputItem, &inputItem);
2046 if (rv != SECSuccess) {
2047 if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) {
2048 /* ssl3_ComputeRecordMAC() expects the MAC to have been removed
2049 * from the input length already. */
2050 return ssl3_ComputeRecordMAC(spec, header, headerLen,
2051 input, inputLen - macSize,
2052 outbuf, outLen);
2053 }
2054
2055 *outLen = 0;
2056 rv = SECFailure;
2057 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2058 return rv;
2059 }
2060
2061 PORT_Assert(outputItem.len == (unsigned)macSize);
2062 *outLen = outputItem.len;
2063
2064 return rv;
2065 }
2066
2067 static PRBool
ssl3_ClientAuthTokenPresent(sslSessionID * sid)2068 ssl3_ClientAuthTokenPresent(sslSessionID *sid)
2069 {
2070 PK11SlotInfo *slot = NULL;
2071 PRBool isPresent = PR_TRUE;
2072
2073 /* we only care if we are doing client auth */
2074 if (!sid || !sid->u.ssl3.clAuthValid) {
2075 return PR_TRUE;
2076 }
2077
2078 /* get the slot */
2079 slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
2080 sid->u.ssl3.clAuthSlotID);
2081 if (slot == NULL ||
2082 !PK11_IsPresent(slot) ||
2083 sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) ||
2084 sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) ||
2085 sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) ||
2086 (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
2087 isPresent = PR_FALSE;
2088 }
2089 if (slot) {
2090 PK11_FreeSlot(slot);
2091 }
2092 return isPresent;
2093 }
2094
2095 /* Caller must hold the spec read lock. */
2096 SECStatus
ssl3_MACEncryptRecord(ssl3CipherSpec * cwSpec,PRBool isServer,PRBool isDTLS,SSLContentType ct,const PRUint8 * pIn,PRUint32 contentLen,sslBuffer * wrBuf)2097 ssl3_MACEncryptRecord(ssl3CipherSpec *cwSpec,
2098 PRBool isServer,
2099 PRBool isDTLS,
2100 SSLContentType ct,
2101 const PRUint8 *pIn,
2102 PRUint32 contentLen,
2103 sslBuffer *wrBuf)
2104 {
2105 SECStatus rv;
2106 PRUint32 macLen = 0;
2107 PRUint32 fragLen;
2108 PRUint32 p1Len, p2Len, oddLen = 0;
2109 unsigned int ivLen = 0;
2110 unsigned char pseudoHeaderBuf[13];
2111 sslBuffer pseudoHeader = SSL_BUFFER(pseudoHeaderBuf);
2112 unsigned int len;
2113
2114 if (cwSpec->cipherDef->type == type_block &&
2115 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
2116 /* Prepend the per-record explicit IV using technique 2b from
2117 * RFC 4346 section 6.2.3.2: The IV is a cryptographically
2118 * strong random number XORed with the CBC residue from the previous
2119 * record.
2120 */
2121 ivLen = cwSpec->cipherDef->iv_size;
2122 if (ivLen > SSL_BUFFER_SPACE(wrBuf)) {
2123 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2124 return SECFailure;
2125 }
2126 rv = PK11_GenerateRandom(SSL_BUFFER_NEXT(wrBuf), ivLen);
2127 if (rv != SECSuccess) {
2128 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
2129 return rv;
2130 }
2131 rv = cwSpec->cipher(cwSpec->cipherContext,
2132 SSL_BUFFER_NEXT(wrBuf), /* output */
2133 &len, /* outlen */
2134 ivLen, /* max outlen */
2135 SSL_BUFFER_NEXT(wrBuf), /* input */
2136 ivLen); /* input len */
2137 if (rv != SECSuccess || len != ivLen) {
2138 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2139 return SECFailure;
2140 }
2141
2142 rv = sslBuffer_Skip(wrBuf, len, NULL);
2143 PORT_Assert(rv == SECSuccess); /* Can't fail. */
2144 }
2145
2146 rv = ssl3_BuildRecordPseudoHeader(
2147 cwSpec->epoch, cwSpec->nextSeqNum, ct,
2148 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->recordVersion,
2149 isDTLS, contentLen, &pseudoHeader);
2150 PORT_Assert(rv == SECSuccess);
2151 if (cwSpec->cipherDef->type == type_aead) {
2152 const unsigned int nonceLen = cwSpec->cipherDef->explicit_nonce_size;
2153 const unsigned int tagLen = cwSpec->cipherDef->tag_size;
2154 unsigned int ivOffset = 0;
2155 CK_GENERATOR_FUNCTION gen;
2156 /* ivOut includes the iv and the nonce and is the internal iv/nonce
2157 * for the AEAD function. On Encrypt, this is an in/out parameter */
2158 unsigned char ivOut[MAX_IV_LENGTH];
2159 ivLen = cwSpec->cipherDef->iv_size;
2160
2161 PORT_Assert((ivLen + nonceLen) <= MAX_IV_LENGTH);
2162 PORT_Assert((ivLen + nonceLen) >= sizeof(sslSequenceNumber));
2163
2164 if (nonceLen + contentLen + tagLen > SSL_BUFFER_SPACE(wrBuf)) {
2165 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2166 return SECFailure;
2167 }
2168
2169 if (nonceLen == 0) {
2170 ivOffset = ivLen - sizeof(sslSequenceNumber);
2171 gen = CKG_GENERATE_COUNTER_XOR;
2172 } else {
2173 ivOffset = ivLen;
2174 gen = CKG_GENERATE_COUNTER;
2175 }
2176 ivOffset = tls13_SetupAeadIv(isDTLS, ivOut, cwSpec->keyMaterial.iv,
2177 ivOffset, ivLen, cwSpec->epoch);
2178 rv = tls13_AEAD(cwSpec->cipherContext,
2179 PR_FALSE,
2180 gen, ivOffset * BPB, /* iv generator params */
2181 ivOut, /* iv in */
2182 ivOut, /* iv out */
2183 ivLen + nonceLen, /* full iv length */
2184 NULL, 0, /* nonce is generated*/
2185 SSL_BUFFER_BASE(&pseudoHeader), /* aad */
2186 SSL_BUFFER_LEN(&pseudoHeader), /* aadlen */
2187 SSL_BUFFER_NEXT(wrBuf) + nonceLen, /* output */
2188 &len, /* out len */
2189 SSL_BUFFER_SPACE(wrBuf) - nonceLen, /* max out */
2190 tagLen,
2191 pIn, contentLen); /* input */
2192 if (rv != SECSuccess) {
2193 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2194 return SECFailure;
2195 }
2196 len += nonceLen; /* include the nonce at the beginning */
2197 /* copy out the generated iv if we are using explict nonces */
2198 if (nonceLen) {
2199 PORT_Memcpy(SSL_BUFFER_NEXT(wrBuf), ivOut + ivLen, nonceLen);
2200 }
2201
2202 rv = sslBuffer_Skip(wrBuf, len, NULL);
2203 PORT_Assert(rv == SECSuccess); /* Can't fail. */
2204 } else {
2205 int blockSize = cwSpec->cipherDef->block_size;
2206
2207 /*
2208 * Add the MAC
2209 */
2210 rv = ssl3_ComputeRecordMAC(cwSpec, SSL_BUFFER_BASE(&pseudoHeader),
2211 SSL_BUFFER_LEN(&pseudoHeader),
2212 pIn, contentLen,
2213 SSL_BUFFER_NEXT(wrBuf) + contentLen, &macLen);
2214 if (rv != SECSuccess) {
2215 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2216 return SECFailure;
2217 }
2218 p1Len = contentLen;
2219 p2Len = macLen;
2220 fragLen = contentLen + macLen; /* needs to be encrypted */
2221 PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
2222
2223 /*
2224 * Pad the text (if we're doing a block cipher)
2225 * then Encrypt it
2226 */
2227 if (cwSpec->cipherDef->type == type_block) {
2228 unsigned char *pBuf;
2229 int padding_length;
2230 int i;
2231
2232 oddLen = contentLen % blockSize;
2233 /* Assume blockSize is a power of two */
2234 padding_length = blockSize - 1 - ((fragLen) & (blockSize - 1));
2235 fragLen += padding_length + 1;
2236 PORT_Assert((fragLen % blockSize) == 0);
2237
2238 /* Pad according to TLS rules (also acceptable to SSL3). */
2239 pBuf = SSL_BUFFER_NEXT(wrBuf) + fragLen - 1;
2240 for (i = padding_length + 1; i > 0; --i) {
2241 *pBuf-- = padding_length;
2242 }
2243 /* now, if contentLen is not a multiple of block size, fix it */
2244 p2Len = fragLen - p1Len;
2245 }
2246 if (p1Len < 256) {
2247 oddLen = p1Len;
2248 p1Len = 0;
2249 } else {
2250 p1Len -= oddLen;
2251 }
2252 if (oddLen) {
2253 p2Len += oddLen;
2254 PORT_Assert((blockSize < 2) ||
2255 (p2Len % blockSize) == 0);
2256 memmove(SSL_BUFFER_NEXT(wrBuf) + p1Len, pIn + p1Len, oddLen);
2257 }
2258 if (p1Len > 0) {
2259 unsigned int cipherBytesPart1 = 0;
2260 rv = cwSpec->cipher(cwSpec->cipherContext,
2261 SSL_BUFFER_NEXT(wrBuf), /* output */
2262 &cipherBytesPart1, /* actual outlen */
2263 p1Len, /* max outlen */
2264 pIn,
2265 p1Len); /* input, and inputlen */
2266 PORT_Assert(rv == SECSuccess && cipherBytesPart1 == p1Len);
2267 if (rv != SECSuccess || cipherBytesPart1 != p1Len) {
2268 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2269 return SECFailure;
2270 }
2271 rv = sslBuffer_Skip(wrBuf, p1Len, NULL);
2272 PORT_Assert(rv == SECSuccess);
2273 }
2274 if (p2Len > 0) {
2275 unsigned int cipherBytesPart2 = 0;
2276 rv = cwSpec->cipher(cwSpec->cipherContext,
2277 SSL_BUFFER_NEXT(wrBuf),
2278 &cipherBytesPart2, /* output and actual outLen */
2279 p2Len, /* max outlen */
2280 SSL_BUFFER_NEXT(wrBuf),
2281 p2Len); /* input and inputLen*/
2282 PORT_Assert(rv == SECSuccess && cipherBytesPart2 == p2Len);
2283 if (rv != SECSuccess || cipherBytesPart2 != p2Len) {
2284 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2285 return SECFailure;
2286 }
2287 rv = sslBuffer_Skip(wrBuf, p2Len, NULL);
2288 PORT_Assert(rv == SECSuccess);
2289 }
2290 }
2291
2292 return SECSuccess;
2293 }
2294
2295 /* Note: though this can report failure, it shouldn't. */
2296 SECStatus
ssl_InsertRecordHeader(const sslSocket * ss,ssl3CipherSpec * cwSpec,SSLContentType contentType,sslBuffer * wrBuf,PRBool * needsLength)2297 ssl_InsertRecordHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec,
2298 SSLContentType contentType, sslBuffer *wrBuf,
2299 PRBool *needsLength)
2300 {
2301 SECStatus rv;
2302
2303 #ifndef UNSAFE_FUZZER_MODE
2304 if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
2305 cwSpec->epoch > TrafficKeyClearText) {
2306 if (IS_DTLS(ss)) {
2307 return dtls13_InsertCipherTextHeader(ss, cwSpec, wrBuf,
2308 needsLength);
2309 }
2310 contentType = ssl_ct_application_data;
2311 }
2312 #endif
2313 rv = sslBuffer_AppendNumber(wrBuf, contentType, 1);
2314 if (rv != SECSuccess) {
2315 return SECFailure;
2316 }
2317
2318 rv = sslBuffer_AppendNumber(wrBuf, cwSpec->recordVersion, 2);
2319 if (rv != SECSuccess) {
2320 return SECFailure;
2321 }
2322 if (IS_DTLS(ss)) {
2323 rv = sslBuffer_AppendNumber(wrBuf, cwSpec->epoch, 2);
2324 if (rv != SECSuccess) {
2325 return SECFailure;
2326 }
2327 rv = sslBuffer_AppendNumber(wrBuf, cwSpec->nextSeqNum, 6);
2328 if (rv != SECSuccess) {
2329 return SECFailure;
2330 }
2331 }
2332 *needsLength = PR_TRUE;
2333 return SECSuccess;
2334 }
2335
2336 SECStatus
ssl_ProtectRecord(sslSocket * ss,ssl3CipherSpec * cwSpec,SSLContentType ct,const PRUint8 * pIn,PRUint32 contentLen,sslBuffer * wrBuf)2337 ssl_ProtectRecord(sslSocket *ss, ssl3CipherSpec *cwSpec, SSLContentType ct,
2338 const PRUint8 *pIn, PRUint32 contentLen, sslBuffer *wrBuf)
2339 {
2340 PRBool needsLength;
2341 unsigned int lenOffset;
2342 SECStatus rv;
2343
2344 PORT_Assert(cwSpec->direction == ssl_secret_write);
2345 PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
2346 PORT_Assert(cwSpec->cipherDef->max_records <= RECORD_SEQ_MAX);
2347
2348 if (cwSpec->nextSeqNum >= cwSpec->cipherDef->max_records) {
2349 PORT_Assert(cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_3);
2350 SSL_TRC(3, ("%d: SSL[-]: write sequence number at limit 0x%0llx",
2351 SSL_GETPID(), cwSpec->nextSeqNum));
2352 PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
2353 return SECFailure;
2354 }
2355
2356 rv = ssl_InsertRecordHeader(ss, cwSpec, ct, wrBuf, &needsLength);
2357 if (rv != SECSuccess) {
2358 return SECFailure;
2359 }
2360 if (needsLength) {
2361 rv = sslBuffer_Skip(wrBuf, 2, &lenOffset);
2362 if (rv != SECSuccess) {
2363 return SECFailure;
2364 }
2365 }
2366
2367 #ifdef UNSAFE_FUZZER_MODE
2368 {
2369 unsigned int len;
2370 rv = Null_Cipher(NULL, SSL_BUFFER_NEXT(wrBuf), &len,
2371 SSL_BUFFER_SPACE(wrBuf), pIn, contentLen);
2372 if (rv != SECSuccess) {
2373 return SECFailure; /* error was set */
2374 }
2375 rv = sslBuffer_Skip(wrBuf, len, NULL);
2376 PORT_Assert(rv == SECSuccess); /* Can't fail. */
2377 }
2378 #else
2379 if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
2380 PRUint8 *cipherText = SSL_BUFFER_NEXT(wrBuf);
2381 unsigned int bufLen = SSL_BUFFER_LEN(wrBuf);
2382 rv = tls13_ProtectRecord(ss, cwSpec, ct, pIn, contentLen, wrBuf);
2383 if (rv != SECSuccess) {
2384 return SECFailure;
2385 }
2386 if (IS_DTLS(ss)) {
2387 bufLen = SSL_BUFFER_LEN(wrBuf) - bufLen;
2388 rv = dtls13_MaskSequenceNumber(ss, cwSpec,
2389 SSL_BUFFER_BASE(wrBuf),
2390 cipherText, bufLen);
2391 }
2392 } else {
2393 rv = ssl3_MACEncryptRecord(cwSpec, ss->sec.isServer, IS_DTLS(ss), ct,
2394 pIn, contentLen, wrBuf);
2395 }
2396 #endif
2397 if (rv != SECSuccess) {
2398 return SECFailure; /* error was set */
2399 }
2400
2401 if (needsLength) {
2402 /* Insert the length. */
2403 rv = sslBuffer_InsertLength(wrBuf, lenOffset, 2);
2404 if (rv != SECSuccess) {
2405 PORT_Assert(0); /* Can't fail. */
2406 return SECFailure;
2407 }
2408 }
2409
2410 ++cwSpec->nextSeqNum;
2411 return SECSuccess;
2412 }
2413
2414 SECStatus
ssl_ProtectNextRecord(sslSocket * ss,ssl3CipherSpec * spec,SSLContentType ct,const PRUint8 * pIn,unsigned int nIn,unsigned int * written)2415 ssl_ProtectNextRecord(sslSocket *ss, ssl3CipherSpec *spec, SSLContentType ct,
2416 const PRUint8 *pIn, unsigned int nIn,
2417 unsigned int *written)
2418 {
2419 sslBuffer *wrBuf = &ss->sec.writeBuf;
2420 unsigned int contentLen;
2421 unsigned int spaceNeeded;
2422 SECStatus rv;
2423
2424 contentLen = PR_MIN(nIn, spec->recordSizeLimit);
2425 spaceNeeded = contentLen + SSL3_BUFFER_FUDGE;
2426 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
2427 spec->cipherDef->type == type_block) {
2428 spaceNeeded += spec->cipherDef->iv_size;
2429 }
2430 if (spaceNeeded > SSL_BUFFER_SPACE(wrBuf)) {
2431 rv = sslBuffer_Grow(wrBuf, spaceNeeded);
2432 if (rv != SECSuccess) {
2433 SSL_DBG(("%d: SSL3[%d]: failed to expand write buffer to %d",
2434 SSL_GETPID(), ss->fd, spaceNeeded));
2435 return SECFailure;
2436 }
2437 }
2438
2439 rv = ssl_ProtectRecord(ss, spec, ct, pIn, contentLen, wrBuf);
2440 if (rv != SECSuccess) {
2441 return SECFailure;
2442 }
2443 PRINT_BUF(50, (ss, "send (encrypted) record data:",
2444 SSL_BUFFER_BASE(wrBuf), SSL_BUFFER_LEN(wrBuf)));
2445 *written = contentLen;
2446 return SECSuccess;
2447 }
2448
2449 /* Process the plain text before sending it.
2450 * Returns the number of bytes of plaintext that were successfully sent
2451 * plus the number of bytes of plaintext that were copied into the
2452 * output (write) buffer.
2453 * Returns -1 on an error. PR_WOULD_BLOCK_ERROR is set if the error is blocking
2454 * and not terminal.
2455 *
2456 * Notes on the use of the private ssl flags:
2457 * (no private SSL flags)
2458 * Attempt to make and send SSL records for all plaintext
2459 * If non-blocking and a send gets WOULD_BLOCK,
2460 * or if the pending (ciphertext) buffer is not empty,
2461 * then buffer remaining bytes of ciphertext into pending buf,
2462 * and continue to do that for all succssive records until all
2463 * bytes are used.
2464 * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2465 * As above, except this suppresses all write attempts, and forces
2466 * all ciphertext into the pending ciphertext buffer.
2467 * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
2468 * Forces the use of the provided epoch
2469 */
2470 PRInt32
ssl3_SendRecord(sslSocket * ss,ssl3CipherSpec * cwSpec,SSLContentType ct,const PRUint8 * pIn,PRInt32 nIn,PRInt32 flags)2471 ssl3_SendRecord(sslSocket *ss,
2472 ssl3CipherSpec *cwSpec, /* non-NULL for DTLS retransmits */
2473 SSLContentType ct,
2474 const PRUint8 *pIn, /* input buffer */
2475 PRInt32 nIn, /* bytes of input */
2476 PRInt32 flags)
2477 {
2478 sslBuffer *wrBuf = &ss->sec.writeBuf;
2479 ssl3CipherSpec *spec;
2480 SECStatus rv;
2481 PRInt32 totalSent = 0;
2482
2483 SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
2484 SSL_GETPID(), ss->fd, ssl3_DecodeContentType(ct),
2485 nIn));
2486 PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn));
2487
2488 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2489 PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
2490
2491 if (ss->ssl3.fatalAlertSent) {
2492 SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent",
2493 SSL_GETPID(), ss->fd));
2494 if (ct != ssl_ct_alert) {
2495 /* If we are sending an alert, then we already have an
2496 * error, so don't overwrite. */
2497 PORT_SetError(SSL_ERROR_HANDSHAKE_FAILED);
2498 }
2499 return -1;
2500 }
2501
2502 /* check for Token Presence */
2503 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
2504 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
2505 return -1;
2506 }
2507
2508 if (ss->recordWriteCallback) {
2509 PRUint16 epoch;
2510 ssl_GetSpecReadLock(ss);
2511 epoch = ss->ssl3.cwSpec->epoch;
2512 ssl_ReleaseSpecReadLock(ss);
2513 rv = ss->recordWriteCallback(ss->fd, epoch, ct, pIn, nIn,
2514 ss->recordWriteCallbackArg);
2515 if (rv != SECSuccess) {
2516 return -1;
2517 }
2518 return nIn;
2519 }
2520
2521 if (cwSpec) {
2522 /* cwSpec can only be set for retransmissions of the DTLS handshake. */
2523 PORT_Assert(IS_DTLS(ss) &&
2524 (ct == ssl_ct_handshake ||
2525 ct == ssl_ct_change_cipher_spec));
2526 spec = cwSpec;
2527 } else {
2528 spec = ss->ssl3.cwSpec;
2529 }
2530
2531 while (nIn > 0) {
2532 unsigned int written = 0;
2533 PRInt32 sent;
2534
2535 ssl_GetSpecReadLock(ss);
2536 rv = ssl_ProtectNextRecord(ss, spec, ct, pIn, nIn, &written);
2537 ssl_ReleaseSpecReadLock(ss);
2538 if (rv != SECSuccess) {
2539 goto loser;
2540 }
2541
2542 PORT_Assert(written > 0);
2543 /* DTLS should not fragment non-application data here. */
2544 if (IS_DTLS(ss) && ct != ssl_ct_application_data) {
2545 PORT_Assert(written == nIn);
2546 }
2547
2548 pIn += written;
2549 nIn -= written;
2550 PORT_Assert(nIn >= 0);
2551
2552 /* If there's still some previously saved ciphertext,
2553 * or the caller doesn't want us to send the data yet,
2554 * then add all our new ciphertext to the amount previously saved.
2555 */
2556 if ((ss->pendingBuf.len > 0) ||
2557 (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2558
2559 rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf),
2560 SSL_BUFFER_LEN(wrBuf));
2561 if (rv != SECSuccess) {
2562 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2563 goto loser;
2564 }
2565
2566 if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2567 ss->handshakeBegun = 1;
2568 sent = ssl_SendSavedWriteData(ss);
2569 if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2570 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2571 goto loser;
2572 }
2573 if (ss->pendingBuf.len) {
2574 flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2575 }
2576 }
2577 } else {
2578 PORT_Assert(SSL_BUFFER_LEN(wrBuf) > 0);
2579 ss->handshakeBegun = 1;
2580 sent = ssl_DefSend(ss, SSL_BUFFER_BASE(wrBuf),
2581 SSL_BUFFER_LEN(wrBuf),
2582 flags & ~ssl_SEND_FLAG_MASK);
2583 if (sent < 0) {
2584 if (PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
2585 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2586 goto loser;
2587 }
2588 /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
2589 sent = 0;
2590 }
2591 if (SSL_BUFFER_LEN(wrBuf) > (unsigned int)sent) {
2592 if (IS_DTLS(ss)) {
2593 /* DTLS just says no in this case. No buffering */
2594 PORT_SetError(PR_WOULD_BLOCK_ERROR);
2595 goto loser;
2596 }
2597 /* now take all the remaining unsent new ciphertext and
2598 * append it to the buffer of previously unsent ciphertext.
2599 */
2600 rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf) + sent,
2601 SSL_BUFFER_LEN(wrBuf) - sent);
2602 if (rv != SECSuccess) {
2603 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2604 goto loser;
2605 }
2606 }
2607 }
2608 wrBuf->len = 0;
2609 totalSent += written;
2610 }
2611 return totalSent;
2612
2613 loser:
2614 /* Don't leave bits of buffer lying around. */
2615 wrBuf->len = 0;
2616 return -1;
2617 }
2618
2619 #define SSL3_PENDING_HIGH_WATER 1024
2620
2621 /* Attempt to send the content of "in" in an SSL application_data record.
2622 * Returns "len" or -1 on failure.
2623 */
2624 int
ssl3_SendApplicationData(sslSocket * ss,const unsigned char * in,PRInt32 len,PRInt32 flags)2625 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
2626 PRInt32 len, PRInt32 flags)
2627 {
2628 PRInt32 totalSent = 0;
2629 PRInt32 discarded = 0;
2630 PRBool splitNeeded = PR_FALSE;
2631
2632 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2633 /* These flags for internal use only */
2634 PORT_Assert(!(flags & ssl_SEND_FLAG_NO_RETRANSMIT));
2635 if (len < 0 || !in) {
2636 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2637 return -1;
2638 }
2639
2640 if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
2641 !ssl_SocketIsBlocking(ss)) {
2642 PORT_Assert(!ssl_SocketIsBlocking(ss));
2643 PORT_SetError(PR_WOULD_BLOCK_ERROR);
2644 return -1;
2645 }
2646
2647 if (ss->appDataBuffered && len) {
2648 PORT_Assert(in[0] == (unsigned char)(ss->appDataBuffered));
2649 if (in[0] != (unsigned char)(ss->appDataBuffered)) {
2650 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2651 return -1;
2652 }
2653 in++;
2654 len--;
2655 discarded = 1;
2656 }
2657
2658 /* We will split the first byte of the record into its own record, as
2659 * explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h.
2660 */
2661 if (len > 1 && ss->opt.cbcRandomIV &&
2662 ss->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
2663 ss->ssl3.cwSpec->cipherDef->type == type_block /* CBC */) {
2664 splitNeeded = PR_TRUE;
2665 }
2666
2667 while (len > totalSent) {
2668 PRInt32 sent, toSend;
2669
2670 if (totalSent > 0) {
2671 /*
2672 * The thread yield is intended to give the reader thread a
2673 * chance to get some cycles while the writer thread is in
2674 * the middle of a large application data write. (See
2675 * Bugzilla bug 127740, comment #1.)
2676 */
2677 ssl_ReleaseXmitBufLock(ss);
2678 PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */
2679 ssl_GetXmitBufLock(ss);
2680 }
2681
2682 if (splitNeeded) {
2683 toSend = 1;
2684 splitNeeded = PR_FALSE;
2685 } else {
2686 toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
2687 }
2688
2689 /*
2690 * Note that the 0 epoch is OK because flags will never require
2691 * its use, as guaranteed by the PORT_Assert above.
2692 */
2693 sent = ssl3_SendRecord(ss, NULL, ssl_ct_application_data,
2694 in + totalSent, toSend, flags);
2695 if (sent < 0) {
2696 if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
2697 PORT_Assert(ss->lastWriteBlocked);
2698 break;
2699 }
2700 return -1; /* error code set by ssl3_SendRecord */
2701 }
2702 totalSent += sent;
2703 if (ss->pendingBuf.len) {
2704 /* must be a non-blocking socket */
2705 PORT_Assert(!ssl_SocketIsBlocking(ss));
2706 PORT_Assert(ss->lastWriteBlocked);
2707 break;
2708 }
2709 }
2710 if (ss->pendingBuf.len) {
2711 /* Must be non-blocking. */
2712 PORT_Assert(!ssl_SocketIsBlocking(ss));
2713 if (totalSent > 0) {
2714 ss->appDataBuffered = 0x100 | in[totalSent - 1];
2715 }
2716
2717 totalSent = totalSent + discarded - 1;
2718 if (totalSent <= 0) {
2719 PORT_SetError(PR_WOULD_BLOCK_ERROR);
2720 totalSent = SECFailure;
2721 }
2722 return totalSent;
2723 }
2724 ss->appDataBuffered = 0;
2725 return totalSent + discarded;
2726 }
2727
2728 /* Attempt to send buffered handshake messages.
2729 * Always set sendBuf.len to 0, even when returning SECFailure.
2730 *
2731 * Depending on whether we are doing DTLS or not, this either calls
2732 *
2733 * - ssl3_FlushHandshakeMessages if non-DTLS
2734 * - dtls_FlushHandshakeMessages if DTLS
2735 *
2736 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
2737 * ssl3_AppendHandshake(), ssl3_SendClientHello(),
2738 * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
2739 * ssl3_SendFinished(),
2740 */
2741 SECStatus
ssl3_FlushHandshake(sslSocket * ss,PRInt32 flags)2742 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
2743 {
2744 if (IS_DTLS(ss)) {
2745 return dtls_FlushHandshakeMessages(ss, flags);
2746 }
2747 return ssl3_FlushHandshakeMessages(ss, flags);
2748 }
2749
2750 /* Attempt to send the content of sendBuf buffer in an SSL handshake record.
2751 * Always set sendBuf.len to 0, even when returning SECFailure.
2752 *
2753 * Called from ssl3_FlushHandshake
2754 */
2755 static SECStatus
ssl3_FlushHandshakeMessages(sslSocket * ss,PRInt32 flags)2756 ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
2757 {
2758 static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2759 PRInt32 count = -1;
2760 SECStatus rv;
2761
2762 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2763 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2764
2765 if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
2766 return SECSuccess;
2767
2768 /* only these flags are allowed */
2769 PORT_Assert(!(flags & ~allowedFlags));
2770 if ((flags & ~allowedFlags) != 0) {
2771 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2772 return SECFailure;
2773 }
2774 count = ssl3_SendRecord(ss, NULL, ssl_ct_handshake,
2775 ss->sec.ci.sendBuf.buf,
2776 ss->sec.ci.sendBuf.len, flags);
2777 if (count < 0) {
2778 int err = PORT_GetError();
2779 PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
2780 if (err == PR_WOULD_BLOCK_ERROR) {
2781 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2782 }
2783 rv = SECFailure;
2784 } else if ((unsigned int)count < ss->sec.ci.sendBuf.len) {
2785 /* short write should never happen */
2786 PORT_Assert((unsigned int)count >= ss->sec.ci.sendBuf.len);
2787 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2788 rv = SECFailure;
2789 } else {
2790 rv = SECSuccess;
2791 }
2792
2793 /* Whether we succeeded or failed, toss the old handshake data. */
2794 ss->sec.ci.sendBuf.len = 0;
2795 return rv;
2796 }
2797
2798 /*
2799 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
2800 * the remote client sends a negative response to our certificate request.
2801 * Returns SECFailure if the application has required client auth.
2802 * SECSuccess otherwise.
2803 */
2804 SECStatus
ssl3_HandleNoCertificate(sslSocket * ss)2805 ssl3_HandleNoCertificate(sslSocket *ss)
2806 {
2807 ssl3_CleanupPeerCerts(ss);
2808
2809 /* If the server has required client-auth blindly but doesn't
2810 * actually look at the certificate it won't know that no
2811 * certificate was presented so we shutdown the socket to ensure
2812 * an error. We only do this if we haven't already completed the
2813 * first handshake because if we're redoing the handshake we
2814 * know the server is paying attention to the certificate.
2815 */
2816 if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
2817 (!ss->firstHsDone &&
2818 (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
2819 PRFileDesc *lower;
2820
2821 ssl_UncacheSessionID(ss);
2822
2823 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
2824 SSL3_SendAlert(ss, alert_fatal, certificate_required);
2825 } else {
2826 SSL3_SendAlert(ss, alert_fatal, bad_certificate);
2827 }
2828
2829 lower = ss->fd->lower;
2830 #ifdef _WIN32
2831 lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
2832 #else
2833 lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
2834 #endif
2835 PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
2836 return SECFailure;
2837 }
2838 return SECSuccess;
2839 }
2840
2841 /************************************************************************
2842 * Alerts
2843 */
2844
2845 /*
2846 ** Acquires both handshake and XmitBuf locks.
2847 ** Called from: ssl3_IllegalParameter <-
2848 ** ssl3_HandshakeFailure <-
2849 ** ssl3_HandleAlert <- ssl3_HandleRecord.
2850 ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
2851 ** ssl3_ConsumeHandshakeVariable <-
2852 ** ssl3_HandleHelloRequest <-
2853 ** ssl3_HandleServerHello <-
2854 ** ssl3_HandleServerKeyExchange <-
2855 ** ssl3_HandleCertificateRequest <-
2856 ** ssl3_HandleServerHelloDone <-
2857 ** ssl3_HandleClientHello <-
2858 ** ssl3_HandleV2ClientHello <-
2859 ** ssl3_HandleCertificateVerify <-
2860 ** ssl3_HandleClientKeyExchange <-
2861 ** ssl3_HandleCertificate <-
2862 ** ssl3_HandleFinished <-
2863 ** ssl3_HandleHandshakeMessage <-
2864 ** ssl3_HandlePostHelloHandshakeMessage <-
2865 ** ssl3_HandleRecord <-
2866 **
2867 */
2868 SECStatus
SSL3_SendAlert(sslSocket * ss,SSL3AlertLevel level,SSL3AlertDescription desc)2869 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
2870 {
2871 PRUint8 bytes[2];
2872 SECStatus rv;
2873 PRBool needHsLock = !ssl_HaveSSL3HandshakeLock(ss);
2874
2875 /* Check that if I need the HS lock I also need the Xmit lock */
2876 PORT_Assert(!needHsLock || !ssl_HaveXmitBufLock(ss));
2877
2878 SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
2879 SSL_GETPID(), ss->fd, level, desc));
2880
2881 bytes[0] = level;
2882 bytes[1] = desc;
2883
2884 if (needHsLock) {
2885 ssl_GetSSL3HandshakeLock(ss);
2886 }
2887 if (level == alert_fatal) {
2888 if (ss->sec.ci.sid) {
2889 ssl_UncacheSessionID(ss);
2890 }
2891 }
2892
2893 rv = tls13_SetAlertCipherSpec(ss);
2894 if (rv != SECSuccess) {
2895 if (needHsLock) {
2896 ssl_ReleaseSSL3HandshakeLock(ss);
2897 }
2898 return rv;
2899 }
2900
2901 ssl_GetXmitBufLock(ss);
2902 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
2903 if (rv == SECSuccess) {
2904 PRInt32 sent;
2905 sent = ssl3_SendRecord(ss, NULL, ssl_ct_alert, bytes, 2,
2906 (desc == no_certificate) ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
2907 rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
2908 }
2909 if (level == alert_fatal) {
2910 ss->ssl3.fatalAlertSent = PR_TRUE;
2911 }
2912 ssl_ReleaseXmitBufLock(ss);
2913 if (needHsLock) {
2914 ssl_ReleaseSSL3HandshakeLock(ss);
2915 }
2916 if (rv == SECSuccess && ss->alertSentCallback) {
2917 SSLAlert alert = { level, desc };
2918 ss->alertSentCallback(ss->fd, ss->alertSentCallbackArg, &alert);
2919 }
2920 return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
2921 }
2922
2923 /*
2924 * Send illegal_parameter alert. Set generic error number.
2925 */
2926 static SECStatus
ssl3_IllegalParameter(sslSocket * ss)2927 ssl3_IllegalParameter(sslSocket *ss)
2928 {
2929 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
2930 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2931 : SSL_ERROR_BAD_SERVER);
2932 return SECFailure;
2933 }
2934
2935 /*
2936 * Send handshake_Failure alert. Set generic error number.
2937 */
2938 static SECStatus
ssl3_HandshakeFailure(sslSocket * ss)2939 ssl3_HandshakeFailure(sslSocket *ss)
2940 {
2941 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
2942 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2943 : SSL_ERROR_BAD_SERVER);
2944 return SECFailure;
2945 }
2946
2947 void
ssl3_SendAlertForCertError(sslSocket * ss,PRErrorCode errCode)2948 ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode)
2949 {
2950 SSL3AlertDescription desc = bad_certificate;
2951 PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
2952
2953 switch (errCode) {
2954 case SEC_ERROR_LIBRARY_FAILURE:
2955 desc = unsupported_certificate;
2956 break;
2957 case SEC_ERROR_EXPIRED_CERTIFICATE:
2958 desc = certificate_expired;
2959 break;
2960 case SEC_ERROR_REVOKED_CERTIFICATE:
2961 desc = certificate_revoked;
2962 break;
2963 case SEC_ERROR_INADEQUATE_KEY_USAGE:
2964 case SEC_ERROR_INADEQUATE_CERT_TYPE:
2965 desc = certificate_unknown;
2966 break;
2967 case SEC_ERROR_UNTRUSTED_CERT:
2968 desc = isTLS ? access_denied : certificate_unknown;
2969 break;
2970 case SEC_ERROR_UNKNOWN_ISSUER:
2971 case SEC_ERROR_UNTRUSTED_ISSUER:
2972 desc = isTLS ? unknown_ca : certificate_unknown;
2973 break;
2974 case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
2975 desc = isTLS ? unknown_ca : certificate_expired;
2976 break;
2977
2978 case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
2979 case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
2980 case SEC_ERROR_CA_CERT_INVALID:
2981 case SEC_ERROR_BAD_SIGNATURE:
2982 default:
2983 desc = bad_certificate;
2984 break;
2985 }
2986 SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
2987 SSL_GETPID(), ss->fd, errCode));
2988
2989 (void)SSL3_SendAlert(ss, alert_fatal, desc);
2990 }
2991
2992 /*
2993 * Send decode_error alert. Set generic error number.
2994 */
2995 SECStatus
ssl3_DecodeError(sslSocket * ss)2996 ssl3_DecodeError(sslSocket *ss)
2997 {
2998 (void)SSL3_SendAlert(ss, alert_fatal,
2999 ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error
3000 : illegal_parameter);
3001 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3002 : SSL_ERROR_BAD_SERVER);
3003 return SECFailure;
3004 }
3005
3006 /* Called from ssl3_HandleRecord.
3007 ** Caller must hold both RecvBuf and Handshake locks.
3008 */
3009 static SECStatus
ssl3_HandleAlert(sslSocket * ss,sslBuffer * buf)3010 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
3011 {
3012 SSL3AlertLevel level;
3013 SSL3AlertDescription desc;
3014 int error;
3015
3016 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3017 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3018
3019 SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
3020
3021 if (buf->len != 2) {
3022 (void)ssl3_DecodeError(ss);
3023 PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
3024 return SECFailure;
3025 }
3026 level = (SSL3AlertLevel)buf->buf[0];
3027 desc = (SSL3AlertDescription)buf->buf[1];
3028 buf->len = 0;
3029 SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
3030 SSL_GETPID(), ss->fd, level, desc));
3031
3032 if (ss->alertReceivedCallback) {
3033 SSLAlert alert = { level, desc };
3034 ss->alertReceivedCallback(ss->fd, ss->alertReceivedCallbackArg, &alert);
3035 }
3036
3037 switch (desc) {
3038 case close_notify:
3039 ss->recvdCloseNotify = 1;
3040 error = SSL_ERROR_CLOSE_NOTIFY_ALERT;
3041 break;
3042 case unexpected_message:
3043 error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
3044 break;
3045 case bad_record_mac:
3046 error = SSL_ERROR_BAD_MAC_ALERT;
3047 break;
3048 case decryption_failed_RESERVED:
3049 error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
3050 break;
3051 case record_overflow:
3052 error = SSL_ERROR_RECORD_OVERFLOW_ALERT;
3053 break;
3054 case decompression_failure:
3055 error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
3056 break;
3057 case handshake_failure:
3058 error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
3059 break;
3060 case no_certificate:
3061 error = SSL_ERROR_NO_CERTIFICATE;
3062 break;
3063 case certificate_required:
3064 error = SSL_ERROR_RX_CERTIFICATE_REQUIRED_ALERT;
3065 break;
3066 case bad_certificate:
3067 error = SSL_ERROR_BAD_CERT_ALERT;
3068 break;
3069 case unsupported_certificate:
3070 error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;
3071 break;
3072 case certificate_revoked:
3073 error = SSL_ERROR_REVOKED_CERT_ALERT;
3074 break;
3075 case certificate_expired:
3076 error = SSL_ERROR_EXPIRED_CERT_ALERT;
3077 break;
3078 case certificate_unknown:
3079 error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
3080 break;
3081 case illegal_parameter:
3082 error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;
3083 break;
3084 case inappropriate_fallback:
3085 error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
3086 break;
3087
3088 /* All alerts below are TLS only. */
3089 case unknown_ca:
3090 error = SSL_ERROR_UNKNOWN_CA_ALERT;
3091 break;
3092 case access_denied:
3093 error = SSL_ERROR_ACCESS_DENIED_ALERT;
3094 break;
3095 case decode_error:
3096 error = SSL_ERROR_DECODE_ERROR_ALERT;
3097 break;
3098 case decrypt_error:
3099 error = SSL_ERROR_DECRYPT_ERROR_ALERT;
3100 break;
3101 case export_restriction:
3102 error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
3103 break;
3104 case protocol_version:
3105 error = SSL_ERROR_PROTOCOL_VERSION_ALERT;
3106 break;
3107 case insufficient_security:
3108 error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
3109 break;
3110 case internal_error:
3111 error = SSL_ERROR_INTERNAL_ERROR_ALERT;
3112 break;
3113 case user_canceled:
3114 error = SSL_ERROR_USER_CANCELED_ALERT;
3115 break;
3116 case no_renegotiation:
3117 error = SSL_ERROR_NO_RENEGOTIATION_ALERT;
3118 break;
3119
3120 /* Alerts for TLS client hello extensions */
3121 case missing_extension:
3122 error = SSL_ERROR_MISSING_EXTENSION_ALERT;
3123 break;
3124 case unsupported_extension:
3125 error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT;
3126 break;
3127 case certificate_unobtainable:
3128 error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT;
3129 break;
3130 case unrecognized_name:
3131 error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
3132 break;
3133 case bad_certificate_status_response:
3134 error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT;
3135 break;
3136 case bad_certificate_hash_value:
3137 error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT;
3138 break;
3139 case ech_required:
3140 error = SSL_ERROR_ECH_REQUIRED_ALERT;
3141 break;
3142 default:
3143 error = SSL_ERROR_RX_UNKNOWN_ALERT;
3144 break;
3145 }
3146 if ((ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) &&
3147 (ss->ssl3.hs.ws != wait_server_hello)) {
3148 /* TLS 1.3 requires all but "end of data" alerts to be
3149 * treated as fatal. */
3150 switch (desc) {
3151 case close_notify:
3152 case user_canceled:
3153 break;
3154 default:
3155 level = alert_fatal;
3156 }
3157 }
3158 if (level == alert_fatal) {
3159 ssl_UncacheSessionID(ss);
3160 if ((ss->ssl3.hs.ws == wait_server_hello) &&
3161 (desc == handshake_failure)) {
3162 /* XXX This is a hack. We're assuming that any handshake failure
3163 * XXX on the client hello is a failure to match ciphers.
3164 */
3165 error = SSL_ERROR_NO_CYPHER_OVERLAP;
3166 }
3167 PORT_SetError(error);
3168 return SECFailure;
3169 }
3170 if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
3171 /* I'm a server. I've requested a client cert. He hasn't got one. */
3172 SECStatus rv;
3173
3174 PORT_Assert(ss->sec.isServer);
3175 ss->ssl3.hs.ws = wait_client_key;
3176 rv = ssl3_HandleNoCertificate(ss);
3177 return rv;
3178 }
3179 return SECSuccess;
3180 }
3181
3182 /*
3183 * Change Cipher Specs
3184 * Called from ssl3_HandleServerHelloDone,
3185 * ssl3_HandleClientHello,
3186 * and ssl3_HandleFinished
3187 *
3188 * Acquires and releases spec write lock, to protect switching the current
3189 * and pending write spec pointers.
3190 */
3191
3192 SECStatus
ssl3_SendChangeCipherSpecsInt(sslSocket * ss)3193 ssl3_SendChangeCipherSpecsInt(sslSocket *ss)
3194 {
3195 PRUint8 change = change_cipher_spec_choice;
3196 SECStatus rv;
3197
3198 SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
3199 SSL_GETPID(), ss->fd));
3200
3201 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3202 if (rv != SECSuccess) {
3203 return SECFailure; /* error code set by ssl3_FlushHandshake */
3204 }
3205
3206 if (!IS_DTLS(ss)) {
3207 PRInt32 sent;
3208 sent = ssl3_SendRecord(ss, NULL, ssl_ct_change_cipher_spec,
3209 &change, 1, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3210 if (sent < 0) {
3211 return SECFailure; /* error code set by ssl3_SendRecord */
3212 }
3213 } else {
3214 rv = dtls_QueueMessage(ss, ssl_ct_change_cipher_spec, &change, 1);
3215 if (rv != SECSuccess) {
3216 return SECFailure;
3217 }
3218 }
3219 return SECSuccess;
3220 }
3221
3222 static SECStatus
ssl3_SendChangeCipherSpecs(sslSocket * ss)3223 ssl3_SendChangeCipherSpecs(sslSocket *ss)
3224 {
3225 SECStatus rv;
3226
3227 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3228 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3229
3230 rv = ssl3_SendChangeCipherSpecsInt(ss);
3231 if (rv != SECSuccess) {
3232 return rv; /* Error code set. */
3233 }
3234
3235 /* swap the pending and current write specs. */
3236 ssl_GetSpecWriteLock(ss); /**************************************/
3237
3238 ssl_CipherSpecRelease(ss->ssl3.cwSpec);
3239 ss->ssl3.cwSpec = ss->ssl3.pwSpec;
3240 ss->ssl3.pwSpec = NULL;
3241
3242 SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
3243 SSL_GETPID(), ss->fd));
3244
3245 /* With DTLS, we need to set a holddown timer in case the final
3246 * message got lost */
3247 if (IS_DTLS(ss) && ss->ssl3.crSpec->epoch == ss->ssl3.cwSpec->epoch) {
3248 rv = dtls_StartHolddownTimer(ss);
3249 }
3250 ssl_ReleaseSpecWriteLock(ss); /**************************************/
3251
3252 return rv;
3253 }
3254
3255 /* Called from ssl3_HandleRecord.
3256 ** Caller must hold both RecvBuf and Handshake locks.
3257 *
3258 * Acquires and releases spec write lock, to protect switching the current
3259 * and pending write spec pointers.
3260 */
3261 static SECStatus
ssl3_HandleChangeCipherSpecs(sslSocket * ss,sslBuffer * buf)3262 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
3263 {
3264 SSL3WaitState ws = ss->ssl3.hs.ws;
3265 SSL3ChangeCipherSpecChoice change;
3266
3267 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3268 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3269
3270 SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
3271 SSL_GETPID(), ss->fd));
3272
3273 /* For DTLS: Ignore this if we aren't expecting it. Don't kill a connection
3274 * as a result of receiving trash.
3275 * For TLS: Maybe ignore, but only after checking format. */
3276 if (ws != wait_change_cipher && IS_DTLS(ss)) {
3277 /* Ignore this because it's out of order. */
3278 SSL_TRC(3, ("%d: SSL3[%d]: discard out of order "
3279 "DTLS change_cipher_spec",
3280 SSL_GETPID(), ss->fd));
3281 buf->len = 0;
3282 return SECSuccess;
3283 }
3284
3285 /* Handshake messages should not span ChangeCipherSpec. */
3286 if (ss->ssl3.hs.header_bytes) {
3287 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3288 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3289 return SECFailure;
3290 }
3291 if (buf->len != 1) {
3292 (void)ssl3_DecodeError(ss);
3293 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3294 return SECFailure;
3295 }
3296 change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
3297 if (change != change_cipher_spec_choice) {
3298 /* illegal_parameter is correct here for both SSL3 and TLS. */
3299 (void)ssl3_IllegalParameter(ss);
3300 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3301 return SECFailure;
3302 }
3303
3304 buf->len = 0;
3305 if (ws != wait_change_cipher) {
3306 /* Ignore a CCS for TLS 1.3. This only happens if the server sends a
3307 * HelloRetryRequest. In other cases, the CCS will fail decryption and
3308 * will be discarded by ssl3_HandleRecord(). */
3309 if (ws == wait_server_hello &&
3310 ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
3311 ss->ssl3.hs.helloRetry) {
3312 PORT_Assert(!ss->sec.isServer);
3313 return SECSuccess;
3314 }
3315 /* Note: For a server, we can't test ss->ssl3.hs.helloRetry or
3316 * ss->version because the server might be stateless (and so it won't
3317 * have set either value yet). Set a flag so that at least we will
3318 * guarantee that the server will treat any ClientHello properly. */
3319 if (ws == wait_client_hello &&
3320 ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3 &&
3321 !ss->ssl3.hs.receivedCcs) {
3322 PORT_Assert(ss->sec.isServer);
3323 ss->ssl3.hs.receivedCcs = PR_TRUE;
3324 return SECSuccess;
3325 }
3326 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3327 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3328 return SECFailure;
3329 }
3330
3331 SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
3332 SSL_GETPID(), ss->fd));
3333 ssl_GetSpecWriteLock(ss); /*************************************/
3334 PORT_Assert(ss->ssl3.prSpec);
3335 ssl_CipherSpecRelease(ss->ssl3.crSpec);
3336 ss->ssl3.crSpec = ss->ssl3.prSpec;
3337 ss->ssl3.prSpec = NULL;
3338 ssl_ReleaseSpecWriteLock(ss); /*************************************/
3339
3340 ss->ssl3.hs.ws = wait_finished;
3341 return SECSuccess;
3342 }
3343
3344 static CK_MECHANISM_TYPE
ssl3_GetMgfMechanismByHashType(SSLHashType hash)3345 ssl3_GetMgfMechanismByHashType(SSLHashType hash)
3346 {
3347 switch (hash) {
3348 case ssl_hash_sha256:
3349 return CKG_MGF1_SHA256;
3350 case ssl_hash_sha384:
3351 return CKG_MGF1_SHA384;
3352 case ssl_hash_sha512:
3353 return CKG_MGF1_SHA512;
3354 default:
3355 PORT_Assert(0);
3356 }
3357 return CKG_MGF1_SHA256;
3358 }
3359
3360 /* Function valid for >= TLS 1.2, only. */
3361 static CK_MECHANISM_TYPE
ssl3_GetHashMechanismByHashType(SSLHashType hashType)3362 ssl3_GetHashMechanismByHashType(SSLHashType hashType)
3363 {
3364 switch (hashType) {
3365 case ssl_hash_sha512:
3366 return CKM_SHA512;
3367 case ssl_hash_sha384:
3368 return CKM_SHA384;
3369 case ssl_hash_sha256:
3370 case ssl_hash_none:
3371 /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
3372 return CKM_SHA256;
3373 case ssl_hash_sha1:
3374 return CKM_SHA_1;
3375 default:
3376 PORT_Assert(0);
3377 }
3378 return CKM_SHA256;
3379 }
3380
3381 /* Function valid for >= TLS 1.2, only. */
3382 static CK_MECHANISM_TYPE
ssl3_GetPrfHashMechanism(sslSocket * ss)3383 ssl3_GetPrfHashMechanism(sslSocket *ss)
3384 {
3385 return ssl3_GetHashMechanismByHashType(ss->ssl3.hs.suite_def->prf_hash);
3386 }
3387
3388 static SSLHashType
ssl3_GetSuitePrfHash(sslSocket * ss)3389 ssl3_GetSuitePrfHash(sslSocket *ss)
3390 {
3391 /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
3392 if (ss->ssl3.hs.suite_def->prf_hash == ssl_hash_none) {
3393 return ssl_hash_sha256;
3394 }
3395 return ss->ssl3.hs.suite_def->prf_hash;
3396 }
3397
3398 /* This method completes the derivation of the MS from the PMS.
3399 **
3400 ** 1. Derive the MS, if possible, else return an error.
3401 **
3402 ** 2. Check the version if |pms_version| is non-zero and if wrong,
3403 ** return an error.
3404 **
3405 ** 3. If |msp| is nonzero, return MS in |*msp|.
3406
3407 ** Called from:
3408 ** ssl3_ComputeMasterSecretInt
3409 ** tls_ComputeExtendedMasterSecretInt
3410 */
3411 static SECStatus
ssl3_ComputeMasterSecretFinish(sslSocket * ss,CK_MECHANISM_TYPE master_derive,CK_MECHANISM_TYPE key_derive,CK_VERSION * pms_version,SECItem * params,CK_FLAGS keyFlags,PK11SymKey * pms,PK11SymKey ** msp)3412 ssl3_ComputeMasterSecretFinish(sslSocket *ss,
3413 CK_MECHANISM_TYPE master_derive,
3414 CK_MECHANISM_TYPE key_derive,
3415 CK_VERSION *pms_version,
3416 SECItem *params, CK_FLAGS keyFlags,
3417 PK11SymKey *pms, PK11SymKey **msp)
3418 {
3419 PK11SymKey *ms = NULL;
3420
3421 ms = PK11_DeriveWithFlags(pms, master_derive,
3422 params, key_derive,
3423 CKA_DERIVE, 0, keyFlags);
3424 if (!ms) {
3425 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3426 return SECFailure;
3427 }
3428
3429 if (pms_version && ss->opt.detectRollBack) {
3430 SSL3ProtocolVersion client_version;
3431 client_version = pms_version->major << 8 | pms_version->minor;
3432
3433 if (IS_DTLS(ss)) {
3434 client_version = dtls_DTLSVersionToTLSVersion(client_version);
3435 }
3436
3437 if (client_version != ss->clientHelloVersion) {
3438 /* Destroy MS. Version roll-back detected. */
3439 PK11_FreeSymKey(ms);
3440 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3441 return SECFailure;
3442 }
3443 }
3444
3445 if (msp) {
3446 *msp = ms;
3447 } else {
3448 PK11_FreeSymKey(ms);
3449 }
3450
3451 return SECSuccess;
3452 }
3453
3454 /* Compute the ordinary (pre draft-ietf-tls-session-hash) master
3455 ** secret and return it in |*msp|.
3456 **
3457 ** Called from: ssl3_ComputeMasterSecret
3458 */
3459 static SECStatus
ssl3_ComputeMasterSecretInt(sslSocket * ss,PK11SymKey * pms,PK11SymKey ** msp)3460 ssl3_ComputeMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3461 PK11SymKey **msp)
3462 {
3463 PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
3464 PRBool isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3465 /*
3466 * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
3467 * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
3468 * data into a 48-byte value, and does not expect to return the version.
3469 */
3470 PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
3471 (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh));
3472 CK_MECHANISM_TYPE master_derive;
3473 CK_MECHANISM_TYPE key_derive;
3474 SECItem params;
3475 CK_FLAGS keyFlags;
3476 CK_VERSION pms_version;
3477 CK_VERSION *pms_version_ptr = NULL;
3478 /* master_params may be used as a CK_SSL3_MASTER_KEY_DERIVE_PARAMS */
3479 CK_TLS12_MASTER_KEY_DERIVE_PARAMS master_params;
3480 unsigned int master_params_len;
3481
3482 if (isTLS12) {
3483 if (isDH)
3484 master_derive = CKM_TLS12_MASTER_KEY_DERIVE_DH;
3485 else
3486 master_derive = CKM_TLS12_MASTER_KEY_DERIVE;
3487 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3488 keyFlags = CKF_SIGN | CKF_VERIFY;
3489 } else if (isTLS) {
3490 if (isDH)
3491 master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
3492 else
3493 master_derive = CKM_TLS_MASTER_KEY_DERIVE;
3494 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3495 keyFlags = CKF_SIGN | CKF_VERIFY;
3496 } else {
3497 if (isDH)
3498 master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
3499 else
3500 master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
3501 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3502 keyFlags = 0;
3503 }
3504
3505 if (!isDH) {
3506 pms_version_ptr = &pms_version;
3507 }
3508
3509 master_params.pVersion = pms_version_ptr;
3510 master_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
3511 master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3512 master_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
3513 master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3514 if (isTLS12) {
3515 master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3516 master_params_len = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS);
3517 } else {
3518 /* prfHashMechanism is not relevant with this PRF */
3519 master_params_len = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS);
3520 }
3521
3522 params.data = (unsigned char *)&master_params;
3523 params.len = master_params_len;
3524
3525 return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3526 pms_version_ptr, ¶ms,
3527 keyFlags, pms, msp);
3528 }
3529
3530 /* Compute the draft-ietf-tls-session-hash master
3531 ** secret and return it in |*msp|.
3532 **
3533 ** Called from: ssl3_ComputeMasterSecret
3534 */
3535 static SECStatus
tls_ComputeExtendedMasterSecretInt(sslSocket * ss,PK11SymKey * pms,PK11SymKey ** msp)3536 tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3537 PK11SymKey **msp)
3538 {
3539 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3540 CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS extended_master_params;
3541 SSL3Hashes hashes;
3542 /*
3543 * Determine whether to use the DH/ECDH or RSA derivation modes.
3544 */
3545 /*
3546 * TODO(ekr@rtfm.com): Verify that the slot can handle this key expansion
3547 * mode. Bug 1198298 */
3548 PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
3549 (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh));
3550 CK_MECHANISM_TYPE master_derive;
3551 CK_MECHANISM_TYPE key_derive;
3552 SECItem params;
3553 const CK_FLAGS keyFlags = CKF_SIGN | CKF_VERIFY;
3554 CK_VERSION pms_version;
3555 CK_VERSION *pms_version_ptr = NULL;
3556 SECStatus rv;
3557
3558 rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0);
3559 if (rv != SECSuccess) {
3560 PORT_Assert(0); /* Should never fail */
3561 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3562 return SECFailure;
3563 }
3564
3565 if (isDH) {
3566 master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH;
3567 } else {
3568 master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE;
3569 pms_version_ptr = &pms_version;
3570 }
3571
3572 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
3573 /* TLS 1.2+ */
3574 extended_master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3575 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3576 } else {
3577 /* TLS < 1.2 */
3578 extended_master_params.prfHashMechanism = CKM_TLS_PRF;
3579 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3580 }
3581
3582 extended_master_params.pVersion = pms_version_ptr;
3583 extended_master_params.pSessionHash = hashes.u.raw;
3584 extended_master_params.ulSessionHashLen = hashes.len;
3585
3586 params.data = (unsigned char *)&extended_master_params;
3587 params.len = sizeof extended_master_params;
3588
3589 return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3590 pms_version_ptr, ¶ms,
3591 keyFlags, pms, msp);
3592 }
3593
3594 /* Wrapper method to compute the master secret and return it in |*msp|.
3595 **
3596 ** Called from ssl3_ComputeMasterSecret
3597 */
3598 static SECStatus
ssl3_ComputeMasterSecret(sslSocket * ss,PK11SymKey * pms,PK11SymKey ** msp)3599 ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
3600 PK11SymKey **msp)
3601 {
3602 PORT_Assert(pms != NULL);
3603 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3604
3605 if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
3606 return tls_ComputeExtendedMasterSecretInt(ss, pms, msp);
3607 } else {
3608 return ssl3_ComputeMasterSecretInt(ss, pms, msp);
3609 }
3610 }
3611
3612 /*
3613 * Derive encryption and MAC Keys (and IVs) from master secret
3614 * Sets a useful error code when returning SECFailure.
3615 *
3616 * Called only from ssl3_InitPendingCipherSpec(),
3617 * which in turn is called from
3618 * ssl3_SendRSAClientKeyExchange (for Full handshake)
3619 * ssl3_SendDHClientKeyExchange (for Full handshake)
3620 * ssl3_HandleClientKeyExchange (for Full handshake)
3621 * ssl3_HandleServerHello (for session restart)
3622 * ssl3_HandleClientHello (for session restart)
3623 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
3624 * ssl3_InitPendingCipherSpec does that.
3625 *
3626 */
3627 static SECStatus
ssl3_DeriveConnectionKeys(sslSocket * ss,PK11SymKey * masterSecret)3628 ssl3_DeriveConnectionKeys(sslSocket *ss, PK11SymKey *masterSecret)
3629 {
3630 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3631 ssl3CipherSpec *prSpec = ss->ssl3.prSpec;
3632 ssl3CipherSpec *clientSpec;
3633 ssl3CipherSpec *serverSpec;
3634 PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
3635 PRBool isTLS12 =
3636 (PRBool)(isTLS && ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3637 const ssl3BulkCipherDef *cipher_def = pwSpec->cipherDef;
3638 PK11SlotInfo *slot = NULL;
3639 PK11SymKey *derivedKeyHandle = NULL;
3640 void *pwArg = ss->pkcs11PinArg;
3641 int keySize;
3642 CK_TLS12_KEY_MAT_PARAMS key_material_params; /* may be used as a
3643 * CK_SSL3_KEY_MAT_PARAMS */
3644 unsigned int key_material_params_len;
3645 CK_SSL3_KEY_MAT_OUT returnedKeys;
3646 CK_MECHANISM_TYPE key_derive;
3647 CK_MECHANISM_TYPE bulk_mechanism;
3648 SSLCipherAlgorithm calg;
3649 SECItem params;
3650 PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == ssl_calg_null);
3651
3652 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3653 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3654 PORT_Assert(masterSecret);
3655
3656 /* These functions operate in terms of who is writing specs. */
3657 if (ss->sec.isServer) {
3658 clientSpec = prSpec;
3659 serverSpec = pwSpec;
3660 } else {
3661 clientSpec = pwSpec;
3662 serverSpec = prSpec;
3663 }
3664
3665 /*
3666 * generate the key material
3667 */
3668 if (cipher_def->type == type_block &&
3669 ss->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
3670 /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
3671 key_material_params.ulIVSizeInBits = 0;
3672 PORT_Memset(clientSpec->keyMaterial.iv, 0, cipher_def->iv_size);
3673 PORT_Memset(serverSpec->keyMaterial.iv, 0, cipher_def->iv_size);
3674 }
3675
3676 key_material_params.bIsExport = PR_FALSE;
3677 key_material_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
3678 key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3679 key_material_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
3680 key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3681 key_material_params.pReturnedKeyMaterial = &returnedKeys;
3682
3683 if (skipKeysAndIVs) {
3684 keySize = 0;
3685 returnedKeys.pIVClient = NULL;
3686 returnedKeys.pIVServer = NULL;
3687 key_material_params.ulKeySizeInBits = 0;
3688 key_material_params.ulIVSizeInBits = 0;
3689 } else {
3690 keySize = cipher_def->key_size;
3691 returnedKeys.pIVClient = clientSpec->keyMaterial.iv;
3692 returnedKeys.pIVServer = serverSpec->keyMaterial.iv;
3693 key_material_params.ulKeySizeInBits = cipher_def->secret_key_size * BPB;
3694 key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB;
3695 }
3696 key_material_params.ulMacSizeInBits = pwSpec->macDef->mac_size * BPB;
3697
3698 calg = cipher_def->calg;
3699 bulk_mechanism = ssl3_Alg2Mech(calg);
3700
3701 if (isTLS12) {
3702 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3703 key_material_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3704 key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS);
3705 } else if (isTLS) {
3706 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3707 key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
3708 } else {
3709 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3710 key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
3711 }
3712
3713 params.data = (unsigned char *)&key_material_params;
3714 params.len = key_material_params_len;
3715
3716 /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
3717 * DERIVE by DEFAULT */
3718 derivedKeyHandle = PK11_Derive(masterSecret, key_derive, ¶ms,
3719 bulk_mechanism, CKA_ENCRYPT, keySize);
3720 if (!derivedKeyHandle) {
3721 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3722 return SECFailure;
3723 }
3724 /* we really should use the actual mac'ing mechanism here, but we
3725 * don't because these types are used to map keytype anyway and both
3726 * mac's map to the same keytype.
3727 */
3728 slot = PK11_GetSlotFromKey(derivedKeyHandle);
3729
3730 PK11_FreeSlot(slot); /* slot is held until the key is freed */
3731 clientSpec->keyMaterial.macKey =
3732 PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3733 CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret,
3734 PR_TRUE, pwArg);
3735 if (clientSpec->keyMaterial.macKey == NULL) {
3736 goto loser; /* loser sets err */
3737 }
3738 serverSpec->keyMaterial.macKey =
3739 PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3740 CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret,
3741 PR_TRUE, pwArg);
3742 if (serverSpec->keyMaterial.macKey == NULL) {
3743 goto loser; /* loser sets err */
3744 }
3745 if (!skipKeysAndIVs) {
3746 clientSpec->keyMaterial.key =
3747 PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3748 bulk_mechanism, returnedKeys.hClientKey,
3749 PR_TRUE, pwArg);
3750 if (clientSpec->keyMaterial.key == NULL) {
3751 goto loser; /* loser sets err */
3752 }
3753 serverSpec->keyMaterial.key =
3754 PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3755 bulk_mechanism, returnedKeys.hServerKey,
3756 PR_TRUE, pwArg);
3757 if (serverSpec->keyMaterial.key == NULL) {
3758 goto loser; /* loser sets err */
3759 }
3760 }
3761 PK11_FreeSymKey(derivedKeyHandle);
3762 return SECSuccess;
3763
3764 loser:
3765 PK11_FreeSymKey(derivedKeyHandle);
3766 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3767 return SECFailure;
3768 }
3769
3770 void
ssl3_CoalesceEchHandshakeHashes(sslSocket * ss)3771 ssl3_CoalesceEchHandshakeHashes(sslSocket *ss)
3772 {
3773 /* |sha| contains the CHOuter transcript, which is the singular
3774 * transcript if not doing ECH. If the server responded with 1.2,
3775 * contexts are not yet initialized. */
3776 if (ss->ssl3.hs.echAccepted) {
3777 if (ss->ssl3.hs.sha) {
3778 PORT_Assert(ss->ssl3.hs.shaEchInner);
3779 PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
3780 ss->ssl3.hs.sha = ss->ssl3.hs.shaEchInner;
3781 ss->ssl3.hs.shaEchInner = NULL;
3782 }
3783 } else {
3784 if (ss->ssl3.hs.shaEchInner) {
3785 PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
3786 ss->ssl3.hs.shaEchInner = NULL;
3787 }
3788 }
3789 }
3790
3791 /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
3792 * buffered messages in ss->ssl3.hs.messages. Called from
3793 * ssl3_NegotiateCipherSuite(), tls13_HandleClientHelloPart2(),
3794 * and ssl3_HandleServerHello. */
3795 SECStatus
ssl3_InitHandshakeHashes(sslSocket * ss)3796 ssl3_InitHandshakeHashes(sslSocket *ss)
3797 {
3798 SSL_TRC(30, ("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
3799
3800 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
3801 if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
3802 ss->ssl3.hs.hashType = handshake_hash_record;
3803 } else {
3804 PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha);
3805 /*
3806 * note: We should probably lookup an SSL3 slot for these
3807 * handshake hashes in hopes that we wind up with the same slots
3808 * that the master secret will wind up in ...
3809 */
3810 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
3811 /* determine the hash from the prf */
3812 const SECOidData *hash_oid =
3813 SECOID_FindOIDByMechanism(ssl3_GetPrfHashMechanism(ss));
3814
3815 /* Get the PKCS #11 mechanism for the Hash from the cipher suite (prf_hash)
3816 * Convert that to the OidTag. We can then use that OidTag to create our
3817 * PK11Context */
3818 PORT_Assert(hash_oid != NULL);
3819 if (hash_oid == NULL) {
3820 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3821 return SECFailure;
3822 }
3823
3824 ss->ssl3.hs.sha = PK11_CreateDigestContext(hash_oid->offset);
3825 if (ss->ssl3.hs.sha == NULL) {
3826 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3827 return SECFailure;
3828 }
3829 ss->ssl3.hs.hashType = handshake_hash_single;
3830 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3831 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3832 return SECFailure;
3833 }
3834
3835 /* Alternate transcript hash used in Encrypted Client Hello. */
3836 if (!ss->sec.isServer && ss->ssl3.hs.echHpkeCtx) {
3837 ss->ssl3.hs.shaEchInner = PK11_CreateDigestContext(hash_oid->offset);
3838 if (ss->ssl3.hs.shaEchInner == NULL) {
3839 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3840 return SECFailure;
3841 }
3842 if (PK11_DigestBegin(ss->ssl3.hs.shaEchInner) != SECSuccess) {
3843 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3844 return SECFailure;
3845 }
3846 }
3847 } else {
3848 /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
3849 * created successfully. */
3850 ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
3851 if (ss->ssl3.hs.md5 == NULL) {
3852 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3853 return SECFailure;
3854 }
3855 ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
3856 if (ss->ssl3.hs.sha == NULL) {
3857 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
3858 ss->ssl3.hs.md5 = NULL;
3859 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3860 return SECFailure;
3861 }
3862 ss->ssl3.hs.hashType = handshake_hash_combo;
3863
3864 if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
3865 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3866 return SECFailure;
3867 }
3868 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3869 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3870 return SECFailure;
3871 }
3872 }
3873 }
3874
3875 if (ss->ssl3.hs.hashType != handshake_hash_record &&
3876 ss->ssl3.hs.messages.len > 0) {
3877 /* When doing ECH, ssl3_UpdateHandshakeHashes will store outer messages into
3878 * the both the outer and inner transcripts. ssl3_UpdateDefaultHandshakeHashes
3879 * uses only the default context (which is the outer when doing ECH). */
3880 if (ssl3_UpdateDefaultHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
3881 ss->ssl3.hs.messages.len) != SECSuccess) {
3882 return SECFailure;
3883 }
3884 /* When doing ECH, deriving accept_confirmation requires all messages
3885 * up to SH, then a synthetic SH. Don't free the buffers just yet. */
3886 if (!ss->ssl3.hs.echHpkeCtx) {
3887 sslBuffer_Clear(&ss->ssl3.hs.messages);
3888 }
3889 }
3890 if (ss->ssl3.hs.shaEchInner &&
3891 ss->ssl3.hs.echInnerMessages.len > 0) {
3892 if (PK11_DigestOp(ss->ssl3.hs.shaEchInner, ss->ssl3.hs.echInnerMessages.buf,
3893 ss->ssl3.hs.echInnerMessages.len) != SECSuccess) {
3894 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3895 return SECFailure;
3896 }
3897 if (!ss->ssl3.hs.echHpkeCtx) {
3898 sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
3899 }
3900 }
3901
3902 return SECSuccess;
3903 }
3904
3905 void
ssl3_RestartHandshakeHashes(sslSocket * ss)3906 ssl3_RestartHandshakeHashes(sslSocket *ss)
3907 {
3908 SSL_TRC(30, ("%d: SSL3[%d]: reset handshake hashes",
3909 SSL_GETPID(), ss->fd));
3910 ss->ssl3.hs.hashType = handshake_hash_unknown;
3911 ss->ssl3.hs.messages.len = 0;
3912 ss->ssl3.hs.echInnerMessages.len = 0;
3913 if (ss->ssl3.hs.md5) {
3914 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
3915 ss->ssl3.hs.md5 = NULL;
3916 }
3917 if (ss->ssl3.hs.sha) {
3918 PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
3919 ss->ssl3.hs.sha = NULL;
3920 }
3921 if (ss->ssl3.hs.shaEchInner) {
3922 PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
3923 ss->ssl3.hs.shaEchInner = NULL;
3924 }
3925 if (ss->ssl3.hs.shaPostHandshake) {
3926 PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
3927 ss->ssl3.hs.shaPostHandshake = NULL;
3928 }
3929 }
3930
3931 /* Add the provided bytes to the handshake hash context. When doing
3932 * TLS 1.3 ECH, |target| may be provided to specify only the inner/outer
3933 * transcript, else the input is added to both contexts. This happens
3934 * only on the client. On the server, only the default context is used. */
3935 SECStatus
ssl3_UpdateHandshakeHashesInt(sslSocket * ss,const unsigned char * b,unsigned int l,sslBuffer * target)3936 ssl3_UpdateHandshakeHashesInt(sslSocket *ss, const unsigned char *b,
3937 unsigned int l, sslBuffer *target)
3938 {
3939
3940 SECStatus rv = SECSuccess;
3941 PRBool explicit = (target != NULL);
3942 PRBool appendToEchInner = !ss->sec.isServer &&
3943 ss->ssl3.hs.echHpkeCtx &&
3944 !explicit;
3945 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3946 PORT_Assert(target != &ss->ssl3.hs.echInnerMessages ||
3947 !ss->sec.isServer);
3948
3949 if (target == NULL) {
3950 /* Default context. */
3951 target = &ss->ssl3.hs.messages;
3952 }
3953 /* With TLS 1.3, and versions TLS.1.1 and older, we keep the hash(es)
3954 * always up to date. However, we must initially buffer the handshake
3955 * messages, until we know what to do.
3956 * If ss->ssl3.hs.hashType != handshake_hash_unknown,
3957 * it means we know what to do. We calculate (hash our input),
3958 * and we stop appending to the buffer.
3959 *
3960 * With TLS 1.2, we always append all handshake messages,
3961 * and never update the hash, because the hash function we must use for
3962 * certificate_verify might be different from the hash function we use
3963 * when signing other handshake hashes. */
3964 if (ss->ssl3.hs.hashType == handshake_hash_unknown ||
3965 ss->ssl3.hs.hashType == handshake_hash_record) {
3966 rv = sslBuffer_Append(target, b, l);
3967 if (rv != SECSuccess) {
3968 return SECFailure;
3969 }
3970 if (appendToEchInner) {
3971 return sslBuffer_Append(&ss->ssl3.hs.echInnerMessages, b, l);
3972 }
3973 return SECSuccess;
3974 }
3975
3976 PRINT_BUF(90, (ss, "handshake hash input:", b, l));
3977
3978 if (ss->ssl3.hs.hashType == handshake_hash_single) {
3979 PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
3980 if (target == &ss->ssl3.hs.messages) {
3981 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
3982 if (rv != SECSuccess) {
3983 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3984 return rv;
3985 }
3986 }
3987 if (ss->ssl3.hs.shaEchInner &&
3988 (target == &ss->ssl3.hs.echInnerMessages || !explicit)) {
3989 rv = PK11_DigestOp(ss->ssl3.hs.shaEchInner, b, l);
3990 if (rv != SECSuccess) {
3991 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3992 return rv;
3993 }
3994 }
3995 } else if (ss->ssl3.hs.hashType == handshake_hash_combo) {
3996 rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
3997 if (rv != SECSuccess) {
3998 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3999 return rv;
4000 }
4001 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
4002 if (rv != SECSuccess) {
4003 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4004 return rv;
4005 }
4006 }
4007 return rv;
4008 }
4009
4010 static SECStatus
ssl3_UpdateDefaultHandshakeHashes(sslSocket * ss,const unsigned char * b,unsigned int l)4011 ssl3_UpdateDefaultHandshakeHashes(sslSocket *ss, const unsigned char *b,
4012 unsigned int l)
4013 {
4014 return ssl3_UpdateHandshakeHashesInt(ss, b, l,
4015 &ss->ssl3.hs.messages);
4016 }
4017
4018 static SECStatus
ssl3_UpdateInnerHandshakeHashes(sslSocket * ss,const unsigned char * b,unsigned int l)4019 ssl3_UpdateInnerHandshakeHashes(sslSocket *ss, const unsigned char *b,
4020 unsigned int l)
4021 {
4022 return ssl3_UpdateHandshakeHashesInt(ss, b, l,
4023 &ss->ssl3.hs.echInnerMessages);
4024 }
4025
4026 /*
4027 * Handshake messages
4028 */
4029 /* Called from ssl3_InitHandshakeHashes()
4030 ** ssl3_AppendHandshake()
4031 ** ssl3_HandleV2ClientHello()
4032 ** ssl3_HandleHandshakeMessage()
4033 ** Caller must hold the ssl3Handshake lock.
4034 */
4035 SECStatus
ssl3_UpdateHandshakeHashes(sslSocket * ss,const unsigned char * b,unsigned int l)4036 ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l)
4037 {
4038 return ssl3_UpdateHandshakeHashesInt(ss, b, l, NULL);
4039 }
4040
4041 SECStatus
ssl3_UpdatePostHandshakeHashes(sslSocket * ss,const unsigned char * b,unsigned int l)4042 ssl3_UpdatePostHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l)
4043 {
4044 SECStatus rv = SECSuccess;
4045
4046 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4047
4048 PRINT_BUF(90, (ss, "post handshake hash input:", b, l));
4049
4050 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single);
4051 PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
4052 rv = PK11_DigestOp(ss->ssl3.hs.shaPostHandshake, b, l);
4053 if (rv != SECSuccess) {
4054 PORT_SetError(SSL_ERROR_DIGEST_FAILURE);
4055 }
4056 return rv;
4057 }
4058
4059 SECStatus
ssl3_AppendHandshakeHeader(sslSocket * ss,SSLHandshakeType t,PRUint32 length)4060 ssl3_AppendHandshakeHeader(sslSocket *ss, SSLHandshakeType t, PRUint32 length)
4061 {
4062 SECStatus rv;
4063
4064 /* If we already have a message in place, we need to enqueue it.
4065 * This empties the buffer. This is a convenient place to call
4066 * dtls_StageHandshakeMessage to mark the message boundary.
4067 */
4068 if (IS_DTLS(ss)) {
4069 rv = dtls_StageHandshakeMessage(ss);
4070 if (rv != SECSuccess) {
4071 return rv;
4072 }
4073 }
4074
4075 SSL_TRC(30, ("%d: SSL3[%d]: append handshake header: type %s",
4076 SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
4077
4078 rv = ssl3_AppendHandshakeNumber(ss, t, 1);
4079 if (rv != SECSuccess) {
4080 return rv; /* error code set by AppendHandshake, if applicable. */
4081 }
4082 rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4083 if (rv != SECSuccess) {
4084 return rv; /* error code set by AppendHandshake, if applicable. */
4085 }
4086
4087 if (IS_DTLS(ss)) {
4088 /* Note that we make an unfragmented message here. We fragment in the
4089 * transmission code, if necessary */
4090 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2);
4091 if (rv != SECSuccess) {
4092 return rv; /* error code set by AppendHandshake, if applicable. */
4093 }
4094 ss->ssl3.hs.sendMessageSeq++;
4095
4096 /* 0 is the fragment offset, because it's not fragmented yet */
4097 rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
4098 if (rv != SECSuccess) {
4099 return rv; /* error code set by AppendHandshake, if applicable. */
4100 }
4101
4102 /* Fragment length -- set to the packet length because not fragmented */
4103 rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4104 if (rv != SECSuccess) {
4105 return rv; /* error code set by AppendHandshake, if applicable. */
4106 }
4107 }
4108
4109 return rv; /* error code set by AppendHandshake, if applicable. */
4110 }
4111
4112 /**************************************************************************
4113 * Consume Handshake functions.
4114 *
4115 * All data used in these functions is protected by two locks,
4116 * the RecvBufLock and the SSL3HandshakeLock
4117 **************************************************************************/
4118
4119 /* Read up the next "bytes" number of bytes from the (decrypted) input
4120 * stream "b" (which is *length bytes long). Copy them into buffer "v".
4121 * Reduces *length by bytes. Advances *b by bytes.
4122 *
4123 * If this function returns SECFailure, it has already sent an alert,
4124 * and has set a generic error code. The caller should probably
4125 * override the generic error code by setting another.
4126 */
4127 SECStatus
ssl3_ConsumeHandshake(sslSocket * ss,void * v,PRUint32 bytes,PRUint8 ** b,PRUint32 * length)4128 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRUint32 bytes, PRUint8 **b,
4129 PRUint32 *length)
4130 {
4131 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4132 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4133
4134 if ((PRUint32)bytes > *length) {
4135 return ssl3_DecodeError(ss);
4136 }
4137 PORT_Memcpy(v, *b, bytes);
4138 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4139 *b += bytes;
4140 *length -= bytes;
4141 return SECSuccess;
4142 }
4143
4144 /* Read up the next "bytes" number of bytes from the (decrypted) input
4145 * stream "b" (which is *length bytes long), and interpret them as an
4146 * integer in network byte order. Sets *num to the received value.
4147 * Reduces *length by bytes. Advances *b by bytes.
4148 *
4149 * On error, an alert has been sent, and a generic error code has been set.
4150 */
4151 SECStatus
ssl3_ConsumeHandshakeNumber64(sslSocket * ss,PRUint64 * num,PRUint32 bytes,PRUint8 ** b,PRUint32 * length)4152 ssl3_ConsumeHandshakeNumber64(sslSocket *ss, PRUint64 *num, PRUint32 bytes,
4153 PRUint8 **b, PRUint32 *length)
4154 {
4155 PRUint8 *buf = *b;
4156 PRUint32 i;
4157
4158 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4159 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4160
4161 *num = 0;
4162 if (bytes > sizeof(*num)) {
4163 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4164 return SECFailure;
4165 }
4166
4167 if (bytes > *length) {
4168 return ssl3_DecodeError(ss);
4169 }
4170 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4171
4172 for (i = 0; i < bytes; i++) {
4173 *num = (*num << 8) + buf[i];
4174 }
4175 *b += bytes;
4176 *length -= bytes;
4177 return SECSuccess;
4178 }
4179
4180 SECStatus
ssl3_ConsumeHandshakeNumber(sslSocket * ss,PRUint32 * num,PRUint32 bytes,PRUint8 ** b,PRUint32 * length)4181 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRUint32 *num, PRUint32 bytes,
4182 PRUint8 **b, PRUint32 *length)
4183 {
4184 PRUint64 num64;
4185 SECStatus rv;
4186
4187 PORT_Assert(bytes <= sizeof(*num));
4188 if (bytes > sizeof(*num)) {
4189 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4190 return SECFailure;
4191 }
4192 rv = ssl3_ConsumeHandshakeNumber64(ss, &num64, bytes, b, length);
4193 if (rv != SECSuccess) {
4194 return SECFailure;
4195 }
4196 *num = num64 & 0xffffffff;
4197 return SECSuccess;
4198 }
4199
4200 /* Read in two values from the incoming decrypted byte stream "b", which is
4201 * *length bytes long. The first value is a number whose size is "bytes"
4202 * bytes long. The second value is a byte-string whose size is the value
4203 * of the first number received. The latter byte-string, and its length,
4204 * is returned in the SECItem i.
4205 *
4206 * Returns SECFailure (-1) on failure.
4207 * On error, an alert has been sent, and a generic error code has been set.
4208 *
4209 * RADICAL CHANGE for NSS 3.11. All callers of this function make copies
4210 * of the data returned in the SECItem *i, so making a copy of it here
4211 * is simply wasteful. So, This function now just sets SECItem *i to
4212 * point to the values in the buffer **b.
4213 */
4214 SECStatus
ssl3_ConsumeHandshakeVariable(sslSocket * ss,SECItem * i,PRUint32 bytes,PRUint8 ** b,PRUint32 * length)4215 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRUint32 bytes,
4216 PRUint8 **b, PRUint32 *length)
4217 {
4218 PRUint32 count;
4219 SECStatus rv;
4220
4221 PORT_Assert(bytes <= 3);
4222 i->len = 0;
4223 i->data = NULL;
4224 i->type = siBuffer;
4225 rv = ssl3_ConsumeHandshakeNumber(ss, &count, bytes, b, length);
4226 if (rv != SECSuccess) {
4227 return SECFailure;
4228 }
4229 if (count > 0) {
4230 if (count > *length) {
4231 return ssl3_DecodeError(ss);
4232 }
4233 i->data = *b;
4234 i->len = count;
4235 *b += count;
4236 *length -= count;
4237 }
4238 return SECSuccess;
4239 }
4240
4241 /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
4242 * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
4243 *
4244 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4245 SECOidTag
ssl3_HashTypeToOID(SSLHashType hashType)4246 ssl3_HashTypeToOID(SSLHashType hashType)
4247 {
4248 switch (hashType) {
4249 case ssl_hash_sha1:
4250 return SEC_OID_SHA1;
4251 case ssl_hash_sha256:
4252 return SEC_OID_SHA256;
4253 case ssl_hash_sha384:
4254 return SEC_OID_SHA384;
4255 case ssl_hash_sha512:
4256 return SEC_OID_SHA512;
4257 default:
4258 break;
4259 }
4260 return SEC_OID_UNKNOWN;
4261 }
4262
4263 SECOidTag
ssl3_AuthTypeToOID(SSLAuthType authType)4264 ssl3_AuthTypeToOID(SSLAuthType authType)
4265 {
4266 switch (authType) {
4267 case ssl_auth_rsa_sign:
4268 return SEC_OID_PKCS1_RSA_ENCRYPTION;
4269 case ssl_auth_rsa_pss:
4270 return SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
4271 case ssl_auth_ecdsa:
4272 return SEC_OID_ANSIX962_EC_PUBLIC_KEY;
4273 case ssl_auth_dsa:
4274 return SEC_OID_ANSIX9_DSA_SIGNATURE;
4275 default:
4276 break;
4277 }
4278 /* shouldn't ever get there */
4279 PORT_Assert(0);
4280 return SEC_OID_UNKNOWN;
4281 }
4282
4283 SSLHashType
ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme)4284 ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme)
4285 {
4286 switch (scheme) {
4287 case ssl_sig_rsa_pkcs1_sha1:
4288 case ssl_sig_dsa_sha1:
4289 case ssl_sig_ecdsa_sha1:
4290 return ssl_hash_sha1;
4291 case ssl_sig_rsa_pkcs1_sha256:
4292 case ssl_sig_ecdsa_secp256r1_sha256:
4293 case ssl_sig_rsa_pss_rsae_sha256:
4294 case ssl_sig_rsa_pss_pss_sha256:
4295 case ssl_sig_dsa_sha256:
4296 return ssl_hash_sha256;
4297 case ssl_sig_rsa_pkcs1_sha384:
4298 case ssl_sig_ecdsa_secp384r1_sha384:
4299 case ssl_sig_rsa_pss_rsae_sha384:
4300 case ssl_sig_rsa_pss_pss_sha384:
4301 case ssl_sig_dsa_sha384:
4302 return ssl_hash_sha384;
4303 case ssl_sig_rsa_pkcs1_sha512:
4304 case ssl_sig_ecdsa_secp521r1_sha512:
4305 case ssl_sig_rsa_pss_rsae_sha512:
4306 case ssl_sig_rsa_pss_pss_sha512:
4307 case ssl_sig_dsa_sha512:
4308 return ssl_hash_sha512;
4309 case ssl_sig_rsa_pkcs1_sha1md5:
4310 return ssl_hash_none; /* Special for TLS 1.0/1.1. */
4311 case ssl_sig_none:
4312 case ssl_sig_ed25519:
4313 case ssl_sig_ed448:
4314 break;
4315 }
4316 PORT_Assert(0);
4317 return ssl_hash_none;
4318 }
4319
4320 static PRBool
ssl_SignatureSchemeMatchesSpkiOid(SSLSignatureScheme scheme,SECOidTag spkiOid)4321 ssl_SignatureSchemeMatchesSpkiOid(SSLSignatureScheme scheme, SECOidTag spkiOid)
4322 {
4323 SECOidTag authOid = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme));
4324
4325 if (spkiOid == authOid) {
4326 return PR_TRUE;
4327 }
4328 if ((authOid == SEC_OID_PKCS1_RSA_ENCRYPTION) &&
4329 (spkiOid == SEC_OID_X500_RSA_ENCRYPTION)) {
4330 return PR_TRUE;
4331 }
4332 return PR_FALSE;
4333 }
4334
4335 /* Validate that the signature scheme works for the given key type. */
4336 PRBool
ssl_SignatureSchemeValid(SSLSignatureScheme scheme,SECOidTag spkiOid,PRBool isTls13)4337 ssl_SignatureSchemeValid(SSLSignatureScheme scheme, SECOidTag spkiOid,
4338 PRBool isTls13)
4339 {
4340 if (!ssl_IsSupportedSignatureScheme(scheme)) {
4341 return PR_FALSE;
4342 }
4343 /* if we are purposefully passed SEC_OID_UNKNOWN, it means
4344 * we not checking the scheme against a potential key, so skip
4345 * the call */
4346 if ((spkiOid != SEC_OID_UNKNOWN) &&
4347 !ssl_SignatureSchemeMatchesSpkiOid(scheme, spkiOid)) {
4348 return PR_FALSE;
4349 }
4350 if (isTls13) {
4351 if (ssl_SignatureSchemeToHashType(scheme) == ssl_hash_sha1) {
4352 return PR_FALSE;
4353 }
4354 if (ssl_IsRsaPkcs1SignatureScheme(scheme)) {
4355 return PR_FALSE;
4356 }
4357 if (ssl_IsDsaSignatureScheme(scheme)) {
4358 return PR_FALSE;
4359 }
4360 /* With TLS 1.3, EC keys should have been selected based on calling
4361 * ssl_SignatureSchemeFromSpki(), reject them otherwise. */
4362 return spkiOid != SEC_OID_ANSIX962_EC_PUBLIC_KEY;
4363 }
4364 return PR_TRUE;
4365 }
4366
4367 static SECStatus
ssl_SignatureSchemeFromPssSpki(const CERTSubjectPublicKeyInfo * spki,SSLSignatureScheme * scheme)4368 ssl_SignatureSchemeFromPssSpki(const CERTSubjectPublicKeyInfo *spki,
4369 SSLSignatureScheme *scheme)
4370 {
4371 SECKEYRSAPSSParams pssParam = { 0 };
4372 PORTCheapArenaPool arena;
4373 SECStatus rv;
4374
4375 /* The key doesn't have parameters, boo. */
4376 if (!spki->algorithm.parameters.len) {
4377 *scheme = ssl_sig_none;
4378 return SECSuccess;
4379 }
4380
4381 PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE);
4382 rv = SEC_QuickDERDecodeItem(&arena.arena, &pssParam,
4383 SEC_ASN1_GET(SECKEY_RSAPSSParamsTemplate),
4384 &spki->algorithm.parameters);
4385 if (rv != SECSuccess) {
4386 goto loser;
4387 }
4388 /* Not having hashAlg means SHA-1 and we don't accept that. */
4389 if (!pssParam.hashAlg) {
4390 goto loser;
4391 }
4392 switch (SECOID_GetAlgorithmTag(pssParam.hashAlg)) {
4393 case SEC_OID_SHA256:
4394 *scheme = ssl_sig_rsa_pss_pss_sha256;
4395 break;
4396 case SEC_OID_SHA384:
4397 *scheme = ssl_sig_rsa_pss_pss_sha384;
4398 break;
4399 case SEC_OID_SHA512:
4400 *scheme = ssl_sig_rsa_pss_pss_sha512;
4401 break;
4402 default:
4403 goto loser;
4404 }
4405
4406 PORT_DestroyCheapArena(&arena);
4407 return SECSuccess;
4408
4409 loser:
4410 PORT_DestroyCheapArena(&arena);
4411 PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4412 return SECFailure;
4413 }
4414
4415 static SECStatus
ssl_SignatureSchemeFromEcSpki(const CERTSubjectPublicKeyInfo * spki,SSLSignatureScheme * scheme)4416 ssl_SignatureSchemeFromEcSpki(const CERTSubjectPublicKeyInfo *spki,
4417 SSLSignatureScheme *scheme)
4418 {
4419 const sslNamedGroupDef *group;
4420 SECKEYPublicKey *key;
4421
4422 key = SECKEY_ExtractPublicKey(spki);
4423 if (!key) {
4424 PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4425 return SECFailure;
4426 }
4427 group = ssl_ECPubKey2NamedGroup(key);
4428 SECKEY_DestroyPublicKey(key);
4429 if (!group) {
4430 PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4431 return SECFailure;
4432 }
4433 switch (group->name) {
4434 case ssl_grp_ec_secp256r1:
4435 *scheme = ssl_sig_ecdsa_secp256r1_sha256;
4436 return SECSuccess;
4437 case ssl_grp_ec_secp384r1:
4438 *scheme = ssl_sig_ecdsa_secp384r1_sha384;
4439 return SECSuccess;
4440 case ssl_grp_ec_secp521r1:
4441 *scheme = ssl_sig_ecdsa_secp521r1_sha512;
4442 return SECSuccess;
4443 default:
4444 break;
4445 }
4446 PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4447 return SECFailure;
4448 }
4449
4450 /* Newer signature schemes are designed so that a single SPKI can be used with
4451 * that scheme. This determines that scheme from the SPKI. If the SPKI doesn't
4452 * have a single scheme, |*scheme| is set to ssl_sig_none. */
4453 SECStatus
ssl_SignatureSchemeFromSpki(const CERTSubjectPublicKeyInfo * spki,PRBool isTls13,SSLSignatureScheme * scheme)4454 ssl_SignatureSchemeFromSpki(const CERTSubjectPublicKeyInfo *spki,
4455 PRBool isTls13, SSLSignatureScheme *scheme)
4456 {
4457 SECOidTag spkiOid = SECOID_GetAlgorithmTag(&spki->algorithm);
4458
4459 if (spkiOid == SEC_OID_PKCS1_RSA_PSS_SIGNATURE) {
4460 return ssl_SignatureSchemeFromPssSpki(spki, scheme);
4461 }
4462
4463 /* Only do this lookup for TLS 1.3, where the scheme can be determined from
4464 * the SPKI alone because the ECDSA key size determines the hash. Earlier
4465 * TLS versions allow the same EC key to be used with different hashes. */
4466 if (isTls13 && spkiOid == SEC_OID_ANSIX962_EC_PUBLIC_KEY) {
4467 return ssl_SignatureSchemeFromEcSpki(spki, scheme);
4468 }
4469
4470 *scheme = ssl_sig_none;
4471 return SECSuccess;
4472 }
4473
4474 /* Check that a signature scheme is enabled by configuration. */
4475 PRBool
ssl_SignatureSchemeEnabled(const sslSocket * ss,SSLSignatureScheme scheme)4476 ssl_SignatureSchemeEnabled(const sslSocket *ss, SSLSignatureScheme scheme)
4477 {
4478 unsigned int i;
4479 for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
4480 if (scheme == ss->ssl3.signatureSchemes[i]) {
4481 return PR_TRUE;
4482 }
4483 }
4484 return PR_FALSE;
4485 }
4486
4487 static PRBool
ssl_SignatureKeyMatchesSpkiOid(const ssl3KEADef * keaDef,SECOidTag spkiOid)4488 ssl_SignatureKeyMatchesSpkiOid(const ssl3KEADef *keaDef, SECOidTag spkiOid)
4489 {
4490 switch (spkiOid) {
4491 case SEC_OID_X500_RSA_ENCRYPTION:
4492 case SEC_OID_PKCS1_RSA_ENCRYPTION:
4493 case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
4494 return keaDef->signKeyType == rsaKey;
4495 case SEC_OID_ANSIX9_DSA_SIGNATURE:
4496 return keaDef->signKeyType == dsaKey;
4497 case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
4498 return keaDef->signKeyType == ecKey;
4499 default:
4500 break;
4501 }
4502 return PR_FALSE;
4503 }
4504
4505 /* ssl3_CheckSignatureSchemeConsistency checks that the signature algorithm
4506 * identifier in |scheme| is consistent with the public key in |spki|. It also
4507 * checks the hash algorithm against the configured signature algorithms. If
4508 * all the tests pass, SECSuccess is returned. Otherwise, PORT_SetError is
4509 * called and SECFailure is returned. */
4510 SECStatus
ssl_CheckSignatureSchemeConsistency(sslSocket * ss,SSLSignatureScheme scheme,CERTSubjectPublicKeyInfo * spki)4511 ssl_CheckSignatureSchemeConsistency(sslSocket *ss, SSLSignatureScheme scheme,
4512 CERTSubjectPublicKeyInfo *spki)
4513 {
4514 SSLSignatureScheme spkiScheme;
4515 PRBool isTLS13 = ss->version == SSL_LIBRARY_VERSION_TLS_1_3;
4516 SECOidTag spkiOid;
4517 SECStatus rv;
4518
4519 rv = ssl_SignatureSchemeFromSpki(spki, isTLS13, &spkiScheme);
4520 if (rv != SECSuccess) {
4521 return SECFailure;
4522 }
4523 if (spkiScheme != ssl_sig_none) {
4524 /* The SPKI in the certificate can only be used for a single scheme. */
4525 if (spkiScheme != scheme ||
4526 !ssl_SignatureSchemeEnabled(ss, scheme)) {
4527 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4528 return SECFailure;
4529 }
4530 return SECSuccess;
4531 }
4532
4533 spkiOid = SECOID_GetAlgorithmTag(&spki->algorithm);
4534
4535 /* If we're a client, check that the signature algorithm matches the signing
4536 * key type of the cipher suite. */
4537 if (!isTLS13 && !ss->sec.isServer) {
4538 if (!ssl_SignatureKeyMatchesSpkiOid(ss->ssl3.hs.kea_def, spkiOid)) {
4539 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4540 return SECFailure;
4541 }
4542 }
4543
4544 /* Verify that the signature scheme matches the signing key. */
4545 if ((spkiOid == SEC_OID_UNKNOWN) ||
4546 !ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13)) {
4547 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4548 return SECFailure;
4549 }
4550
4551 if (!ssl_SignatureSchemeEnabled(ss, scheme)) {
4552 PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
4553 return SECFailure;
4554 }
4555
4556 return SECSuccess;
4557 }
4558
4559 PRBool
ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme)4560 ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme)
4561 {
4562 switch (scheme) {
4563 case ssl_sig_rsa_pkcs1_sha1:
4564 case ssl_sig_rsa_pkcs1_sha256:
4565 case ssl_sig_rsa_pkcs1_sha384:
4566 case ssl_sig_rsa_pkcs1_sha512:
4567 case ssl_sig_rsa_pss_rsae_sha256:
4568 case ssl_sig_rsa_pss_rsae_sha384:
4569 case ssl_sig_rsa_pss_rsae_sha512:
4570 case ssl_sig_rsa_pss_pss_sha256:
4571 case ssl_sig_rsa_pss_pss_sha384:
4572 case ssl_sig_rsa_pss_pss_sha512:
4573 case ssl_sig_ecdsa_secp256r1_sha256:
4574 case ssl_sig_ecdsa_secp384r1_sha384:
4575 case ssl_sig_ecdsa_secp521r1_sha512:
4576 case ssl_sig_dsa_sha1:
4577 case ssl_sig_dsa_sha256:
4578 case ssl_sig_dsa_sha384:
4579 case ssl_sig_dsa_sha512:
4580 case ssl_sig_ecdsa_sha1:
4581 return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy);
4582 break;
4583
4584 case ssl_sig_rsa_pkcs1_sha1md5:
4585 case ssl_sig_none:
4586 case ssl_sig_ed25519:
4587 case ssl_sig_ed448:
4588 return PR_FALSE;
4589 }
4590 return PR_FALSE;
4591 }
4592
4593 PRBool
ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme)4594 ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme)
4595 {
4596 switch (scheme) {
4597 case ssl_sig_rsa_pss_rsae_sha256:
4598 case ssl_sig_rsa_pss_rsae_sha384:
4599 case ssl_sig_rsa_pss_rsae_sha512:
4600 case ssl_sig_rsa_pss_pss_sha256:
4601 case ssl_sig_rsa_pss_pss_sha384:
4602 case ssl_sig_rsa_pss_pss_sha512:
4603 return PR_TRUE;
4604
4605 default:
4606 return PR_FALSE;
4607 }
4608 return PR_FALSE;
4609 }
4610
4611 PRBool
ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme)4612 ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme)
4613 {
4614 switch (scheme) {
4615 case ssl_sig_rsa_pss_rsae_sha256:
4616 case ssl_sig_rsa_pss_rsae_sha384:
4617 case ssl_sig_rsa_pss_rsae_sha512:
4618 return PR_TRUE;
4619
4620 default:
4621 return PR_FALSE;
4622 }
4623 return PR_FALSE;
4624 }
4625
4626 PRBool
ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme)4627 ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme)
4628 {
4629 switch (scheme) {
4630 case ssl_sig_rsa_pkcs1_sha256:
4631 case ssl_sig_rsa_pkcs1_sha384:
4632 case ssl_sig_rsa_pkcs1_sha512:
4633 case ssl_sig_rsa_pkcs1_sha1:
4634 return PR_TRUE;
4635
4636 default:
4637 return PR_FALSE;
4638 }
4639 return PR_FALSE;
4640 }
4641
4642 PRBool
ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme)4643 ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme)
4644 {
4645 switch (scheme) {
4646 case ssl_sig_dsa_sha256:
4647 case ssl_sig_dsa_sha384:
4648 case ssl_sig_dsa_sha512:
4649 case ssl_sig_dsa_sha1:
4650 return PR_TRUE;
4651
4652 default:
4653 return PR_FALSE;
4654 }
4655 return PR_FALSE;
4656 }
4657
4658 SSLAuthType
ssl_SignatureSchemeToAuthType(SSLSignatureScheme scheme)4659 ssl_SignatureSchemeToAuthType(SSLSignatureScheme scheme)
4660 {
4661 switch (scheme) {
4662 case ssl_sig_rsa_pkcs1_sha1:
4663 case ssl_sig_rsa_pkcs1_sha1md5:
4664 case ssl_sig_rsa_pkcs1_sha256:
4665 case ssl_sig_rsa_pkcs1_sha384:
4666 case ssl_sig_rsa_pkcs1_sha512:
4667 /* We report based on the key type for PSS signatures. */
4668 case ssl_sig_rsa_pss_rsae_sha256:
4669 case ssl_sig_rsa_pss_rsae_sha384:
4670 case ssl_sig_rsa_pss_rsae_sha512:
4671 return ssl_auth_rsa_sign;
4672 case ssl_sig_rsa_pss_pss_sha256:
4673 case ssl_sig_rsa_pss_pss_sha384:
4674 case ssl_sig_rsa_pss_pss_sha512:
4675 return ssl_auth_rsa_pss;
4676 case ssl_sig_ecdsa_secp256r1_sha256:
4677 case ssl_sig_ecdsa_secp384r1_sha384:
4678 case ssl_sig_ecdsa_secp521r1_sha512:
4679 case ssl_sig_ecdsa_sha1:
4680 return ssl_auth_ecdsa;
4681 case ssl_sig_dsa_sha1:
4682 case ssl_sig_dsa_sha256:
4683 case ssl_sig_dsa_sha384:
4684 case ssl_sig_dsa_sha512:
4685 return ssl_auth_dsa;
4686
4687 default:
4688 PORT_Assert(0);
4689 }
4690 return ssl_auth_null;
4691 }
4692
4693 /* ssl_ConsumeSignatureScheme reads a SSLSignatureScheme (formerly
4694 * SignatureAndHashAlgorithm) structure from |b| and puts the resulting value
4695 * into |out|. |b| and |length| are updated accordingly.
4696 *
4697 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4698 SECStatus
ssl_ConsumeSignatureScheme(sslSocket * ss,PRUint8 ** b,PRUint32 * length,SSLSignatureScheme * out)4699 ssl_ConsumeSignatureScheme(sslSocket *ss, PRUint8 **b,
4700 PRUint32 *length, SSLSignatureScheme *out)
4701 {
4702 PRUint32 tmp;
4703 SECStatus rv;
4704
4705 rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
4706 if (rv != SECSuccess) {
4707 return SECFailure; /* Alert sent, Error code set already. */
4708 }
4709 if (!ssl_IsSupportedSignatureScheme((SSLSignatureScheme)tmp)) {
4710 SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
4711 PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
4712 return SECFailure;
4713 }
4714 *out = (SSLSignatureScheme)tmp;
4715 return SECSuccess;
4716 }
4717
4718 /**************************************************************************
4719 * end of Consume Handshake functions.
4720 **************************************************************************/
4721
4722 static SECStatus
ssl3_ComputeHandshakeHash(unsigned char * buf,unsigned int len,SSLHashType hashAlg,SSL3Hashes * hashes)4723 ssl3_ComputeHandshakeHash(unsigned char *buf, unsigned int len,
4724 SSLHashType hashAlg, SSL3Hashes *hashes)
4725 {
4726 SECStatus rv = SECFailure;
4727 PK11Context *hashContext = PK11_CreateDigestContext(
4728 ssl3_HashTypeToOID(hashAlg));
4729
4730 if (!hashContext) {
4731 return rv;
4732 }
4733 rv = PK11_DigestBegin(hashContext);
4734 if (rv == SECSuccess) {
4735 rv = PK11_DigestOp(hashContext, buf, len);
4736 }
4737 if (rv == SECSuccess) {
4738 rv = PK11_DigestFinal(hashContext, hashes->u.raw, &hashes->len,
4739 sizeof(hashes->u.raw));
4740 }
4741 if (rv == SECSuccess) {
4742 hashes->hashAlg = hashAlg;
4743 }
4744 PK11_DestroyContext(hashContext, PR_TRUE);
4745 return rv;
4746 }
4747
4748 /* Extract the hashes of handshake messages to this point.
4749 * Called from ssl3_SendCertificateVerify
4750 * ssl3_SendFinished
4751 * ssl3_HandleHandshakeMessage
4752 *
4753 * Caller must hold the SSL3HandshakeLock.
4754 * Caller must hold a read or write lock on the Spec R/W lock.
4755 * (There is presently no way to assert on a Read lock.)
4756 */
4757 SECStatus
ssl3_ComputeHandshakeHashes(sslSocket * ss,ssl3CipherSpec * spec,SSL3Hashes * hashes,PRUint32 sender)4758 ssl3_ComputeHandshakeHashes(sslSocket *ss,
4759 ssl3CipherSpec *spec, /* uses ->master_secret */
4760 SSL3Hashes *hashes, /* output goes here. */
4761 PRUint32 sender)
4762 {
4763 SECStatus rv = SECSuccess;
4764 PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
4765 unsigned int outLength;
4766 PRUint8 md5_inner[MAX_MAC_LENGTH];
4767 PRUint8 sha_inner[MAX_MAC_LENGTH];
4768
4769 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4770 if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
4771 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4772 return SECFailure;
4773 }
4774
4775 hashes->hashAlg = ssl_hash_none;
4776
4777 if (ss->ssl3.hs.hashType == handshake_hash_single) {
4778 PK11Context *h;
4779 unsigned int stateLen;
4780 unsigned char stackBuf[1024];
4781 unsigned char *stateBuf = NULL;
4782
4783 h = ss->ssl3.hs.sha;
4784 stateBuf = PK11_SaveContextAlloc(h, stackBuf,
4785 sizeof(stackBuf), &stateLen);
4786 if (stateBuf == NULL) {
4787 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4788 rv = SECFailure;
4789 goto tls12_loser;
4790 }
4791 rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
4792 sizeof(hashes->u.raw));
4793 if (rv != SECSuccess) {
4794 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4795 rv = SECFailure;
4796 goto tls12_loser;
4797 }
4798
4799 hashes->hashAlg = ssl3_GetSuitePrfHash(ss);
4800
4801 tls12_loser:
4802 if (stateBuf) {
4803 if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
4804 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4805 rv = SECFailure;
4806 }
4807 if (stateBuf != stackBuf) {
4808 PORT_ZFree(stateBuf, stateLen);
4809 }
4810 }
4811 } else if (ss->ssl3.hs.hashType == handshake_hash_record) {
4812 rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
4813 ss->ssl3.hs.messages.len,
4814 ssl3_GetSuitePrfHash(ss),
4815 hashes);
4816 } else {
4817 PK11Context *md5;
4818 PK11Context *sha = NULL;
4819 unsigned char *md5StateBuf = NULL;
4820 unsigned char *shaStateBuf = NULL;
4821 unsigned int md5StateLen, shaStateLen;
4822 unsigned char md5StackBuf[256];
4823 unsigned char shaStackBuf[512];
4824 const int md5Pad = ssl_GetMacDefByAlg(ssl_mac_md5)->pad_size;
4825 const int shaPad = ssl_GetMacDefByAlg(ssl_mac_sha)->pad_size;
4826
4827 md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
4828 sizeof md5StackBuf, &md5StateLen);
4829 if (md5StateBuf == NULL) {
4830 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4831 rv = SECFailure;
4832 goto loser;
4833 }
4834 md5 = ss->ssl3.hs.md5;
4835
4836 shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
4837 sizeof shaStackBuf, &shaStateLen);
4838 if (shaStateBuf == NULL) {
4839 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4840 rv = SECFailure;
4841 goto loser;
4842 }
4843 sha = ss->ssl3.hs.sha;
4844
4845 if (!isTLS) {
4846 /* compute hashes for SSL3. */
4847 unsigned char s[4];
4848
4849 if (!spec->masterSecret) {
4850 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4851 rv = SECFailure;
4852 goto loser;
4853 }
4854
4855 s[0] = (unsigned char)(sender >> 24);
4856 s[1] = (unsigned char)(sender >> 16);
4857 s[2] = (unsigned char)(sender >> 8);
4858 s[3] = (unsigned char)sender;
4859
4860 if (sender != 0) {
4861 rv |= PK11_DigestOp(md5, s, 4);
4862 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
4863 }
4864
4865 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, md5Pad));
4866
4867 rv |= PK11_DigestKey(md5, spec->masterSecret);
4868 rv |= PK11_DigestOp(md5, mac_pad_1, md5Pad);
4869 rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
4870 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4871 if (rv != SECSuccess) {
4872 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4873 rv = SECFailure;
4874 goto loser;
4875 }
4876
4877 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
4878
4879 if (sender != 0) {
4880 rv |= PK11_DigestOp(sha, s, 4);
4881 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
4882 }
4883
4884 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, shaPad));
4885
4886 rv |= PK11_DigestKey(sha, spec->masterSecret);
4887 rv |= PK11_DigestOp(sha, mac_pad_1, shaPad);
4888 rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
4889 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4890 if (rv != SECSuccess) {
4891 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4892 rv = SECFailure;
4893 goto loser;
4894 }
4895
4896 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
4897
4898 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, md5Pad));
4899 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
4900
4901 rv |= PK11_DigestBegin(md5);
4902 rv |= PK11_DigestKey(md5, spec->masterSecret);
4903 rv |= PK11_DigestOp(md5, mac_pad_2, md5Pad);
4904 rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
4905 }
4906 rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH);
4907 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4908 if (rv != SECSuccess) {
4909 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4910 rv = SECFailure;
4911 goto loser;
4912 }
4913
4914 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
4915
4916 if (!isTLS) {
4917 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, shaPad));
4918 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
4919
4920 rv |= PK11_DigestBegin(sha);
4921 rv |= PK11_DigestKey(sha, spec->masterSecret);
4922 rv |= PK11_DigestOp(sha, mac_pad_2, shaPad);
4923 rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
4924 }
4925 rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH);
4926 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4927 if (rv != SECSuccess) {
4928 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4929 rv = SECFailure;
4930 goto loser;
4931 }
4932
4933 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
4934
4935 hashes->len = MD5_LENGTH + SHA1_LENGTH;
4936
4937 loser:
4938 if (md5StateBuf) {
4939 if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) !=
4940 SECSuccess) {
4941 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4942 rv = SECFailure;
4943 }
4944 if (md5StateBuf != md5StackBuf) {
4945 PORT_ZFree(md5StateBuf, md5StateLen);
4946 }
4947 }
4948 if (shaStateBuf) {
4949 if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) !=
4950 SECSuccess) {
4951 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4952 rv = SECFailure;
4953 }
4954 if (shaStateBuf != shaStackBuf) {
4955 PORT_ZFree(shaStateBuf, shaStateLen);
4956 }
4957 }
4958 }
4959 return rv;
4960 }
4961
4962 /**************************************************************************
4963 * end of Handshake Hash functions.
4964 * Begin Send and Handle functions for handshakes.
4965 **************************************************************************/
4966
4967 #ifdef TRACE
4968 #define CHTYPE(t) \
4969 case client_hello_##t: \
4970 return #t;
4971
4972 static const char *
ssl_ClientHelloTypeName(sslClientHelloType type)4973 ssl_ClientHelloTypeName(sslClientHelloType type)
4974 {
4975 switch (type) {
4976 CHTYPE(initial);
4977 CHTYPE(retry);
4978 CHTYPE(retransmit); /* DTLS only */
4979 CHTYPE(renegotiation); /* TLS <= 1.2 only */
4980 }
4981 PORT_Assert(0);
4982 return NULL;
4983 }
4984 #undef CHTYPE
4985 #endif
4986
4987 PR_STATIC_ASSERT(SSL3_SESSIONID_BYTES == SSL3_RANDOM_LENGTH);
4988 static void
ssl_MakeFakeSid(sslSocket * ss,PRUint8 * buf)4989 ssl_MakeFakeSid(sslSocket *ss, PRUint8 *buf)
4990 {
4991 PRUint8 x = 0x5a;
4992 int i;
4993 for (i = 0; i < SSL3_SESSIONID_BYTES; ++i) {
4994 x += ss->ssl3.hs.client_random[i];
4995 buf[i] = x;
4996 }
4997 }
4998
4999 /* Set the version fields of the cipher spec for a ClientHello. */
5000 static void
ssl_SetClientHelloSpecVersion(sslSocket * ss,ssl3CipherSpec * spec)5001 ssl_SetClientHelloSpecVersion(sslSocket *ss, ssl3CipherSpec *spec)
5002 {
5003 ssl_GetSpecWriteLock(ss);
5004 PORT_Assert(spec->cipherDef->cipher == cipher_null);
5005 /* This is - a best guess - but it doesn't matter here. */
5006 spec->version = ss->vrange.max;
5007 if (IS_DTLS(ss)) {
5008 spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_0_WIRE;
5009 } else {
5010 /* For new connections, cap the record layer version number of TLS
5011 * ClientHello to { 3, 1 } (TLS 1.0). Some TLS 1.0 servers (which seem
5012 * to use F5 BIG-IP) ignore ClientHello.client_version and use the
5013 * record layer version number (TLSPlaintext.version) instead when
5014 * negotiating protocol versions. In addition, if the record layer
5015 * version number of ClientHello is { 3, 2 } (TLS 1.1) or higher, these
5016 * servers reset the TCP connections. Lastly, some F5 BIG-IP servers
5017 * hang if a record containing a ClientHello has a version greater than
5018 * { 3, 1 } and a length greater than 255. Set this flag to work around
5019 * such servers.
5020 *
5021 * The final version is set when a version is negotiated.
5022 */
5023 spec->recordVersion = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0,
5024 ss->vrange.max);
5025 }
5026 ssl_ReleaseSpecWriteLock(ss);
5027 }
5028
5029 SECStatus
ssl3_InsertChHeaderSize(const sslSocket * ss,sslBuffer * preamble,const sslBuffer * extensions)5030 ssl3_InsertChHeaderSize(const sslSocket *ss, sslBuffer *preamble, const sslBuffer *extensions)
5031 {
5032 SECStatus rv;
5033 unsigned int msgLen = preamble->len;
5034 msgLen += extensions->len ? (2 + extensions->len) : 0;
5035 unsigned int headerLen = IS_DTLS(ss) ? 12 : 4;
5036
5037 /* Record the message length. */
5038 rv = sslBuffer_InsertNumber(preamble, 1, msgLen - headerLen, 3);
5039 if (rv != SECSuccess) {
5040 return SECFailure; /* code set */
5041 }
5042 if (IS_DTLS(ss)) {
5043 /* Record the (unfragmented) fragment length. */
5044 unsigned int offset = 1 /* ch */ + 3 /* len */ +
5045 2 /* seq */ + 3 /* fragment offset */;
5046 rv = sslBuffer_InsertNumber(preamble, offset, msgLen - headerLen, 3);
5047 if (rv != SECSuccess) {
5048 return SECFailure; /* code set */
5049 }
5050 }
5051
5052 return SECSuccess;
5053 }
5054
5055 static SECStatus
ssl3_AppendCipherSuites(sslSocket * ss,PRBool fallbackSCSV,sslBuffer * buf)5056 ssl3_AppendCipherSuites(sslSocket *ss, PRBool fallbackSCSV, sslBuffer *buf)
5057 {
5058 SECStatus rv;
5059 unsigned int offset;
5060 unsigned int i;
5061 unsigned int saveLen;
5062
5063 rv = sslBuffer_Skip(buf, 2, &offset);
5064 if (rv != SECSuccess) {
5065 return SECFailure;
5066 }
5067
5068 if (ss->ssl3.hs.sendingSCSV) {
5069 /* Add the actual SCSV */
5070 rv = sslBuffer_AppendNumber(buf, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
5071 sizeof(ssl3CipherSuite));
5072 if (rv != SECSuccess) {
5073 return SECFailure;
5074 }
5075 }
5076 if (fallbackSCSV) {
5077 rv = sslBuffer_AppendNumber(buf, TLS_FALLBACK_SCSV,
5078 sizeof(ssl3CipherSuite));
5079 if (rv != SECSuccess) {
5080 return SECFailure;
5081 }
5082 }
5083
5084 saveLen = SSL_BUFFER_LEN(buf);
5085 /* CipherSuites are appended to Hello message here */
5086 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
5087 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
5088 if (ssl3_config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) {
5089 rv = sslBuffer_AppendNumber(buf, suite->cipher_suite,
5090 sizeof(ssl3CipherSuite));
5091 if (rv != SECSuccess) {
5092 return SECFailure;
5093 }
5094 }
5095 }
5096 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange) ||
5097 (SSL_BUFFER_LEN(buf) - saveLen) == 0) {
5098 PORT_SetError(SSL_ERROR_SSL_DISABLED);
5099 return SECFailure;
5100 }
5101
5102 return sslBuffer_InsertLength(buf, offset, 2);
5103 }
5104
5105 SECStatus
ssl3_CreateClientHelloPreamble(sslSocket * ss,const sslSessionID * sid,PRBool realSid,PRUint16 version,PRBool isEchInner,const sslBuffer * extensions,sslBuffer * preamble)5106 ssl3_CreateClientHelloPreamble(sslSocket *ss, const sslSessionID *sid,
5107 PRBool realSid, PRUint16 version, PRBool isEchInner,
5108 const sslBuffer *extensions, sslBuffer *preamble)
5109 {
5110 SECStatus rv;
5111 sslBuffer constructed = SSL_BUFFER_EMPTY;
5112 const PRUint8 *client_random = isEchInner ? ss->ssl3.hs.client_inner_random : ss->ssl3.hs.client_random;
5113 PORT_Assert(sid);
5114 PRBool fallbackSCSV = ss->opt.enableFallbackSCSV && !isEchInner &&
5115 (!realSid || version < sid->version);
5116
5117 rv = sslBuffer_AppendNumber(&constructed, ssl_hs_client_hello, 1);
5118 if (rv != SECSuccess) {
5119 goto loser;
5120 }
5121
5122 rv = sslBuffer_Skip(&constructed, 3, NULL);
5123 if (rv != SECSuccess) {
5124 goto loser;
5125 }
5126
5127 if (IS_DTLS(ss)) {
5128 /* Note that we make an unfragmented message here. We fragment in the
5129 * transmission code, if necessary */
5130 rv = sslBuffer_AppendNumber(&constructed, ss->ssl3.hs.sendMessageSeq, 2);
5131 if (rv != SECSuccess) {
5132 goto loser;
5133 }
5134 ss->ssl3.hs.sendMessageSeq++;
5135
5136 /* 0 is the fragment offset, because it's not fragmented yet */
5137 rv = sslBuffer_AppendNumber(&constructed, 0, 3);
5138 if (rv != SECSuccess) {
5139 goto loser;
5140 }
5141
5142 /* Fragment length -- set to the packet length because not fragmented */
5143 rv = sslBuffer_Skip(&constructed, 3, NULL);
5144 if (rv != SECSuccess) {
5145 goto loser;
5146 }
5147 }
5148
5149 if (ss->firstHsDone) {
5150 /* The client hello version must stay unchanged to work around
5151 * the Windows SChannel bug described in ssl3_SendClientHello. */
5152 PORT_Assert(version == ss->clientHelloVersion);
5153 }
5154
5155 ss->clientHelloVersion = PR_MIN(version, SSL_LIBRARY_VERSION_TLS_1_2);
5156 if (IS_DTLS(ss)) {
5157 PRUint16 dtlsVersion = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
5158 rv = sslBuffer_AppendNumber(&constructed, dtlsVersion, 2);
5159 } else {
5160 rv = sslBuffer_AppendNumber(&constructed, ss->clientHelloVersion, 2);
5161 }
5162 if (rv != SECSuccess) {
5163 goto loser;
5164 }
5165
5166 rv = sslBuffer_Append(&constructed, client_random, SSL3_RANDOM_LENGTH);
5167 if (rv != SECSuccess) {
5168 goto loser;
5169 }
5170
5171 if (sid->version < SSL_LIBRARY_VERSION_TLS_1_3 && !isEchInner) {
5172 rv = sslBuffer_AppendVariable(&constructed, sid->u.ssl3.sessionID,
5173 sid->u.ssl3.sessionIDLength, 1);
5174 } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) {
5175 /* We're faking session resumption, so rather than create new
5176 * randomness, just mix up the client random a little. */
5177 PRUint8 buf[SSL3_SESSIONID_BYTES];
5178 ssl_MakeFakeSid(ss, buf);
5179 rv = sslBuffer_AppendVariable(&constructed, buf, SSL3_SESSIONID_BYTES, 1);
5180 } else {
5181 rv = sslBuffer_AppendNumber(&constructed, 0, 1);
5182 }
5183 if (rv != SECSuccess) {
5184 goto loser;
5185 }
5186
5187 if (IS_DTLS(ss)) {
5188 /* This cookieLen applies to the cookie that appears in the DTLS
5189 * ClientHello, which isn't used in DTLS 1.3. */
5190 rv = sslBuffer_AppendVariable(&constructed, ss->ssl3.hs.cookie.data,
5191 ss->ssl3.hs.helloRetry ? 0 : ss->ssl3.hs.cookie.len,
5192 1);
5193 if (rv != SECSuccess) {
5194 goto loser;
5195 }
5196 }
5197
5198 rv = ssl3_AppendCipherSuites(ss, fallbackSCSV, &constructed);
5199 if (rv != SECSuccess) {
5200 goto loser;
5201 }
5202
5203 /* Compression methods: count is always 1, null compression. */
5204 rv = sslBuffer_AppendNumber(&constructed, 1, 1);
5205 if (rv != SECSuccess) {
5206 goto loser;
5207 }
5208 rv = sslBuffer_AppendNumber(&constructed, ssl_compression_null, 1);
5209 if (rv != SECSuccess) {
5210 goto loser;
5211 }
5212
5213 rv = ssl3_InsertChHeaderSize(ss, &constructed, extensions);
5214 if (rv != SECSuccess) {
5215 goto loser;
5216 }
5217
5218 *preamble = constructed;
5219 return SECSuccess;
5220 loser:
5221 sslBuffer_Clear(&constructed);
5222 return SECFailure;
5223 }
5224
5225 /* Called from ssl3_HandleHelloRequest(),
5226 * ssl3_RedoHandshake()
5227 * ssl_BeginClientHandshake (when resuming ssl3 session)
5228 * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
5229 *
5230 * The |type| argument indicates what is going on here:
5231 * - client_hello_initial is set for the very first ClientHello
5232 * - client_hello_retry indicates that this is a second attempt after receiving
5233 * a HelloRetryRequest (in TLS 1.3)
5234 * - client_hello_retransmit is used in DTLS when resending
5235 * - client_hello_renegotiation is used to renegotiate (in TLS <1.3)
5236 */
5237 SECStatus
ssl3_SendClientHello(sslSocket * ss,sslClientHelloType type)5238 ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type)
5239 {
5240 sslSessionID *sid;
5241 SECStatus rv;
5242 PRBool isTLS = PR_FALSE;
5243 PRBool requestingResume = PR_FALSE;
5244 PRBool unlockNeeded = PR_FALSE;
5245 sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
5246 PRUint16 version = ss->vrange.max;
5247 PRInt32 flags;
5248 sslBuffer chBuf = SSL_BUFFER_EMPTY;
5249
5250 SSL_TRC(3, ("%d: SSL3[%d]: send %s ClientHello handshake", SSL_GETPID(),
5251 ss->fd, ssl_ClientHelloTypeName(type)));
5252
5253 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5254 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5255
5256 /* shouldn't get here if SSL3 is disabled, but ... */
5257 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
5258 PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
5259 PORT_SetError(SSL_ERROR_SSL_DISABLED);
5260 return SECFailure;
5261 }
5262
5263 /* If we are responding to a HelloRetryRequest, don't reinitialize. We need
5264 * to maintain the handshake hashes. */
5265 if (!ss->ssl3.hs.helloRetry) {
5266 ssl3_RestartHandshakeHashes(ss);
5267 }
5268 PORT_Assert(!ss->ssl3.hs.helloRetry || type == client_hello_retry);
5269
5270 if (type == client_hello_initial) {
5271 ssl_SetClientHelloSpecVersion(ss, ss->ssl3.cwSpec);
5272 }
5273 /* These must be reset every handshake. */
5274 ssl3_ResetExtensionData(&ss->xtnData, ss);
5275 ss->ssl3.hs.sendingSCSV = PR_FALSE;
5276 ss->ssl3.hs.preliminaryInfo = 0;
5277 PORT_Assert(IS_DTLS(ss) || type != client_hello_retransmit);
5278 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
5279 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
5280
5281 /* How many suites does our PKCS11 support (regardless of policy)? */
5282 if (ssl3_config_match_init(ss) == 0) {
5283 return SECFailure; /* ssl3_config_match_init has set error code. */
5284 }
5285
5286 /*
5287 * During a renegotiation, ss->clientHelloVersion will be used again to
5288 * work around a Windows SChannel bug. Ensure that it is still enabled.
5289 */
5290 if (ss->firstHsDone) {
5291 PORT_Assert(type != client_hello_initial);
5292 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
5293 PORT_SetError(SSL_ERROR_SSL_DISABLED);
5294 return SECFailure;
5295 }
5296
5297 if (ss->clientHelloVersion < ss->vrange.min ||
5298 ss->clientHelloVersion > ss->vrange.max) {
5299 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
5300 return SECFailure;
5301 }
5302 }
5303
5304 /* Check if we have a ss->sec.ci.sid.
5305 * Check that it's not expired.
5306 * If we have an sid and it comes from an external cache, we use it. */
5307 if (ss->sec.ci.sid && ss->sec.ci.sid->cached == in_external_cache) {
5308 PORT_Assert(!ss->sec.isServer);
5309 sid = ssl_ReferenceSID(ss->sec.ci.sid);
5310 SSL_TRC(3, ("%d: SSL3[%d]: using external resumption token in ClientHello",
5311 SSL_GETPID(), ss->fd));
5312 } else if (ss->sec.ci.sid && ss->statelessResume && type == client_hello_retry) {
5313 /* If we are sending a second ClientHello, reuse the same SID
5314 * as the original one. */
5315 sid = ssl_ReferenceSID(ss->sec.ci.sid);
5316 } else if (!ss->opt.noCache) {
5317 /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
5318 * handles expired entries and other details.
5319 * XXX If we've been called from ssl_BeginClientHandshake, then
5320 * this lookup is duplicative and wasteful.
5321 */
5322 sid = ssl_LookupSID(ssl_Time(ss), &ss->sec.ci.peer,
5323 ss->sec.ci.port, ss->peerID, ss->url);
5324 } else {
5325 sid = NULL;
5326 }
5327
5328 /* We can't resume based on a different token. If the sid exists,
5329 * make sure the token that holds the master secret still exists ...
5330 * If we previously did client-auth, make sure that the token that holds
5331 * the private key still exists, is logged in, hasn't been removed, etc.
5332 */
5333 if (sid) {
5334 PRBool sidOK = PR_TRUE;
5335
5336 if (sid->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
5337 if (!tls13_ResumptionCompatible(ss, sid->u.ssl3.cipherSuite)) {
5338 sidOK = PR_FALSE;
5339 }
5340 } else {
5341 /* Check that the cipher suite we need is enabled. */
5342 const ssl3CipherSuiteCfg *suite =
5343 ssl_LookupCipherSuiteCfg(sid->u.ssl3.cipherSuite,
5344 ss->cipherSuites);
5345 SSLVersionRange vrange = { sid->version, sid->version };
5346 if (!suite || !ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
5347 sidOK = PR_FALSE;
5348 }
5349 }
5350
5351 /* Check that we can recover the master secret. */
5352 if (sidOK) {
5353 PK11SlotInfo *slot = NULL;
5354 if (sid->u.ssl3.masterValid) {
5355 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
5356 sid->u.ssl3.masterSlotID);
5357 }
5358 if (slot == NULL) {
5359 sidOK = PR_FALSE;
5360 } else {
5361 PK11SymKey *wrapKey = NULL;
5362 if (!PK11_IsPresent(slot) ||
5363 ((wrapKey = PK11_GetWrapKey(slot,
5364 sid->u.ssl3.masterWrapIndex,
5365 sid->u.ssl3.masterWrapMech,
5366 sid->u.ssl3.masterWrapSeries,
5367 ss->pkcs11PinArg)) == NULL)) {
5368 sidOK = PR_FALSE;
5369 }
5370 if (wrapKey)
5371 PK11_FreeSymKey(wrapKey);
5372 PK11_FreeSlot(slot);
5373 slot = NULL;
5374 }
5375 }
5376 /* If we previously did client-auth, make sure that the token that
5377 ** holds the private key still exists, is logged in, hasn't been
5378 ** removed, etc.
5379 */
5380 if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
5381 sidOK = PR_FALSE;
5382 }
5383
5384 if (sidOK) {
5385 /* Set version based on the sid. */
5386 if (ss->firstHsDone) {
5387 /*
5388 * Windows SChannel compares the client_version inside the RSA
5389 * EncryptedPreMasterSecret of a renegotiation with the
5390 * client_version of the initial ClientHello rather than the
5391 * ClientHello in the renegotiation. To work around this bug, we
5392 * continue to use the client_version used in the initial
5393 * ClientHello when renegotiating.
5394 *
5395 * The client_version of the initial ClientHello is still
5396 * available in ss->clientHelloVersion. Ensure that
5397 * sid->version is bounded within
5398 * [ss->vrange.min, ss->clientHelloVersion], otherwise we
5399 * can't use sid.
5400 */
5401 if (sid->version >= ss->vrange.min &&
5402 sid->version <= ss->clientHelloVersion) {
5403 version = ss->clientHelloVersion;
5404 } else {
5405 sidOK = PR_FALSE;
5406 }
5407 } else {
5408 /*
5409 * Check sid->version is OK first.
5410 * Previously, we would cap the version based on sid->version,
5411 * but that prevents negotiation of a higher version if the
5412 * previous session was reduced (e.g., with version fallback)
5413 */
5414 if (sid->version < ss->vrange.min ||
5415 sid->version > ss->vrange.max) {
5416 sidOK = PR_FALSE;
5417 }
5418 }
5419 }
5420
5421 if (!sidOK) {
5422 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_not_ok);
5423 ssl_UncacheSessionID(ss);
5424 ssl_FreeSID(sid);
5425 sid = NULL;
5426 }
5427 }
5428
5429 if (sid) {
5430 requestingResume = PR_TRUE;
5431 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_hits);
5432
5433 PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
5434 sid->u.ssl3.sessionIDLength));
5435
5436 ss->ssl3.policy = sid->u.ssl3.policy;
5437 } else {
5438 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_misses);
5439
5440 /*
5441 * Windows SChannel compares the client_version inside the RSA
5442 * EncryptedPreMasterSecret of a renegotiation with the
5443 * client_version of the initial ClientHello rather than the
5444 * ClientHello in the renegotiation. To work around this bug, we
5445 * continue to use the client_version used in the initial
5446 * ClientHello when renegotiating.
5447 */
5448 if (ss->firstHsDone) {
5449 version = ss->clientHelloVersion;
5450 }
5451
5452 sid = ssl3_NewSessionID(ss, PR_FALSE);
5453 if (!sid) {
5454 return SECFailure; /* memory error is set */
5455 }
5456 /* ss->version isn't set yet, but the sid needs a sane value. */
5457 sid->version = version;
5458 }
5459
5460 isTLS = (version > SSL_LIBRARY_VERSION_3_0);
5461 ssl_GetSpecWriteLock(ss);
5462 if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
5463 /* SSL records are not being MACed. */
5464 ss->ssl3.cwSpec->version = version;
5465 }
5466 ssl_ReleaseSpecWriteLock(ss);
5467
5468 ssl_FreeSID(ss->sec.ci.sid); /* release the old sid */
5469 ss->sec.ci.sid = sid;
5470
5471 /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV,
5472 * only if TLS is disabled.
5473 */
5474 if (!ss->firstHsDone && !isTLS) {
5475 /* Must set this before calling Hello Extension Senders,
5476 * to suppress sending of empty RI extension.
5477 */
5478 ss->ssl3.hs.sendingSCSV = PR_TRUE;
5479 }
5480
5481 /* When we attempt session resumption (only), we must lock the sid to
5482 * prevent races with other resumption connections that receive a
5483 * NewSessionTicket that will cause the ticket in the sid to be replaced.
5484 * Once we've copied the session ticket into our ClientHello message, it
5485 * is OK for the ticket to change, so we just need to make sure we hold
5486 * the lock across the calls to ssl_ConstructExtensions.
5487 */
5488 if (sid->u.ssl3.lock) {
5489 unlockNeeded = PR_TRUE;
5490 PR_RWLock_Rlock(sid->u.ssl3.lock);
5491 }
5492
5493 /* Generate a new random if this is the first attempt or renegotiation. */
5494 if (type == client_hello_initial ||
5495 type == client_hello_renegotiation) {
5496 rv = ssl3_GetNewRandom(ss->ssl3.hs.client_random);
5497 if (rv != SECSuccess) {
5498 goto loser; /* err set by GetNewRandom. */
5499 }
5500 }
5501
5502 if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
5503 rv = tls13_SetupClientHello(ss, type);
5504 if (rv != SECSuccess) {
5505 goto loser;
5506 }
5507 }
5508
5509 if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
5510 rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_client_hello);
5511 if (rv != SECSuccess) {
5512 goto loser;
5513 }
5514 }
5515
5516 if (IS_DTLS(ss)) {
5517 ssl3_DisableNonDTLSSuites(ss);
5518 }
5519
5520 rv = ssl3_CreateClientHelloPreamble(ss, sid, requestingResume, version,
5521 PR_FALSE, &extensionBuf, &chBuf);
5522 if (rv != SECSuccess) {
5523 goto loser; /* err set by ssl3_CreateClientHelloPreamble. */
5524 }
5525
5526 if (!ss->ssl3.hs.echHpkeCtx) {
5527 if (extensionBuf.len) {
5528 rv = tls13_MaybeGreaseEch(ss, chBuf.len, &extensionBuf);
5529 if (rv != SECSuccess) {
5530 goto loser; /* err set by tls13_MaybeGreaseEch. */
5531 }
5532 rv = ssl_InsertPaddingExtension(ss, chBuf.len, &extensionBuf);
5533 if (rv != SECSuccess) {
5534 goto loser; /* err set by ssl_InsertPaddingExtension. */
5535 }
5536
5537 rv = ssl3_InsertChHeaderSize(ss, &chBuf, &extensionBuf);
5538 if (rv != SECSuccess) {
5539 goto loser; /* err set by ssl3_InsertChHeaderSize. */
5540 }
5541
5542 /* If we are sending a PSK binder, replace the dummy value. */
5543 if (ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)) {
5544 rv = tls13_WriteExtensionsWithBinder(ss, &extensionBuf, &chBuf);
5545 } else {
5546 rv = sslBuffer_AppendNumber(&chBuf, extensionBuf.len, 2);
5547 if (rv != SECSuccess) {
5548 goto loser;
5549 }
5550 rv = sslBuffer_AppendBuffer(&chBuf, &extensionBuf);
5551 }
5552 if (rv != SECSuccess) {
5553 goto loser; /* err set by sslBuffer_Append*. */
5554 }
5555 }
5556
5557 /* If we already have a message in place, we need to enqueue it.
5558 * This empties the buffer. This is a convenient place to call
5559 * dtls_StageHandshakeMessage to mark the message boundary. */
5560 if (IS_DTLS(ss)) {
5561 rv = dtls_StageHandshakeMessage(ss);
5562 if (rv != SECSuccess) {
5563 goto loser;
5564 }
5565 }
5566 rv = ssl3_AppendHandshake(ss, chBuf.buf, chBuf.len);
5567 } else {
5568 rv = tls13_ConstructClientHelloWithEch(ss, sid, !requestingResume, &chBuf, &extensionBuf);
5569 if (rv != SECSuccess) {
5570 goto loser; /* code set */
5571 }
5572 rv = ssl3_UpdateDefaultHandshakeHashes(ss, chBuf.buf, chBuf.len);
5573 if (rv != SECSuccess) {
5574 goto loser; /* code set */
5575 }
5576
5577 if (IS_DTLS(ss)) {
5578 rv = dtls_StageHandshakeMessage(ss);
5579 if (rv != SECSuccess) {
5580 goto loser;
5581 }
5582 }
5583 /* By default, all messagess are added to both the inner and
5584 * outer transcripts. For CH (or CH2 if HRR), that's problematic. */
5585 rv = ssl3_AppendHandshakeSuppressHash(ss, chBuf.buf, chBuf.len);
5586 }
5587 if (rv != SECSuccess) {
5588 goto loser;
5589 }
5590
5591 if (unlockNeeded) {
5592 /* Note: goto loser can't be used past this point. */
5593 PR_RWLock_Unlock(sid->u.ssl3.lock);
5594 }
5595
5596 if (ss->xtnData.sentSessionTicketInClientHello) {
5597 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes);
5598 }
5599
5600 if (ss->ssl3.hs.sendingSCSV) {
5601 /* Since we sent the SCSV, pretend we sent empty RI extension. */
5602 TLSExtensionData *xtnData = &ss->xtnData;
5603 xtnData->advertised[xtnData->numAdvertised++] =
5604 ssl_renegotiation_info_xtn;
5605 }
5606
5607 flags = 0;
5608 rv = ssl3_FlushHandshake(ss, flags);
5609 if (rv != SECSuccess) {
5610 return rv; /* error code set by ssl3_FlushHandshake */
5611 }
5612
5613 if (version >= SSL_LIBRARY_VERSION_TLS_1_3) {
5614 rv = tls13_MaybeDo0RTTHandshake(ss);
5615 if (rv != SECSuccess) {
5616 return SECFailure; /* error code set already. */
5617 }
5618 }
5619
5620 ss->ssl3.hs.ws = wait_server_hello;
5621 sslBuffer_Clear(&chBuf);
5622 sslBuffer_Clear(&extensionBuf);
5623 return SECSuccess;
5624
5625 loser:
5626 if (unlockNeeded) {
5627 PR_RWLock_Unlock(sid->u.ssl3.lock);
5628 }
5629 sslBuffer_Clear(&chBuf);
5630 sslBuffer_Clear(&extensionBuf);
5631 return SECFailure;
5632 }
5633
5634 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
5635 * complete ssl3 Hello Request.
5636 * Caller must hold Handshake and RecvBuf locks.
5637 */
5638 static SECStatus
ssl3_HandleHelloRequest(sslSocket * ss)5639 ssl3_HandleHelloRequest(sslSocket *ss)
5640 {
5641 sslSessionID *sid = ss->sec.ci.sid;
5642 SECStatus rv;
5643
5644 SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
5645 SSL_GETPID(), ss->fd));
5646
5647 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
5648 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5649 PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
5650
5651 if (ss->ssl3.hs.ws == wait_server_hello)
5652 return SECSuccess;
5653 if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
5654 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
5655 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
5656 return SECFailure;
5657 }
5658 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
5659 (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation);
5660 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
5661 return SECFailure;
5662 }
5663
5664 if (sid) {
5665 ssl_UncacheSessionID(ss);
5666 ssl_FreeSID(sid);
5667 ss->sec.ci.sid = NULL;
5668 }
5669
5670 if (IS_DTLS(ss)) {
5671 dtls_RehandshakeCleanup(ss);
5672 }
5673
5674 ssl_GetXmitBufLock(ss);
5675 rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
5676 ssl_ReleaseXmitBufLock(ss);
5677
5678 return rv;
5679 }
5680
5681 static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
5682 CKM_DES3_ECB,
5683 CKM_CAST5_ECB,
5684 CKM_DES_ECB,
5685 CKM_KEY_WRAP_LYNKS,
5686 CKM_IDEA_ECB,
5687 CKM_CAST3_ECB,
5688 CKM_CAST_ECB,
5689 CKM_RC5_ECB,
5690 CKM_RC2_ECB,
5691 CKM_CDMF_ECB,
5692 CKM_SKIPJACK_WRAP,
5693 CKM_SKIPJACK_CBC64,
5694 CKM_AES_ECB,
5695 CKM_CAMELLIA_ECB,
5696 CKM_SEED_ECB
5697 };
5698
5699 static SECStatus
ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech,unsigned int * wrapMechIndex)5700 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech, unsigned int *wrapMechIndex)
5701 {
5702 unsigned int i;
5703 for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
5704 if (wrapMechanismList[i] == mech) {
5705 *wrapMechIndex = i;
5706 return SECSuccess;
5707 }
5708 }
5709 PORT_Assert(0);
5710 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5711 return SECFailure;
5712 }
5713
5714 /* Each process sharing the server session ID cache has its own array of SymKey
5715 * pointers for the symmetric wrapping keys that are used to wrap the master
5716 * secrets. There is one key for each authentication type. These Symkeys
5717 * correspond to the wrapped SymKeys kept in the server session cache.
5718 */
5719 const SSLAuthType ssl_wrap_key_auth_type[SSL_NUM_WRAP_KEYS] = {
5720 ssl_auth_rsa_decrypt,
5721 ssl_auth_rsa_sign,
5722 ssl_auth_rsa_pss,
5723 ssl_auth_ecdsa,
5724 ssl_auth_ecdh_rsa,
5725 ssl_auth_ecdh_ecdsa
5726 };
5727
5728 static SECStatus
ssl_FindIndexByWrapKey(const sslServerCert * serverCert,unsigned int * wrapKeyIndex)5729 ssl_FindIndexByWrapKey(const sslServerCert *serverCert, unsigned int *wrapKeyIndex)
5730 {
5731 unsigned int i;
5732 for (i = 0; i < SSL_NUM_WRAP_KEYS; ++i) {
5733 if (SSL_CERT_IS(serverCert, ssl_wrap_key_auth_type[i])) {
5734 *wrapKeyIndex = i;
5735 return SECSuccess;
5736 }
5737 }
5738 /* Can't assert here because we still get people using DSA certificates. */
5739 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5740 return SECFailure;
5741 }
5742
5743 static PK11SymKey *
ssl_UnwrapSymWrappingKey(SSLWrappedSymWrappingKey * pWswk,SECKEYPrivateKey * svrPrivKey,unsigned int wrapKeyIndex,CK_MECHANISM_TYPE masterWrapMech,void * pwArg)5744 ssl_UnwrapSymWrappingKey(
5745 SSLWrappedSymWrappingKey *pWswk,
5746 SECKEYPrivateKey *svrPrivKey,
5747 unsigned int wrapKeyIndex,
5748 CK_MECHANISM_TYPE masterWrapMech,
5749 void *pwArg)
5750 {
5751 PK11SymKey *unwrappedWrappingKey = NULL;
5752 SECItem wrappedKey;
5753 PK11SymKey *Ks;
5754 SECKEYPublicKey pubWrapKey;
5755 ECCWrappedKeyInfo *ecWrapped;
5756
5757 /* found the wrapping key on disk. */
5758 PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
5759 PORT_Assert(pWswk->wrapKeyIndex == wrapKeyIndex);
5760 if (pWswk->symWrapMechanism != masterWrapMech ||
5761 pWswk->wrapKeyIndex != wrapKeyIndex) {
5762 goto loser;
5763 }
5764 wrappedKey.type = siBuffer;
5765 wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
5766 wrappedKey.len = pWswk->wrappedSymKeyLen;
5767 PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
5768
5769 switch (ssl_wrap_key_auth_type[wrapKeyIndex]) {
5770
5771 case ssl_auth_rsa_decrypt:
5772 case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
5773 unwrappedWrappingKey =
5774 PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
5775 masterWrapMech, CKA_UNWRAP, 0);
5776 break;
5777
5778 case ssl_auth_ecdsa:
5779 case ssl_auth_ecdh_rsa:
5780 case ssl_auth_ecdh_ecdsa:
5781 /*
5782 * For ssl_auth_ecd*, we first create an EC public key based on
5783 * data stored with the wrappedSymmetricWrappingkey. Next,
5784 * we do an ECDH computation involving this public key and
5785 * the SSL server's (long-term) EC private key. The resulting
5786 * shared secret is treated the same way as Fortezza's Ks, i.e.,
5787 * it is used to recover the symmetric wrapping key.
5788 *
5789 * The data in wrappedSymmetricWrappingkey is laid out as defined
5790 * in the ECCWrappedKeyInfo structure.
5791 */
5792 ecWrapped = (ECCWrappedKeyInfo *)pWswk->wrappedSymmetricWrappingkey;
5793
5794 PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5795 ecWrapped->wrappedKeyLen <=
5796 MAX_EC_WRAPPED_KEY_BUFLEN);
5797
5798 if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5799 ecWrapped->wrappedKeyLen >
5800 MAX_EC_WRAPPED_KEY_BUFLEN) {
5801 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5802 goto loser;
5803 }
5804
5805 pubWrapKey.keyType = ecKey;
5806 pubWrapKey.u.ec.size = ecWrapped->size;
5807 pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
5808 pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
5809 pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
5810 pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
5811 ecWrapped->encodedParamLen;
5812
5813 wrappedKey.len = ecWrapped->wrappedKeyLen;
5814 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
5815 ecWrapped->pubValueLen;
5816
5817 /* Derive Ks using ECDH */
5818 Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
5819 NULL, CKM_ECDH1_DERIVE, masterWrapMech,
5820 CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5821 if (Ks == NULL) {
5822 goto loser;
5823 }
5824
5825 /* Use Ks to unwrap the wrapping key */
5826 unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL,
5827 &wrappedKey, masterWrapMech,
5828 CKA_UNWRAP, 0);
5829 PK11_FreeSymKey(Ks);
5830
5831 break;
5832
5833 default:
5834 PORT_Assert(0);
5835 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5836 goto loser;
5837 }
5838 loser:
5839 return unwrappedWrappingKey;
5840 }
5841
5842 typedef struct {
5843 PK11SymKey *symWrapKey[SSL_NUM_WRAP_KEYS];
5844 } ssl3SymWrapKey;
5845
5846 static PZLock *symWrapKeysLock = NULL;
5847 static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS];
5848
5849 SECStatus
ssl_FreeSymWrapKeysLock(void)5850 ssl_FreeSymWrapKeysLock(void)
5851 {
5852 if (symWrapKeysLock) {
5853 PZ_DestroyLock(symWrapKeysLock);
5854 symWrapKeysLock = NULL;
5855 return SECSuccess;
5856 }
5857 PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
5858 return SECFailure;
5859 }
5860
5861 SECStatus
SSL3_ShutdownServerCache(void)5862 SSL3_ShutdownServerCache(void)
5863 {
5864 int i, j;
5865
5866 if (!symWrapKeysLock)
5867 return SECSuccess; /* lock was never initialized */
5868 PZ_Lock(symWrapKeysLock);
5869 /* get rid of all symWrapKeys */
5870 for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
5871 for (j = 0; j < SSL_NUM_WRAP_KEYS; ++j) {
5872 PK11SymKey **pSymWrapKey;
5873 pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
5874 if (*pSymWrapKey) {
5875 PK11_FreeSymKey(*pSymWrapKey);
5876 *pSymWrapKey = NULL;
5877 }
5878 }
5879 }
5880
5881 PZ_Unlock(symWrapKeysLock);
5882 ssl_FreeSessionCacheLocks();
5883 return SECSuccess;
5884 }
5885
5886 SECStatus
ssl_InitSymWrapKeysLock(void)5887 ssl_InitSymWrapKeysLock(void)
5888 {
5889 symWrapKeysLock = PZ_NewLock(nssILockOther);
5890 return symWrapKeysLock ? SECSuccess : SECFailure;
5891 }
5892
5893 /* Try to get wrapping key for mechanism from in-memory array.
5894 * If that fails, look for one on disk.
5895 * If that fails, generate a new one, put the new one on disk,
5896 * Put the new key in the in-memory array.
5897 *
5898 * Note that this function performs some fairly inadvisable functions with
5899 * certificate private keys. ECDSA keys are used with ECDH; similarly, RSA
5900 * signing keys are used to encrypt. Bug 1248320.
5901 */
5902 PK11SymKey *
ssl3_GetWrappingKey(sslSocket * ss,PK11SlotInfo * masterSecretSlot,CK_MECHANISM_TYPE masterWrapMech,void * pwArg)5903 ssl3_GetWrappingKey(sslSocket *ss,
5904 PK11SlotInfo *masterSecretSlot,
5905 CK_MECHANISM_TYPE masterWrapMech,
5906 void *pwArg)
5907 {
5908 SSLAuthType authType;
5909 SECKEYPrivateKey *svrPrivKey;
5910 SECKEYPublicKey *svrPubKey = NULL;
5911 PK11SymKey *unwrappedWrappingKey = NULL;
5912 PK11SymKey **pSymWrapKey;
5913 CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM;
5914 int length;
5915 unsigned int wrapMechIndex;
5916 unsigned int wrapKeyIndex;
5917 SECStatus rv;
5918 SECItem wrappedKey;
5919 SSLWrappedSymWrappingKey wswk;
5920 PK11SymKey *Ks = NULL;
5921 SECKEYPublicKey *pubWrapKey = NULL;
5922 SECKEYPrivateKey *privWrapKey = NULL;
5923 ECCWrappedKeyInfo *ecWrapped;
5924 const sslServerCert *serverCert = ss->sec.serverCert;
5925
5926 PORT_Assert(serverCert);
5927 PORT_Assert(serverCert->serverKeyPair);
5928 PORT_Assert(serverCert->serverKeyPair->privKey);
5929 PORT_Assert(serverCert->serverKeyPair->pubKey);
5930 if (!serverCert || !serverCert->serverKeyPair ||
5931 !serverCert->serverKeyPair->privKey ||
5932 !serverCert->serverKeyPair->pubKey) {
5933 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5934 return NULL; /* hmm */
5935 }
5936
5937 rv = ssl_FindIndexByWrapKey(serverCert, &wrapKeyIndex);
5938 if (rv != SECSuccess)
5939 return NULL; /* unusable wrapping key. */
5940
5941 rv = ssl_FindIndexByWrapMechanism(masterWrapMech, &wrapMechIndex);
5942 if (rv != SECSuccess)
5943 return NULL; /* invalid masterWrapMech. */
5944
5945 authType = ssl_wrap_key_auth_type[wrapKeyIndex];
5946 svrPrivKey = serverCert->serverKeyPair->privKey;
5947 pSymWrapKey = &symWrapKeys[wrapMechIndex].symWrapKey[wrapKeyIndex];
5948
5949 ssl_InitSessionCacheLocks(PR_TRUE);
5950
5951 PZ_Lock(symWrapKeysLock);
5952
5953 unwrappedWrappingKey = *pSymWrapKey;
5954 if (unwrappedWrappingKey != NULL) {
5955 if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
5956 unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
5957 goto done;
5958 }
5959 /* slot series has changed, so this key is no good any more. */
5960 PK11_FreeSymKey(unwrappedWrappingKey);
5961 *pSymWrapKey = unwrappedWrappingKey = NULL;
5962 }
5963
5964 /* Try to get wrapped SymWrapping key out of the (disk) cache. */
5965 /* Following call fills in wswk on success. */
5966 rv = ssl_GetWrappingKey(wrapMechIndex, wrapKeyIndex, &wswk);
5967 if (rv == SECSuccess) {
5968 /* found the wrapped sym wrapping key on disk. */
5969 unwrappedWrappingKey =
5970 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
5971 masterWrapMech, pwArg);
5972 if (unwrappedWrappingKey) {
5973 goto install;
5974 }
5975 }
5976
5977 if (!masterSecretSlot) /* caller doesn't want to create a new one. */
5978 goto loser;
5979
5980 length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
5981 /* Zero length means fixed key length algorithm, or error.
5982 * It's ambiguous.
5983 */
5984 unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
5985 length, pwArg);
5986 if (!unwrappedWrappingKey) {
5987 goto loser;
5988 }
5989
5990 /* Prepare the buffer to receive the wrappedWrappingKey,
5991 * the symmetric wrapping key wrapped using the server's pub key.
5992 */
5993 PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */
5994
5995 svrPubKey = serverCert->serverKeyPair->pubKey;
5996 wrappedKey.type = siBuffer;
5997 wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey);
5998 wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
5999
6000 PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
6001 if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
6002 goto loser;
6003
6004 /* wrap symmetric wrapping key in server's public key. */
6005 switch (authType) {
6006 case ssl_auth_rsa_decrypt:
6007 case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
6008 case ssl_auth_rsa_pss:
6009 asymWrapMechanism = CKM_RSA_PKCS;
6010 rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
6011 unwrappedWrappingKey, &wrappedKey);
6012 break;
6013
6014 case ssl_auth_ecdsa:
6015 case ssl_auth_ecdh_rsa:
6016 case ssl_auth_ecdh_ecdsa:
6017 /*
6018 * We generate an ephemeral EC key pair. Perform an ECDH
6019 * computation involving this ephemeral EC public key and
6020 * the SSL server's (long-term) EC private key. The resulting
6021 * shared secret is treated in the same way as Fortezza's Ks,
6022 * i.e., it is used to wrap the wrapping key. To facilitate
6023 * unwrapping in ssl_UnwrapWrappingKey, we also store all
6024 * relevant info about the ephemeral EC public key in
6025 * wswk.wrappedSymmetricWrappingkey and lay it out as
6026 * described in the ECCWrappedKeyInfo structure.
6027 */
6028 PORT_Assert(SECKEY_GetPublicKeyType(svrPubKey) == ecKey);
6029 if (SECKEY_GetPublicKeyType(svrPubKey) != ecKey) {
6030 /* something is wrong in sslsecur.c if this isn't an ecKey */
6031 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6032 rv = SECFailure;
6033 goto ec_cleanup;
6034 }
6035
6036 privWrapKey = SECKEY_CreateECPrivateKey(
6037 &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
6038 if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
6039 rv = SECFailure;
6040 goto ec_cleanup;
6041 }
6042
6043 /* Set the key size in bits */
6044 if (pubWrapKey->u.ec.size == 0) {
6045 pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
6046 }
6047
6048 PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +
6049 pubWrapKey->u.ec.publicValue.len <
6050 MAX_EC_WRAPPED_KEY_BUFLEN);
6051 if (pubWrapKey->u.ec.DEREncodedParams.len +
6052 pubWrapKey->u.ec.publicValue.len >=
6053 MAX_EC_WRAPPED_KEY_BUFLEN) {
6054 PORT_SetError(SEC_ERROR_INVALID_KEY);
6055 rv = SECFailure;
6056 goto ec_cleanup;
6057 }
6058
6059 /* Derive Ks using ECDH */
6060 Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
6061 NULL, CKM_ECDH1_DERIVE, masterWrapMech,
6062 CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
6063 if (Ks == NULL) {
6064 rv = SECFailure;
6065 goto ec_cleanup;
6066 }
6067
6068 ecWrapped = (ECCWrappedKeyInfo *)(wswk.wrappedSymmetricWrappingkey);
6069 ecWrapped->size = pubWrapKey->u.ec.size;
6070 ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
6071 PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
6072 pubWrapKey->u.ec.DEREncodedParams.len);
6073
6074 ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
6075 PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen,
6076 pubWrapKey->u.ec.publicValue.data,
6077 pubWrapKey->u.ec.publicValue.len);
6078
6079 wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN -
6080 (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
6081 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
6082 ecWrapped->pubValueLen;
6083
6084 /* wrap symmetricWrapping key with the local Ks */
6085 rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
6086 unwrappedWrappingKey, &wrappedKey);
6087
6088 if (rv != SECSuccess) {
6089 goto ec_cleanup;
6090 }
6091
6092 /* Write down the length of wrapped key in the buffer
6093 * wswk.wrappedSymmetricWrappingkey at the appropriate offset
6094 */
6095 ecWrapped->wrappedKeyLen = wrappedKey.len;
6096
6097 ec_cleanup:
6098 if (privWrapKey)
6099 SECKEY_DestroyPrivateKey(privWrapKey);
6100 if (pubWrapKey)
6101 SECKEY_DestroyPublicKey(pubWrapKey);
6102 if (Ks)
6103 PK11_FreeSymKey(Ks);
6104 asymWrapMechanism = masterWrapMech;
6105 break;
6106
6107 default:
6108 rv = SECFailure;
6109 break;
6110 }
6111
6112 if (rv != SECSuccess) {
6113 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6114 goto loser;
6115 }
6116
6117 PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
6118
6119 wswk.symWrapMechanism = masterWrapMech;
6120 wswk.asymWrapMechanism = asymWrapMechanism;
6121 wswk.wrapMechIndex = wrapMechIndex;
6122 wswk.wrapKeyIndex = wrapKeyIndex;
6123 wswk.wrappedSymKeyLen = wrappedKey.len;
6124
6125 /* put it on disk. */
6126 /* If the wrapping key for this KEA type has already been set,
6127 * then abandon the value we just computed and
6128 * use the one we got from the disk.
6129 */
6130 rv = ssl_SetWrappingKey(&wswk);
6131 if (rv == SECSuccess) {
6132 /* somebody beat us to it. The original contents of our wswk
6133 * has been replaced with the content on disk. Now, discard
6134 * the key we just created and unwrap this new one.
6135 */
6136 PK11_FreeSymKey(unwrappedWrappingKey);
6137
6138 unwrappedWrappingKey =
6139 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
6140 masterWrapMech, pwArg);
6141 }
6142
6143 install:
6144 if (unwrappedWrappingKey) {
6145 *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
6146 }
6147
6148 loser:
6149 done:
6150 PZ_Unlock(symWrapKeysLock);
6151 return unwrappedWrappingKey;
6152 }
6153
6154 #ifdef NSS_ALLOW_SSLKEYLOGFILE
6155 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
6156 * bytes to |out|. */
6157 static void
hexEncode(char * out,const unsigned char * in,unsigned int length)6158 hexEncode(char *out, const unsigned char *in, unsigned int length)
6159 {
6160 static const char hextable[] = "0123456789abcdef";
6161 unsigned int i;
6162
6163 for (i = 0; i < length; i++) {
6164 *(out++) = hextable[in[i] >> 4];
6165 *(out++) = hextable[in[i] & 15];
6166 }
6167 }
6168 #endif
6169
6170 /* Called from ssl3_SendClientKeyExchange(). */
6171 static SECStatus
ssl3_SendRSAClientKeyExchange(sslSocket * ss,SECKEYPublicKey * svrPubKey)6172 ssl3_SendRSAClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
6173 {
6174 PK11SymKey *pms = NULL;
6175 SECStatus rv = SECFailure;
6176 SECItem enc_pms = { siBuffer, NULL, 0 };
6177 PRBool isTLS;
6178
6179 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6180 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6181
6182 /* Generate the pre-master secret ... */
6183 ssl_GetSpecWriteLock(ss);
6184 isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
6185
6186 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
6187 ssl_ReleaseSpecWriteLock(ss);
6188 if (pms == NULL) {
6189 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6190 goto loser;
6191 }
6192
6193 /* Get the wrapped (encrypted) pre-master secret, enc_pms */
6194 unsigned int svrPubKeyBits = SECKEY_PublicKeyStrengthInBits(svrPubKey);
6195 enc_pms.len = (svrPubKeyBits + 7) / 8;
6196 /* Check that the RSA key isn't larger than 8k bit. */
6197 if (svrPubKeyBits > SSL_MAX_RSA_KEY_BITS) {
6198 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
6199 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6200 goto loser;
6201 }
6202 enc_pms.data = (unsigned char *)PORT_Alloc(enc_pms.len);
6203 if (enc_pms.data == NULL) {
6204 goto loser; /* err set by PORT_Alloc */
6205 }
6206
6207 /* Wrap pre-master secret in server's public key. */
6208 rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
6209 if (rv != SECSuccess) {
6210 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6211 goto loser;
6212 }
6213
6214 #ifdef TRACE
6215 if (ssl_trace >= 100) {
6216 SECStatus extractRV = PK11_ExtractKeyValue(pms);
6217 if (extractRV == SECSuccess) {
6218 SECItem *keyData = PK11_GetKeyData(pms);
6219 if (keyData && keyData->data && keyData->len) {
6220 ssl_PrintBuf(ss, "Pre-Master Secret",
6221 keyData->data, keyData->len);
6222 }
6223 }
6224 }
6225 #endif
6226
6227 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
6228 isTLS ? enc_pms.len + 2
6229 : enc_pms.len);
6230 if (rv != SECSuccess) {
6231 goto loser; /* err set by ssl3_AppendHandshake* */
6232 }
6233 if (isTLS) {
6234 rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
6235 } else {
6236 rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
6237 }
6238 if (rv != SECSuccess) {
6239 goto loser; /* err set by ssl3_AppendHandshake* */
6240 }
6241
6242 rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
6243 PK11_FreeSymKey(pms);
6244 pms = NULL;
6245
6246 if (rv != SECSuccess) {
6247 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6248 goto loser;
6249 }
6250
6251 rv = SECSuccess;
6252
6253 loser:
6254 if (enc_pms.data != NULL) {
6255 PORT_Free(enc_pms.data);
6256 }
6257 if (pms != NULL) {
6258 PK11_FreeSymKey(pms);
6259 }
6260 return rv;
6261 }
6262
6263 /* DH shares need to be padded to the size of their prime. Some implementations
6264 * require this. TLS 1.3 also requires this. */
6265 SECStatus
ssl_AppendPaddedDHKeyShare(sslBuffer * buf,const SECKEYPublicKey * pubKey,PRBool appendLength)6266 ssl_AppendPaddedDHKeyShare(sslBuffer *buf, const SECKEYPublicKey *pubKey,
6267 PRBool appendLength)
6268 {
6269 SECStatus rv;
6270 unsigned int pad = pubKey->u.dh.prime.len - pubKey->u.dh.publicValue.len;
6271
6272 if (appendLength) {
6273 rv = sslBuffer_AppendNumber(buf, pubKey->u.dh.prime.len, 2);
6274 if (rv != SECSuccess) {
6275 return rv;
6276 }
6277 }
6278 while (pad) {
6279 rv = sslBuffer_AppendNumber(buf, 0, 1);
6280 if (rv != SECSuccess) {
6281 return rv;
6282 }
6283 --pad;
6284 }
6285 rv = sslBuffer_Append(buf, pubKey->u.dh.publicValue.data,
6286 pubKey->u.dh.publicValue.len);
6287 if (rv != SECSuccess) {
6288 return rv;
6289 }
6290 return SECSuccess;
6291 }
6292
6293 /* Called from ssl3_SendClientKeyExchange(). */
6294 static SECStatus
ssl3_SendDHClientKeyExchange(sslSocket * ss,SECKEYPublicKey * svrPubKey)6295 ssl3_SendDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
6296 {
6297 PK11SymKey *pms = NULL;
6298 SECStatus rv;
6299 PRBool isTLS;
6300 CK_MECHANISM_TYPE target;
6301
6302 const ssl3DHParams *params;
6303 ssl3DHParams customParams;
6304 const sslNamedGroupDef *groupDef;
6305 static const sslNamedGroupDef customGroupDef = {
6306 ssl_grp_ffdhe_custom, 0, ssl_kea_dh, SEC_OID_TLS_DHE_CUSTOM, PR_FALSE
6307 };
6308 sslEphemeralKeyPair *keyPair = NULL;
6309 SECKEYPublicKey *pubKey;
6310 PRUint8 dhData[SSL_MAX_DH_KEY_BITS / 8 + 2];
6311 sslBuffer dhBuf = SSL_BUFFER(dhData);
6312
6313 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6314 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6315
6316 isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
6317
6318 /* Copy DH parameters from server key */
6319
6320 if (SECKEY_GetPublicKeyType(svrPubKey) != dhKey) {
6321 PORT_SetError(SEC_ERROR_BAD_KEY);
6322 return SECFailure;
6323 }
6324
6325 /* Work out the parameters. */
6326 rv = ssl_ValidateDHENamedGroup(ss, &svrPubKey->u.dh.prime,
6327 &svrPubKey->u.dh.base,
6328 &groupDef, ¶ms);
6329 if (rv != SECSuccess) {
6330 /* If we require named groups, we will have already validated the group
6331 * in ssl_HandleDHServerKeyExchange() */
6332 PORT_Assert(!ss->opt.requireDHENamedGroups &&
6333 !ss->xtnData.peerSupportsFfdheGroups);
6334
6335 customParams.name = ssl_grp_ffdhe_custom;
6336 customParams.prime.data = svrPubKey->u.dh.prime.data;
6337 customParams.prime.len = svrPubKey->u.dh.prime.len;
6338 customParams.base.data = svrPubKey->u.dh.base.data;
6339 customParams.base.len = svrPubKey->u.dh.base.len;
6340 params = &customParams;
6341 groupDef = &customGroupDef;
6342 }
6343 ss->sec.keaGroup = groupDef;
6344
6345 rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
6346 if (rv != SECSuccess) {
6347 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
6348 goto loser;
6349 }
6350 pubKey = keyPair->keys->pubKey;
6351 PRINT_BUF(50, (ss, "DH public value:",
6352 pubKey->u.dh.publicValue.data,
6353 pubKey->u.dh.publicValue.len));
6354
6355 if (isTLS)
6356 target = CKM_TLS_MASTER_KEY_DERIVE_DH;
6357 else
6358 target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
6359
6360 /* Determine the PMS */
6361 pms = PK11_PubDerive(keyPair->keys->privKey, svrPubKey,
6362 PR_FALSE, NULL, NULL, CKM_DH_PKCS_DERIVE,
6363 target, CKA_DERIVE, 0, NULL);
6364
6365 if (pms == NULL) {
6366 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6367 goto loser;
6368 }
6369
6370 /* Note: send the DH share padded to avoid triggering bugs. */
6371 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
6372 params->prime.len + 2);
6373 if (rv != SECSuccess) {
6374 goto loser; /* err set by ssl3_AppendHandshake* */
6375 }
6376 rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE);
6377 if (rv != SECSuccess) {
6378 goto loser; /* err set by ssl_AppendPaddedDHKeyShare */
6379 }
6380 rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
6381 if (rv != SECSuccess) {
6382 goto loser; /* err set by ssl3_AppendBufferToHandshake */
6383 }
6384
6385 rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
6386 if (rv != SECSuccess) {
6387 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6388 goto loser;
6389 }
6390
6391 sslBuffer_Clear(&dhBuf);
6392 PK11_FreeSymKey(pms);
6393 ssl_FreeEphemeralKeyPair(keyPair);
6394 return SECSuccess;
6395
6396 loser:
6397 if (pms)
6398 PK11_FreeSymKey(pms);
6399 if (keyPair)
6400 ssl_FreeEphemeralKeyPair(keyPair);
6401 sslBuffer_Clear(&dhBuf);
6402 return SECFailure;
6403 }
6404
6405 /* Called from ssl3_HandleServerHelloDone(). */
6406 static SECStatus
ssl3_SendClientKeyExchange(sslSocket * ss)6407 ssl3_SendClientKeyExchange(sslSocket *ss)
6408 {
6409 SECKEYPublicKey *serverKey = NULL;
6410 SECStatus rv = SECFailure;
6411
6412 SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
6413 SSL_GETPID(), ss->fd));
6414
6415 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6416 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6417
6418 if (ss->sec.peerKey == NULL) {
6419 serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
6420 if (serverKey == NULL) {
6421 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
6422 return SECFailure;
6423 }
6424 } else {
6425 serverKey = ss->sec.peerKey;
6426 ss->sec.peerKey = NULL; /* we're done with it now */
6427 }
6428
6429 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
6430 ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
6431
6432 switch (ss->ssl3.hs.kea_def->exchKeyType) {
6433 case ssl_kea_rsa:
6434 rv = ssl3_SendRSAClientKeyExchange(ss, serverKey);
6435 break;
6436
6437 case ssl_kea_dh:
6438 rv = ssl3_SendDHClientKeyExchange(ss, serverKey);
6439 break;
6440
6441 case ssl_kea_ecdh:
6442 rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
6443 break;
6444
6445 default:
6446 PORT_Assert(0);
6447 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6448 break;
6449 }
6450
6451 SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
6452 SSL_GETPID(), ss->fd));
6453
6454 SECKEY_DestroyPublicKey(serverKey);
6455 return rv; /* err code already set. */
6456 }
6457
6458 /* Used by ssl_PickSignatureScheme(). */
6459 PRBool
ssl_CanUseSignatureScheme(SSLSignatureScheme scheme,const SSLSignatureScheme * peerSchemes,unsigned int peerSchemeCount,PRBool requireSha1,PRBool slotDoesPss)6460 ssl_CanUseSignatureScheme(SSLSignatureScheme scheme,
6461 const SSLSignatureScheme *peerSchemes,
6462 unsigned int peerSchemeCount,
6463 PRBool requireSha1,
6464 PRBool slotDoesPss)
6465 {
6466 SSLHashType hashType;
6467 unsigned int i;
6468
6469 /* Skip RSA-PSS schemes when the certificate's private key slot does
6470 * not support this signature mechanism. */
6471 if (ssl_IsRsaPssSignatureScheme(scheme) && !slotDoesPss) {
6472 return PR_FALSE;
6473 }
6474
6475 hashType = ssl_SignatureSchemeToHashType(scheme);
6476 if (requireSha1 && (hashType != ssl_hash_sha1)) {
6477 return PR_FALSE;
6478 }
6479
6480 if (!ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy)) {
6481 return PR_FALSE;
6482 }
6483
6484 for (i = 0; i < peerSchemeCount; i++) {
6485 if (peerSchemes[i] == scheme) {
6486 return PR_TRUE;
6487 }
6488 }
6489 return PR_FALSE;
6490 }
6491
6492 SECStatus
ssl_PrivateKeySupportsRsaPss(SECKEYPrivateKey * privKey,PRBool * supportsRsaPss)6493 ssl_PrivateKeySupportsRsaPss(SECKEYPrivateKey *privKey,
6494 PRBool *supportsRsaPss)
6495 {
6496 PK11SlotInfo *slot;
6497 slot = PK11_GetSlotFromPrivateKey(privKey);
6498 if (!slot) {
6499 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6500 return SECFailure;
6501 }
6502 *supportsRsaPss = PK11_DoesMechanism(slot, auth_alg_defs[ssl_auth_rsa_pss]);
6503 PK11_FreeSlot(slot);
6504 return SECSuccess;
6505 }
6506
6507 SECStatus
ssl_PickSignatureScheme(sslSocket * ss,CERTCertificate * cert,SECKEYPublicKey * pubKey,SECKEYPrivateKey * privKey,const SSLSignatureScheme * peerSchemes,unsigned int peerSchemeCount,PRBool requireSha1)6508 ssl_PickSignatureScheme(sslSocket *ss,
6509 CERTCertificate *cert,
6510 SECKEYPublicKey *pubKey,
6511 SECKEYPrivateKey *privKey,
6512 const SSLSignatureScheme *peerSchemes,
6513 unsigned int peerSchemeCount,
6514 PRBool requireSha1)
6515 {
6516 unsigned int i;
6517 PRBool doesRsaPss;
6518 PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
6519 SECStatus rv;
6520 SSLSignatureScheme scheme;
6521 SECOidTag spkiOid;
6522
6523 /* We can't require SHA-1 in TLS 1.3. */
6524 PORT_Assert(!(requireSha1 && isTLS13));
6525 if (!pubKey || !privKey) {
6526 PORT_Assert(0);
6527 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6528 return SECFailure;
6529 }
6530
6531 rv = ssl_PrivateKeySupportsRsaPss(privKey, &doesRsaPss);
6532 if (rv != SECSuccess) {
6533 return SECFailure;
6534 }
6535
6536 /* If the certificate SPKI indicates a single scheme, don't search. */
6537 rv = ssl_SignatureSchemeFromSpki(&cert->subjectPublicKeyInfo,
6538 isTLS13, &scheme);
6539 if (rv != SECSuccess) {
6540 return SECFailure;
6541 }
6542 if (scheme != ssl_sig_none) {
6543 if (!ssl_SignatureSchemeEnabled(ss, scheme) ||
6544 !ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
6545 requireSha1, doesRsaPss)) {
6546 PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
6547 return SECFailure;
6548 }
6549 ss->ssl3.hs.signatureScheme = scheme;
6550 return SECSuccess;
6551 }
6552
6553 spkiOid = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm);
6554 if (spkiOid == SEC_OID_UNKNOWN) {
6555 return SECFailure;
6556 }
6557
6558 /* Now we have to search based on the key type. Go through our preferred
6559 * schemes in order and find the first that can be used. */
6560 for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
6561 scheme = ss->ssl3.signatureSchemes[i];
6562
6563 if (ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13) &&
6564 ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
6565 requireSha1, doesRsaPss)) {
6566 ss->ssl3.hs.signatureScheme = scheme;
6567 return SECSuccess;
6568 }
6569 }
6570
6571 PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
6572 return SECFailure;
6573 }
6574
6575 static SECStatus
ssl_PickFallbackSignatureScheme(sslSocket * ss,SECKEYPublicKey * pubKey)6576 ssl_PickFallbackSignatureScheme(sslSocket *ss, SECKEYPublicKey *pubKey)
6577 {
6578 PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
6579
6580 switch (SECKEY_GetPublicKeyType(pubKey)) {
6581 case rsaKey:
6582 if (isTLS12) {
6583 ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1;
6584 } else {
6585 ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1md5;
6586 }
6587 break;
6588 case ecKey:
6589 ss->ssl3.hs.signatureScheme = ssl_sig_ecdsa_sha1;
6590 break;
6591 case dsaKey:
6592 ss->ssl3.hs.signatureScheme = ssl_sig_dsa_sha1;
6593 break;
6594 default:
6595 PORT_Assert(0);
6596 PORT_SetError(SEC_ERROR_INVALID_KEY);
6597 return SECFailure;
6598 }
6599 return SECSuccess;
6600 }
6601
6602 /* ssl3_PickServerSignatureScheme selects a signature scheme for signing the
6603 * handshake. Most of this is determined by the key pair we are using.
6604 * Prior to TLS 1.2, the MD5/SHA1 combination is always used. With TLS 1.2, a
6605 * client may advertise its support for signature and hash combinations. */
6606 static SECStatus
ssl3_PickServerSignatureScheme(sslSocket * ss)6607 ssl3_PickServerSignatureScheme(sslSocket *ss)
6608 {
6609 const sslServerCert *cert = ss->sec.serverCert;
6610 PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
6611
6612 if (!isTLS12 || !ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) {
6613 /* If the client didn't provide any signature_algorithms extension then
6614 * we can assume that they support SHA-1: RFC5246, Section 7.4.1.4.1. */
6615 return ssl_PickFallbackSignatureScheme(ss, cert->serverKeyPair->pubKey);
6616 }
6617
6618 /* Sets error code, if needed. */
6619 return ssl_PickSignatureScheme(ss, cert->serverCert,
6620 cert->serverKeyPair->pubKey,
6621 cert->serverKeyPair->privKey,
6622 ss->xtnData.sigSchemes,
6623 ss->xtnData.numSigSchemes,
6624 PR_FALSE /* requireSha1 */);
6625 }
6626
6627 static SECStatus
ssl_PickClientSignatureScheme(sslSocket * ss,const SSLSignatureScheme * schemes,unsigned int numSchemes)6628 ssl_PickClientSignatureScheme(sslSocket *ss, const SSLSignatureScheme *schemes,
6629 unsigned int numSchemes)
6630 {
6631 SECKEYPrivateKey *privKey = ss->ssl3.clientPrivateKey;
6632 SECStatus rv;
6633 PRBool isTLS13 = (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
6634 SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(ss->ssl3.clientCertificate);
6635
6636 PORT_Assert(pubKey);
6637
6638 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
6639 /* We should have already checked that a signature scheme was
6640 * listed in the request. */
6641 PORT_Assert(schemes && numSchemes > 0);
6642 }
6643
6644 if (!isTLS13 &&
6645 (SECKEY_GetPublicKeyType(pubKey) == rsaKey ||
6646 SECKEY_GetPublicKeyType(pubKey) == dsaKey) &&
6647 SECKEY_PublicKeyStrengthInBits(pubKey) <= 1024) {
6648 /* If the key is a 1024-bit RSA or DSA key, assume conservatively that
6649 * it may be unable to sign SHA-256 hashes. This is the case for older
6650 * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and
6651 * older, DSA key size is at most 1024 bits and the hash function must
6652 * be SHA-1.
6653 */
6654 rv = ssl_PickSignatureScheme(ss, ss->ssl3.clientCertificate,
6655 pubKey, privKey, schemes, numSchemes,
6656 PR_TRUE /* requireSha1 */);
6657 if (rv == SECSuccess) {
6658 SECKEY_DestroyPublicKey(pubKey);
6659 return SECSuccess;
6660 }
6661 /* If this fails, that's because the peer doesn't advertise SHA-1,
6662 * so fall back to the full negotiation. */
6663 }
6664 rv = ssl_PickSignatureScheme(ss, ss->ssl3.clientCertificate,
6665 pubKey, privKey, schemes, numSchemes,
6666 PR_FALSE /* requireSha1 */);
6667 SECKEY_DestroyPublicKey(pubKey);
6668 return rv;
6669 }
6670
6671 /* Called from ssl3_HandleServerHelloDone(). */
6672 static SECStatus
ssl3_SendCertificateVerify(sslSocket * ss,SECKEYPrivateKey * privKey)6673 ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
6674 {
6675 SECStatus rv = SECFailure;
6676 PRBool isTLS12;
6677 SECItem buf = { siBuffer, NULL, 0 };
6678 SSL3Hashes hashes;
6679 unsigned int len;
6680 SSLHashType hashAlg;
6681
6682 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6683 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6684
6685 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
6686 SSL_GETPID(), ss->fd));
6687
6688 ssl_GetSpecReadLock(ss);
6689
6690 if (ss->ssl3.hs.hashType == handshake_hash_record) {
6691 hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
6692 } else {
6693 /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
6694 hashAlg = ssl_hash_none;
6695 }
6696 if (ss->ssl3.hs.hashType == handshake_hash_record &&
6697 hashAlg != ssl3_GetSuitePrfHash(ss)) {
6698 rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
6699 ss->ssl3.hs.messages.len,
6700 hashAlg, &hashes);
6701 if (rv != SECSuccess) {
6702 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
6703 }
6704 } else {
6705 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
6706 }
6707 ssl_ReleaseSpecReadLock(ss);
6708 if (rv != SECSuccess) {
6709 goto done; /* err code was set by ssl3_ComputeHandshakeHash(es) */
6710 }
6711
6712 isTLS12 = (PRBool)(ss->version == SSL_LIBRARY_VERSION_TLS_1_2);
6713 PORT_Assert(ss->version <= SSL_LIBRARY_VERSION_TLS_1_2);
6714
6715 rv = ssl3_SignHashes(ss, &hashes, privKey, &buf);
6716 if (rv == SECSuccess && !ss->sec.isServer) {
6717 /* Remember the info about the slot that did the signing.
6718 ** Later, when doing an SSL restart handshake, verify this.
6719 ** These calls are mere accessors, and can't fail.
6720 */
6721 PK11SlotInfo *slot;
6722 sslSessionID *sid = ss->sec.ci.sid;
6723
6724 slot = PK11_GetSlotFromPrivateKey(privKey);
6725 sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
6726 sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
6727 sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
6728 sid->u.ssl3.clAuthValid = PR_TRUE;
6729 PK11_FreeSlot(slot);
6730 }
6731 if (rv != SECSuccess) {
6732 goto done; /* err code was set by ssl3_SignHashes */
6733 }
6734
6735 len = buf.len + 2 + (isTLS12 ? 2 : 0);
6736
6737 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len);
6738 if (rv != SECSuccess) {
6739 goto done; /* error code set by AppendHandshake */
6740 }
6741 if (isTLS12) {
6742 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
6743 if (rv != SECSuccess) {
6744 goto done; /* err set by AppendHandshake. */
6745 }
6746 }
6747 rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
6748 if (rv != SECSuccess) {
6749 goto done; /* error code set by AppendHandshake */
6750 }
6751
6752 done:
6753 if (buf.data)
6754 PORT_Free(buf.data);
6755 return rv;
6756 }
6757
6758 /* Once a cipher suite has been selected, make sure that the necessary secondary
6759 * information is properly set. */
6760 SECStatus
ssl3_SetupCipherSuite(sslSocket * ss,PRBool initHashes)6761 ssl3_SetupCipherSuite(sslSocket *ss, PRBool initHashes)
6762 {
6763 ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
6764 if (!ss->ssl3.hs.suite_def) {
6765 PORT_Assert(0);
6766 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6767 return SECFailure;
6768 }
6769
6770 ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg];
6771 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite;
6772
6773 if (!initHashes) {
6774 return SECSuccess;
6775 }
6776 /* Now we have a cipher suite, initialize the handshake hashes. */
6777 return ssl3_InitHandshakeHashes(ss);
6778 }
6779
6780 SECStatus
ssl_ClientSetCipherSuite(sslSocket * ss,SSL3ProtocolVersion version,ssl3CipherSuite suite,PRBool initHashes)6781 ssl_ClientSetCipherSuite(sslSocket *ss, SSL3ProtocolVersion version,
6782 ssl3CipherSuite suite, PRBool initHashes)
6783 {
6784 unsigned int i;
6785 if (ssl3_config_match_init(ss) == 0) {
6786 PORT_Assert(PR_FALSE);
6787 return SECFailure;
6788 }
6789 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
6790 ssl3CipherSuiteCfg *suiteCfg = &ss->cipherSuites[i];
6791 if (suite == suiteCfg->cipher_suite) {
6792 SSLVersionRange vrange = { version, version };
6793 if (!ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) {
6794 /* config_match already checks whether the cipher suite is
6795 * acceptable for the version, but the check is repeated here
6796 * in order to give a more precise error code. */
6797 if (!ssl3_CipherSuiteAllowedForVersionRange(suite, &vrange)) {
6798 PORT_SetError(SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION);
6799 } else {
6800 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
6801 }
6802 return SECFailure;
6803 }
6804 break;
6805 }
6806 }
6807 if (i >= ssl_V3_SUITES_IMPLEMENTED) {
6808 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
6809 return SECFailure;
6810 }
6811
6812 /* Don't let the server change its mind. */
6813 if (ss->ssl3.hs.helloRetry && suite != ss->ssl3.hs.cipher_suite) {
6814 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
6815 PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
6816 return SECFailure;
6817 }
6818
6819 ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)suite;
6820 return ssl3_SetupCipherSuite(ss, initHashes);
6821 }
6822
6823 /* Check that session ID we received from the server, if any, matches our
6824 * expectations, depending on whether we're in compat mode and whether we
6825 * negotiated TLS 1.3+ or TLS 1.2-.
6826 */
6827 static PRBool
ssl_CheckServerSessionIdCorrectness(sslSocket * ss,SECItem * sidBytes)6828 ssl_CheckServerSessionIdCorrectness(sslSocket *ss, SECItem *sidBytes)
6829 {
6830 sslSessionID *sid = ss->sec.ci.sid;
6831 PRBool sidMatch = PR_FALSE;
6832 PRBool sentFakeSid = PR_FALSE;
6833 PRBool sentRealSid = sid && sid->version < SSL_LIBRARY_VERSION_TLS_1_3;
6834
6835 /* If attempting to resume a TLS 1.2 connection, the session ID won't be a
6836 * fake. Check for the real value. */
6837 if (sentRealSid) {
6838 sidMatch = (sidBytes->len == sid->u.ssl3.sessionIDLength) &&
6839 (!sidBytes->len || PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len) == 0);
6840 } else {
6841 /* Otherwise, the session ID was a fake if TLS 1.3 compat mode is
6842 * enabled. If so, check for the fake value. */
6843 sentFakeSid = ss->opt.enableTls13CompatMode && !IS_DTLS(ss);
6844 if (sentFakeSid && sidBytes->len == SSL3_SESSIONID_BYTES) {
6845 PRUint8 buf[SSL3_SESSIONID_BYTES];
6846 ssl_MakeFakeSid(ss, buf);
6847 sidMatch = PORT_Memcmp(buf, sidBytes->data, sidBytes->len) == 0;
6848 }
6849 }
6850
6851 /* TLS 1.2: Session ID shouldn't match if we sent a fake. */
6852 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
6853 if (sentFakeSid) {
6854 return !sidMatch;
6855 }
6856 return PR_TRUE;
6857 }
6858
6859 /* TLS 1.3: We sent a session ID. The server's should match. */
6860 if (!IS_DTLS(ss) && (sentRealSid || sentFakeSid)) {
6861 return sidMatch;
6862 }
6863
6864 /* TLS 1.3 (no SID)/DTLS 1.3: The server shouldn't send a session ID. */
6865 return sidBytes->len == 0;
6866 }
6867
6868 static SECStatus
ssl_CheckServerRandom(sslSocket * ss)6869 ssl_CheckServerRandom(sslSocket *ss)
6870 {
6871 /* Check the ServerHello.random per [RFC 8446 Section 4.1.3].
6872 *
6873 * TLS 1.3 clients receiving a ServerHello indicating TLS 1.2 or below
6874 * MUST check that the last 8 bytes are not equal to either of these
6875 * values. TLS 1.2 clients SHOULD also check that the last 8 bytes are
6876 * not equal to the second value if the ServerHello indicates TLS 1.1 or
6877 * below. If a match is found, the client MUST abort the handshake with
6878 * an "illegal_parameter" alert.
6879 */
6880 SSL3ProtocolVersion checkVersion =
6881 ss->ssl3.downgradeCheckVersion ? ss->ssl3.downgradeCheckVersion
6882 : ss->vrange.max;
6883
6884 if (checkVersion >= SSL_LIBRARY_VERSION_TLS_1_2 &&
6885 checkVersion > ss->version) {
6886 /* Both sections use the same sentinel region. */
6887 PRUint8 *downgrade_sentinel =
6888 ss->ssl3.hs.server_random +
6889 SSL3_RANDOM_LENGTH - sizeof(tls12_downgrade_random);
6890
6891 if (!PORT_Memcmp(downgrade_sentinel,
6892 tls12_downgrade_random,
6893 sizeof(tls12_downgrade_random)) ||
6894 !PORT_Memcmp(downgrade_sentinel,
6895 tls1_downgrade_random,
6896 sizeof(tls1_downgrade_random))) {
6897 return SECFailure;
6898 }
6899 }
6900
6901 return SECSuccess;
6902 }
6903
6904 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6905 * ssl3 ServerHello message.
6906 * Caller must hold Handshake and RecvBuf locks.
6907 */
6908 static SECStatus
ssl3_HandleServerHello(sslSocket * ss,PRUint8 * b,PRUint32 length)6909 ssl3_HandleServerHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
6910 {
6911 PRUint32 cipher;
6912 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6913 PRUint32 compression;
6914 SECStatus rv;
6915 SECItem sidBytes = { siBuffer, NULL, 0 };
6916 PRBool isHelloRetry;
6917 SSL3AlertDescription desc = illegal_parameter;
6918 const PRUint8 *savedMsg = b;
6919 const PRUint32 savedLength = length;
6920
6921 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
6922 SSL_GETPID(), ss->fd));
6923 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
6924 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6925
6926 if (ss->ssl3.hs.ws != wait_server_hello) {
6927 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
6928 desc = unexpected_message;
6929 goto alert_loser;
6930 }
6931
6932 /* clean up anything left from previous handshake. */
6933 if (ss->ssl3.clientCertChain != NULL) {
6934 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
6935 ss->ssl3.clientCertChain = NULL;
6936 }
6937 if (ss->ssl3.clientCertificate != NULL) {
6938 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6939 ss->ssl3.clientCertificate = NULL;
6940 }
6941 if (ss->ssl3.clientPrivateKey != NULL) {
6942 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6943 ss->ssl3.clientPrivateKey = NULL;
6944 }
6945
6946 /* Note that if the server selects TLS 1.3, this will set the version to TLS
6947 * 1.2. We will amend that once all other fields have been read. */
6948 rv = ssl_ClientReadVersion(ss, &b, &length, &ss->version);
6949 if (rv != SECSuccess) {
6950 goto loser; /* alert has been sent */
6951 }
6952
6953 rv = ssl3_ConsumeHandshake(
6954 ss, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
6955 if (rv != SECSuccess) {
6956 goto loser; /* alert has been sent */
6957 }
6958 isHelloRetry = !PORT_Memcmp(ss->ssl3.hs.server_random,
6959 ssl_hello_retry_random, SSL3_RANDOM_LENGTH);
6960
6961 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
6962 if (rv != SECSuccess) {
6963 goto loser; /* alert has been sent */
6964 }
6965 if (sidBytes.len > SSL3_SESSIONID_BYTES) {
6966 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_0)
6967 desc = decode_error;
6968 goto alert_loser; /* malformed. */
6969 }
6970
6971 /* Read the cipher suite. */
6972 rv = ssl3_ConsumeHandshakeNumber(ss, &cipher, 2, &b, &length);
6973 if (rv != SECSuccess) {
6974 goto loser; /* alert has been sent */
6975 }
6976
6977 /* Compression method. */
6978 rv = ssl3_ConsumeHandshakeNumber(ss, &compression, 1, &b, &length);
6979 if (rv != SECSuccess) {
6980 goto loser; /* alert has been sent */
6981 }
6982 if (compression != ssl_compression_null) {
6983 desc = illegal_parameter;
6984 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6985 goto alert_loser;
6986 }
6987
6988 /* Parse extensions. */
6989 if (length != 0) {
6990 PRUint32 extensionLength;
6991 rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
6992 if (rv != SECSuccess) {
6993 goto loser; /* alert already sent */
6994 }
6995 if (extensionLength != length) {
6996 desc = decode_error;
6997 goto alert_loser;
6998 }
6999 rv = ssl3_ParseExtensions(ss, &b, &length);
7000 if (rv != SECSuccess) {
7001 goto alert_loser; /* malformed */
7002 }
7003 }
7004
7005 /* Read supported_versions if present. */
7006 rv = tls13_ClientReadSupportedVersion(ss);
7007 if (rv != SECSuccess) {
7008 goto loser;
7009 }
7010
7011 PORT_Assert(!SSL_ALL_VERSIONS_DISABLED(&ss->vrange));
7012 /* Check that the version is within the configured range. */
7013 if (ss->vrange.min > ss->version || ss->vrange.max < ss->version) {
7014 desc = (ss->version > SSL_LIBRARY_VERSION_3_0)
7015 ? protocol_version
7016 : handshake_failure;
7017 errCode = SSL_ERROR_UNSUPPORTED_VERSION;
7018 goto alert_loser;
7019 }
7020
7021 if (isHelloRetry && ss->ssl3.hs.helloRetry) {
7022 SSL_TRC(3, ("%d: SSL3[%d]: received a second hello_retry_request",
7023 SSL_GETPID(), ss->fd));
7024 desc = unexpected_message;
7025 errCode = SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST;
7026 goto alert_loser;
7027 }
7028
7029 /* There are three situations in which the server must pick
7030 * TLS 1.3.
7031 *
7032 * 1. We received HRR
7033 * 2. We sent early app data
7034 * 3. ECH was accepted (checked in MaybeHandleEchSignal)
7035 *
7036 * If we offered ECH and the server negotiated a lower version,
7037 * authenticate to the public name for secure disablement.
7038 *
7039 */
7040 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
7041 if (isHelloRetry || ss->ssl3.hs.helloRetry) {
7042 /* SSL3_SendAlert() will uncache the SID. */
7043 desc = illegal_parameter;
7044 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7045 goto alert_loser;
7046 }
7047 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
7048 /* SSL3_SendAlert() will uncache the SID. */
7049 desc = illegal_parameter;
7050 errCode = SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA;
7051 goto alert_loser;
7052 }
7053 }
7054
7055 /* Check that the server negotiated the same version as it did
7056 * in the first handshake. This isn't really the best place for
7057 * us to be getting this version number, but it's what we have.
7058 * (1294697). */
7059 if (ss->firstHsDone && (ss->version != ss->ssl3.crSpec->version)) {
7060 desc = protocol_version;
7061 errCode = SSL_ERROR_UNSUPPORTED_VERSION;
7062 goto alert_loser;
7063 }
7064
7065 if (ss->opt.enableHelloDowngradeCheck
7066 #ifdef DTLS_1_3_DRAFT_VERSION
7067 /* Disable this check while we are on draft DTLS 1.3 versions. */
7068 && !IS_DTLS(ss)
7069 #endif
7070 ) {
7071 rv = ssl_CheckServerRandom(ss);
7072 if (rv != SECSuccess) {
7073 desc = illegal_parameter;
7074 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7075 goto alert_loser;
7076 }
7077 }
7078
7079 /* Finally, now all the version-related checks have passed. */
7080 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
7081 /* Update the write cipher spec to match the version. But not after
7082 * HelloRetryRequest, because cwSpec might be a 0-RTT cipher spec,
7083 * in which case this is a no-op. */
7084 if (!ss->firstHsDone && !isHelloRetry) {
7085 ssl_GetSpecWriteLock(ss);
7086 ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
7087 ssl_ReleaseSpecWriteLock(ss);
7088 }
7089
7090 /* Check that the session ID is as expected. */
7091 if (!ssl_CheckServerSessionIdCorrectness(ss, &sidBytes)) {
7092 desc = illegal_parameter;
7093 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7094 goto alert_loser;
7095 }
7096
7097 /* Only initialize hashes if this isn't a Hello Retry. */
7098 rv = ssl_ClientSetCipherSuite(ss, ss->version, cipher,
7099 !isHelloRetry);
7100 if (rv != SECSuccess) {
7101 desc = illegal_parameter;
7102 errCode = PORT_GetError();
7103 goto alert_loser;
7104 }
7105
7106 dtls_ReceivedFirstMessageInFlight(ss);
7107
7108 if (isHelloRetry) {
7109 rv = tls13_HandleHelloRetryRequest(ss, savedMsg, savedLength);
7110 if (rv != SECSuccess) {
7111 goto loser;
7112 }
7113 return SECSuccess;
7114 }
7115
7116 rv = ssl3_HandleParsedExtensions(ss, ssl_hs_server_hello);
7117 ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
7118 if (rv != SECSuccess) {
7119 goto alert_loser;
7120 }
7121
7122 rv = ssl_HashHandshakeMessage(ss, ssl_hs_server_hello,
7123 savedMsg, savedLength);
7124 if (rv != SECSuccess) {
7125 goto loser;
7126 }
7127
7128 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
7129 rv = tls13_HandleServerHelloPart2(ss, savedMsg, savedLength);
7130 if (rv != SECSuccess) {
7131 errCode = PORT_GetError();
7132 goto loser;
7133 }
7134 } else {
7135 rv = ssl3_HandleServerHelloPart2(ss, &sidBytes, &errCode);
7136 if (rv != SECSuccess)
7137 goto loser;
7138 }
7139
7140 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
7141 return SECSuccess;
7142
7143 alert_loser:
7144 (void)SSL3_SendAlert(ss, alert_fatal, desc);
7145
7146 loser:
7147 /* Clean up the temporary pointer to the handshake buffer. */
7148 ss->xtnData.signedCertTimestamps.len = 0;
7149 ssl_MapLowLevelError(errCode);
7150 return SECFailure;
7151 }
7152
7153 static SECStatus
ssl3_UnwrapMasterSecretClient(sslSocket * ss,sslSessionID * sid,PK11SymKey ** ms)7154 ssl3_UnwrapMasterSecretClient(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
7155 {
7156 PK11SlotInfo *slot;
7157 PK11SymKey *wrapKey;
7158 CK_FLAGS keyFlags = 0;
7159 SECItem wrappedMS = {
7160 siBuffer,
7161 sid->u.ssl3.keys.wrapped_master_secret,
7162 sid->u.ssl3.keys.wrapped_master_secret_len
7163 };
7164
7165 /* unwrap master secret */
7166 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
7167 sid->u.ssl3.masterSlotID);
7168 if (slot == NULL) {
7169 return SECFailure;
7170 }
7171 if (!PK11_IsPresent(slot)) {
7172 PK11_FreeSlot(slot);
7173 return SECFailure;
7174 }
7175 wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
7176 sid->u.ssl3.masterWrapMech,
7177 sid->u.ssl3.masterWrapSeries,
7178 ss->pkcs11PinArg);
7179 PK11_FreeSlot(slot);
7180 if (wrapKey == NULL) {
7181 return SECFailure;
7182 }
7183
7184 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
7185 keyFlags = CKF_SIGN | CKF_VERIFY;
7186 }
7187
7188 *ms = PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
7189 NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
7190 CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH, keyFlags);
7191 PK11_FreeSymKey(wrapKey);
7192 if (!*ms) {
7193 return SECFailure;
7194 }
7195 return SECSuccess;
7196 }
7197
7198 static SECStatus
ssl3_HandleServerHelloPart2(sslSocket * ss,const SECItem * sidBytes,int * retErrCode)7199 ssl3_HandleServerHelloPart2(sslSocket *ss, const SECItem *sidBytes,
7200 int *retErrCode)
7201 {
7202 SSL3AlertDescription desc = handshake_failure;
7203 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7204 SECStatus rv;
7205 PRBool sid_match;
7206 sslSessionID *sid = ss->sec.ci.sid;
7207
7208 if ((ss->opt.requireSafeNegotiation ||
7209 (ss->firstHsDone && (ss->peerRequestedProtection ||
7210 ss->opt.enableRenegotiation ==
7211 SSL_RENEGOTIATE_REQUIRES_XTN))) &&
7212 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7213 desc = handshake_failure;
7214 errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
7215 : SSL_ERROR_UNSAFE_NEGOTIATION;
7216 goto alert_loser;
7217 }
7218
7219 /* Any errors after this point are not "malformed" errors. */
7220 desc = handshake_failure;
7221
7222 /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
7223 * key exchange algorithm. */
7224 rv = ssl3_SetupBothPendingCipherSpecs(ss);
7225 if (rv != SECSuccess) {
7226 goto alert_loser; /* error code is set. */
7227 }
7228
7229 /* We may or may not have sent a session id, we may get one back or
7230 * not and if so it may match the one we sent.
7231 * Attempt to restore the master secret to see if this is so...
7232 * Don't consider failure to find a matching SID an error.
7233 */
7234 sid_match = (PRBool)(sidBytes->len > 0 &&
7235 sidBytes->len ==
7236 sid->u.ssl3.sessionIDLength &&
7237 !PORT_Memcmp(sid->u.ssl3.sessionID,
7238 sidBytes->data, sidBytes->len));
7239
7240 if (sid_match) {
7241 if (sid->version != ss->version ||
7242 sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
7243 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7244 goto alert_loser;
7245 }
7246 do {
7247 PK11SymKey *masterSecret;
7248
7249 /* [draft-ietf-tls-session-hash-06; Section 5.3]
7250 *
7251 * o If the original session did not use the "extended_master_secret"
7252 * extension but the new ServerHello contains the extension, the
7253 * client MUST abort the handshake.
7254 */
7255 if (!sid->u.ssl3.keys.extendedMasterSecretUsed &&
7256 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
7257 errCode = SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET;
7258 goto alert_loser;
7259 }
7260
7261 /*
7262 * o If the original session used an extended master secret but the new
7263 * ServerHello does not contain the "extended_master_secret"
7264 * extension, the client SHOULD abort the handshake.
7265 *
7266 * TODO(ekr@rtfm.com): Add option to refuse to resume when EMS is not
7267 * used at all (bug 1176526).
7268 */
7269 if (sid->u.ssl3.keys.extendedMasterSecretUsed &&
7270 !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
7271 errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
7272 goto alert_loser;
7273 }
7274
7275 ss->sec.authType = sid->authType;
7276 ss->sec.authKeyBits = sid->authKeyBits;
7277 ss->sec.keaType = sid->keaType;
7278 ss->sec.keaKeyBits = sid->keaKeyBits;
7279 ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
7280 ss->sec.signatureScheme = sid->sigScheme;
7281
7282 rv = ssl3_UnwrapMasterSecretClient(ss, sid, &masterSecret);
7283 if (rv != SECSuccess) {
7284 break; /* not considered an error */
7285 }
7286
7287 /* Got a Match */
7288 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_hits);
7289
7290 /* If we sent a session ticket, then this is a stateless resume. */
7291 if (ss->xtnData.sentSessionTicketInClientHello)
7292 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_stateless_resumes);
7293
7294 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
7295 ss->ssl3.hs.ws = wait_new_session_ticket;
7296 else
7297 ss->ssl3.hs.ws = wait_change_cipher;
7298
7299 ss->ssl3.hs.isResuming = PR_TRUE;
7300
7301 /* copy the peer cert from the SID */
7302 if (sid->peerCert != NULL) {
7303 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
7304 }
7305
7306 /* We are re-using the old MS, so no need to derive again. */
7307 rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE);
7308 if (rv != SECSuccess) {
7309 goto alert_loser; /* err code was set */
7310 }
7311 return SECSuccess;
7312 } while (0);
7313 }
7314
7315 if (sid_match)
7316 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_not_ok);
7317 else
7318 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_misses);
7319
7320 /* We tried to resume a 1.3 session but the server negotiated 1.2. */
7321 if (ss->statelessResume) {
7322 PORT_Assert(sid->version == SSL_LIBRARY_VERSION_TLS_1_3);
7323 PORT_Assert(ss->ssl3.hs.currentSecret);
7324
7325 /* Reset resumption state, only used by 1.3 code. */
7326 ss->statelessResume = PR_FALSE;
7327
7328 /* Clear TLS 1.3 early data traffic key. */
7329 PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
7330 ss->ssl3.hs.currentSecret = NULL;
7331 }
7332
7333 /* throw the old one away */
7334 sid->u.ssl3.keys.resumable = PR_FALSE;
7335 ssl_UncacheSessionID(ss);
7336 ssl_FreeSID(sid);
7337
7338 /* get a new sid */
7339 ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
7340 if (sid == NULL) {
7341 goto alert_loser; /* memory error is set. */
7342 }
7343
7344 sid->version = ss->version;
7345 sid->u.ssl3.sessionIDLength = sidBytes->len;
7346 if (sidBytes->len > 0) {
7347 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len);
7348 }
7349
7350 sid->u.ssl3.keys.extendedMasterSecretUsed =
7351 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
7352
7353 /* Copy Signed Certificate Timestamps, if any. */
7354 if (ss->xtnData.signedCertTimestamps.len) {
7355 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps,
7356 &ss->xtnData.signedCertTimestamps);
7357 ss->xtnData.signedCertTimestamps.len = 0;
7358 if (rv != SECSuccess)
7359 goto loser;
7360 }
7361
7362 ss->ssl3.hs.isResuming = PR_FALSE;
7363 if (ss->ssl3.hs.kea_def->authKeyType != ssl_auth_null) {
7364 /* All current cipher suites other than those with ssl_auth_null (i.e.,
7365 * (EC)DH_anon_* suites) require a certificate, so use that signal. */
7366 ss->ssl3.hs.ws = wait_server_cert;
7367 } else {
7368 /* All the remaining cipher suites must be (EC)DH_anon_* and so
7369 * must be ephemeral. Note, if we ever add PSK this might
7370 * change. */
7371 PORT_Assert(ss->ssl3.hs.kea_def->ephemeral);
7372 ss->ssl3.hs.ws = wait_server_key;
7373 }
7374 return SECSuccess;
7375
7376 alert_loser:
7377 (void)SSL3_SendAlert(ss, alert_fatal, desc);
7378
7379 loser:
7380 *retErrCode = errCode;
7381 return SECFailure;
7382 }
7383
7384 static SECStatus
ssl_HandleDHServerKeyExchange(sslSocket * ss,PRUint8 * b,PRUint32 length)7385 ssl_HandleDHServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
7386 {
7387 SECStatus rv;
7388 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
7389 SSL3AlertDescription desc = illegal_parameter;
7390 SSLHashType hashAlg;
7391 PRBool isTLS = ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0;
7392 SSLSignatureScheme sigScheme;
7393
7394 SECItem dh_p = { siBuffer, NULL, 0 };
7395 SECItem dh_g = { siBuffer, NULL, 0 };
7396 SECItem dh_Ys = { siBuffer, NULL, 0 };
7397 unsigned dh_p_bits;
7398 unsigned dh_g_bits;
7399 PRInt32 minDH;
7400
7401 SSL3Hashes hashes;
7402 SECItem signature = { siBuffer, NULL, 0 };
7403 PLArenaPool *arena = NULL;
7404 SECKEYPublicKey *peerKey = NULL;
7405
7406 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
7407 if (rv != SECSuccess) {
7408 goto loser; /* malformed. */
7409 }
7410
7411 rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH);
7412 if (rv != SECSuccess || minDH <= 0) {
7413 minDH = SSL_DH_MIN_P_BITS;
7414 }
7415 dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p);
7416 if (dh_p_bits < (unsigned)minDH) {
7417 errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
7418 goto alert_loser;
7419 }
7420 if (dh_p_bits > SSL_MAX_DH_KEY_BITS) {
7421 errCode = SSL_ERROR_DH_KEY_TOO_LONG;
7422 goto alert_loser;
7423 }
7424 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
7425 if (rv != SECSuccess) {
7426 goto loser; /* malformed. */
7427 }
7428 /* Abort if dh_g is 0, 1, or obviously too big. */
7429 dh_g_bits = SECKEY_BigIntegerBitLength(&dh_g);
7430 if (dh_g_bits > dh_p_bits || dh_g_bits <= 1) {
7431 goto alert_loser;
7432 }
7433 if (ss->opt.requireDHENamedGroups) {
7434 /* If we're doing named groups, make sure it's good. */
7435 rv = ssl_ValidateDHENamedGroup(ss, &dh_p, &dh_g, NULL, NULL);
7436 if (rv != SECSuccess) {
7437 errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
7438 goto alert_loser;
7439 }
7440 }
7441
7442 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
7443 if (rv != SECSuccess) {
7444 goto loser; /* malformed. */
7445 }
7446 if (!ssl_IsValidDHEShare(&dh_p, &dh_Ys)) {
7447 errCode = SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE;
7448 goto alert_loser;
7449 }
7450
7451 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
7452 rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
7453 if (rv != SECSuccess) {
7454 goto loser; /* alert already sent */
7455 }
7456 rv = ssl_CheckSignatureSchemeConsistency(
7457 ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo);
7458 if (rv != SECSuccess) {
7459 goto alert_loser;
7460 }
7461 hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
7462 } else {
7463 /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
7464 hashAlg = ssl_hash_none;
7465 sigScheme = ssl_sig_none;
7466 }
7467 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
7468 if (rv != SECSuccess) {
7469 goto loser; /* malformed. */
7470 }
7471 if (length != 0) {
7472 if (isTLS) {
7473 desc = decode_error;
7474 }
7475 goto alert_loser; /* malformed. */
7476 }
7477
7478 PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
7479 PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
7480 PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
7481
7482 /* failures after this point are not malformed handshakes. */
7483 /* TLS: send decrypt_error if signature failed. */
7484 desc = isTLS ? decrypt_error : handshake_failure;
7485
7486 /*
7487 * Check to make sure the hash is signed by right guy.
7488 */
7489 rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
7490 dh_p, dh_g, dh_Ys, PR_FALSE /* padY */);
7491 if (rv != SECSuccess) {
7492 errCode =
7493 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7494 goto alert_loser;
7495 }
7496 rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signature);
7497 if (rv != SECSuccess) {
7498 errCode =
7499 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7500 goto alert_loser;
7501 }
7502
7503 /*
7504 * we really need to build a new key here because we can no longer
7505 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
7506 * pkcs11 slots and ID's.
7507 */
7508 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7509 if (arena == NULL) {
7510 errCode = SEC_ERROR_NO_MEMORY;
7511 goto loser;
7512 }
7513
7514 peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
7515 if (peerKey == NULL) {
7516 errCode = SEC_ERROR_NO_MEMORY;
7517 goto loser;
7518 }
7519
7520 peerKey->arena = arena;
7521 peerKey->keyType = dhKey;
7522 peerKey->pkcs11Slot = NULL;
7523 peerKey->pkcs11ID = CK_INVALID_HANDLE;
7524
7525 if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) ||
7526 SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) ||
7527 SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) {
7528 errCode = SEC_ERROR_NO_MEMORY;
7529 goto loser;
7530 }
7531 ss->sec.peerKey = peerKey;
7532 return SECSuccess;
7533
7534 alert_loser:
7535 (void)SSL3_SendAlert(ss, alert_fatal, desc);
7536 loser:
7537 if (arena) {
7538 PORT_FreeArena(arena, PR_FALSE);
7539 }
7540 PORT_SetError(ssl_MapLowLevelError(errCode));
7541 return SECFailure;
7542 }
7543
7544 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
7545 * complete ssl3 ServerKeyExchange message.
7546 * Caller must hold Handshake and RecvBuf locks.
7547 */
7548 static SECStatus
ssl3_HandleServerKeyExchange(sslSocket * ss,PRUint8 * b,PRUint32 length)7549 ssl3_HandleServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
7550 {
7551 SECStatus rv;
7552
7553 SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
7554 SSL_GETPID(), ss->fd));
7555 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7556 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7557
7558 if (ss->ssl3.hs.ws != wait_server_key) {
7559 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
7560 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
7561 return SECFailure;
7562 }
7563
7564 switch (ss->ssl3.hs.kea_def->exchKeyType) {
7565 case ssl_kea_dh:
7566 rv = ssl_HandleDHServerKeyExchange(ss, b, length);
7567 break;
7568
7569 case ssl_kea_ecdh:
7570 rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
7571 break;
7572
7573 default:
7574 SSL3_SendAlert(ss, alert_fatal, handshake_failure);
7575 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
7576 rv = SECFailure;
7577 break;
7578 }
7579
7580 if (rv == SECSuccess) {
7581 ss->ssl3.hs.ws = wait_cert_request;
7582 }
7583 /* All Handle*ServerKeyExchange functions set the error code. */
7584 return rv;
7585 }
7586
7587 typedef struct dnameNode {
7588 struct dnameNode *next;
7589 SECItem name;
7590 } dnameNode;
7591
7592 /*
7593 * Parse the ca_list structure in a CertificateRequest.
7594 *
7595 * Called from:
7596 * ssl3_HandleCertificateRequest
7597 * tls13_HandleCertificateRequest
7598 */
7599 SECStatus
ssl3_ParseCertificateRequestCAs(sslSocket * ss,PRUint8 ** b,PRUint32 * length,CERTDistNames * ca_list)7600 ssl3_ParseCertificateRequestCAs(sslSocket *ss, PRUint8 **b, PRUint32 *length,
7601 CERTDistNames *ca_list)
7602 {
7603 PRUint32 remaining;
7604 int nnames = 0;
7605 dnameNode *node;
7606 SECStatus rv;
7607 int i;
7608
7609 rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 2, b, length);
7610 if (rv != SECSuccess)
7611 return SECFailure; /* malformed, alert has been sent */
7612
7613 if (remaining > *length)
7614 goto alert_loser;
7615
7616 ca_list->head = node = PORT_ArenaZNew(ca_list->arena, dnameNode);
7617 if (node == NULL)
7618 goto no_mem;
7619
7620 while (remaining > 0) {
7621 PRUint32 len;
7622
7623 if (remaining < 2)
7624 goto alert_loser; /* malformed */
7625
7626 rv = ssl3_ConsumeHandshakeNumber(ss, &len, 2, b, length);
7627 if (rv != SECSuccess)
7628 return SECFailure; /* malformed, alert has been sent */
7629 if (len == 0 || remaining < len + 2)
7630 goto alert_loser; /* malformed */
7631
7632 remaining -= 2;
7633 if (SECITEM_MakeItem(ca_list->arena, &node->name, *b, len) != SECSuccess) {
7634 goto no_mem;
7635 }
7636 node->name.len = len;
7637 *b += len;
7638 *length -= len;
7639 remaining -= len;
7640 nnames++;
7641 if (remaining <= 0)
7642 break; /* success */
7643
7644 node->next = PORT_ArenaZNew(ca_list->arena, dnameNode);
7645 node = node->next;
7646 if (node == NULL)
7647 goto no_mem;
7648 }
7649
7650 ca_list->nnames = nnames;
7651 ca_list->names = PORT_ArenaNewArray(ca_list->arena, SECItem, nnames);
7652 if (nnames > 0 && ca_list->names == NULL)
7653 goto no_mem;
7654
7655 for (i = 0, node = (dnameNode *)ca_list->head;
7656 i < nnames;
7657 i++, node = node->next) {
7658 ca_list->names[i] = node->name;
7659 }
7660
7661 return SECSuccess;
7662
7663 no_mem:
7664 return SECFailure;
7665
7666 alert_loser:
7667 (void)SSL3_SendAlert(ss, alert_fatal,
7668 ss->version < SSL_LIBRARY_VERSION_TLS_1_0 ? illegal_parameter
7669 : decode_error);
7670 PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
7671 return SECFailure;
7672 }
7673
7674 SECStatus
ssl_ParseSignatureSchemes(const sslSocket * ss,PLArenaPool * arena,SSLSignatureScheme ** schemesOut,unsigned int * numSchemesOut,unsigned char ** b,unsigned int * len)7675 ssl_ParseSignatureSchemes(const sslSocket *ss, PLArenaPool *arena,
7676 SSLSignatureScheme **schemesOut,
7677 unsigned int *numSchemesOut,
7678 unsigned char **b, unsigned int *len)
7679 {
7680 SECStatus rv;
7681 SECItem buf;
7682 SSLSignatureScheme *schemes = NULL;
7683 unsigned int numSupported = 0;
7684 unsigned int numRemaining = 0;
7685 unsigned int max;
7686
7687 rv = ssl3_ExtConsumeHandshakeVariable(ss, &buf, 2, b, len);
7688 if (rv != SECSuccess) {
7689 return SECFailure;
7690 }
7691 /* An odd-length value is invalid. */
7692 if ((buf.len & 1) != 0) {
7693 ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
7694 return SECFailure;
7695 }
7696
7697 /* Let the caller decide whether to alert here. */
7698 if (buf.len == 0) {
7699 goto done;
7700 }
7701
7702 /* Limit the number of schemes we read. */
7703 numRemaining = buf.len / 2;
7704 max = PR_MIN(numRemaining, MAX_SIGNATURE_SCHEMES);
7705
7706 if (arena) {
7707 schemes = PORT_ArenaZNewArray(arena, SSLSignatureScheme, max);
7708 } else {
7709 schemes = PORT_ZNewArray(SSLSignatureScheme, max);
7710 }
7711 if (!schemes) {
7712 ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
7713 return SECFailure;
7714 }
7715
7716 for (; numRemaining && numSupported < MAX_SIGNATURE_SCHEMES; --numRemaining) {
7717 PRUint32 tmp;
7718 rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2, &buf.data, &buf.len);
7719 if (rv != SECSuccess) {
7720 PORT_Assert(0);
7721 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
7722 return SECFailure;
7723 }
7724 if (ssl_SignatureSchemeValid((SSLSignatureScheme)tmp, SEC_OID_UNKNOWN,
7725 (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)) {
7726 ;
7727 schemes[numSupported++] = (SSLSignatureScheme)tmp;
7728 }
7729 }
7730
7731 if (!numSupported) {
7732 if (!arena) {
7733 PORT_Free(schemes);
7734 }
7735 schemes = NULL;
7736 }
7737
7738 done:
7739 *schemesOut = schemes;
7740 *numSchemesOut = numSupported;
7741 return SECSuccess;
7742 }
7743
7744 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
7745 * a complete ssl3 Certificate Request message.
7746 * Caller must hold Handshake and RecvBuf locks.
7747 */
7748 static SECStatus
ssl3_HandleCertificateRequest(sslSocket * ss,PRUint8 * b,PRUint32 length)7749 ssl3_HandleCertificateRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
7750 {
7751 PLArenaPool *arena = NULL;
7752 PRBool isTLS = PR_FALSE;
7753 PRBool isTLS12 = PR_FALSE;
7754 int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
7755 SECStatus rv;
7756 SSL3AlertDescription desc = illegal_parameter;
7757 SECItem cert_types = { siBuffer, NULL, 0 };
7758 SSLSignatureScheme *signatureSchemes = NULL;
7759 unsigned int signatureSchemeCount = 0;
7760 CERTDistNames ca_list;
7761
7762 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
7763 SSL_GETPID(), ss->fd));
7764 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7765 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7766
7767 if (ss->ssl3.hs.ws != wait_cert_request) {
7768 desc = unexpected_message;
7769 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
7770 goto alert_loser;
7771 }
7772
7773 PORT_Assert(ss->ssl3.clientCertChain == NULL);
7774 PORT_Assert(ss->ssl3.clientCertificate == NULL);
7775 PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
7776
7777 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
7778 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
7779 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
7780 if (rv != SECSuccess)
7781 goto loser; /* malformed, alert has been sent */
7782
7783 arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7784 if (arena == NULL)
7785 goto no_mem;
7786
7787 if (isTLS12) {
7788 rv = ssl_ParseSignatureSchemes(ss, arena,
7789 &signatureSchemes,
7790 &signatureSchemeCount,
7791 &b, &length);
7792 if (rv != SECSuccess) {
7793 PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
7794 goto loser; /* malformed, alert has been sent */
7795 }
7796 if (signatureSchemeCount == 0) {
7797 errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
7798 desc = handshake_failure;
7799 goto alert_loser;
7800 }
7801 }
7802
7803 rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, &ca_list);
7804 if (rv != SECSuccess)
7805 goto done; /* alert sent in ssl3_ParseCertificateRequestCAs */
7806
7807 if (length != 0)
7808 goto alert_loser; /* malformed */
7809
7810 ss->ssl3.hs.ws = wait_hello_done;
7811
7812 rv = ssl3_CompleteHandleCertificateRequest(ss, signatureSchemes,
7813 signatureSchemeCount, &ca_list);
7814 if (rv == SECFailure) {
7815 PORT_Assert(0);
7816 errCode = SEC_ERROR_LIBRARY_FAILURE;
7817 desc = internal_error;
7818 goto alert_loser;
7819 }
7820 goto done;
7821
7822 no_mem:
7823 rv = SECFailure;
7824 PORT_SetError(SEC_ERROR_NO_MEMORY);
7825 goto done;
7826
7827 alert_loser:
7828 if (isTLS && desc == illegal_parameter)
7829 desc = decode_error;
7830 (void)SSL3_SendAlert(ss, alert_fatal, desc);
7831 loser:
7832 PORT_SetError(errCode);
7833 rv = SECFailure;
7834 done:
7835 if (arena != NULL)
7836 PORT_FreeArena(arena, PR_FALSE);
7837 return rv;
7838 }
7839
7840 SECStatus
ssl3_CompleteHandleCertificateRequest(sslSocket * ss,const SSLSignatureScheme * signatureSchemes,unsigned int signatureSchemeCount,CERTDistNames * ca_list)7841 ssl3_CompleteHandleCertificateRequest(sslSocket *ss,
7842 const SSLSignatureScheme *signatureSchemes,
7843 unsigned int signatureSchemeCount,
7844 CERTDistNames *ca_list)
7845 {
7846 SECStatus rv;
7847
7848 /* Should not send a client cert when (non-GREASE) ECH is rejected. */
7849 if (ss->ssl3.hs.echHpkeCtx && !ss->ssl3.hs.echAccepted) {
7850 PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn));
7851 goto send_no_certificate;
7852 }
7853
7854 if (ss->getClientAuthData != NULL) {
7855 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
7856 ssl_preinfo_all);
7857 PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
7858 PORT_Assert(ss->ssl3.clientCertificate == NULL);
7859 PORT_Assert(ss->ssl3.clientCertChain == NULL);
7860 /* XXX Should pass cert_types and algorithms in this call!! */
7861 rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
7862 ss->fd, ca_list,
7863 &ss->ssl3.clientCertificate,
7864 &ss->ssl3.clientPrivateKey);
7865 } else {
7866 rv = SECFailure; /* force it to send a no_certificate alert */
7867 }
7868 switch (rv) {
7869 case SECWouldBlock: /* getClientAuthData has put up a dialog box. */
7870 ssl3_SetAlwaysBlock(ss);
7871 break; /* not an error */
7872
7873 case SECSuccess:
7874 /* check what the callback function returned */
7875 if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
7876 /* we are missing either the key or cert */
7877 goto send_no_certificate;
7878 }
7879 /* Setting ssl3.clientCertChain non-NULL will cause
7880 * ssl3_HandleServerHelloDone to call SendCertificate.
7881 */
7882 ss->ssl3.clientCertChain = CERT_CertChainFromCert(
7883 ss->ssl3.clientCertificate,
7884 certUsageSSLClient, PR_FALSE);
7885 if (ss->ssl3.clientCertChain == NULL) {
7886 goto send_no_certificate;
7887 }
7888 if (ss->ssl3.hs.hashType == handshake_hash_record ||
7889 ss->ssl3.hs.hashType == handshake_hash_single) {
7890 rv = ssl_PickClientSignatureScheme(ss, signatureSchemes,
7891 signatureSchemeCount);
7892 if (rv != SECSuccess) {
7893 /* This should only happen if our schemes changed or
7894 * if an RSA-PSS cert was selected, but the token
7895 * does not support PSS schemes. */
7896 goto send_no_certificate;
7897 }
7898 }
7899 break; /* not an error */
7900
7901 case SECFailure:
7902 default:
7903 send_no_certificate:
7904 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7905 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7906 ss->ssl3.clientCertificate = NULL;
7907 ss->ssl3.clientPrivateKey = NULL;
7908 if (ss->ssl3.clientCertChain) {
7909 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
7910 ss->ssl3.clientCertChain = NULL;
7911 }
7912
7913 if (ss->version > SSL_LIBRARY_VERSION_3_0) {
7914 ss->ssl3.sendEmptyCert = PR_TRUE;
7915 } else {
7916 (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
7917 }
7918 rv = SECSuccess;
7919 break;
7920 }
7921
7922 return rv;
7923 }
7924
7925 static SECStatus
ssl3_CheckFalseStart(sslSocket * ss)7926 ssl3_CheckFalseStart(sslSocket *ss)
7927 {
7928 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7929 PORT_Assert(!ss->ssl3.hs.authCertificatePending);
7930 PORT_Assert(!ss->ssl3.hs.canFalseStart);
7931
7932 if (!ss->canFalseStartCallback) {
7933 SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start",
7934 SSL_GETPID(), ss->fd));
7935 } else {
7936 SECStatus rv;
7937
7938 rv = ssl_CheckServerRandom(ss);
7939 if (rv != SECSuccess) {
7940 SSL_TRC(3, ("%d: SSL[%d]: no false start due to possible downgrade",
7941 SSL_GETPID(), ss->fd));
7942 goto no_false_start;
7943 }
7944
7945 /* An attacker can control the selected ciphersuite so we only wish to
7946 * do False Start in the case that the selected ciphersuite is
7947 * sufficiently strong that the attack can gain no advantage.
7948 * Therefore we always require an 80-bit cipher. */
7949 ssl_GetSpecReadLock(ss);
7950 PRBool weakCipher = ss->ssl3.cwSpec->cipherDef->secret_key_size < 10;
7951 ssl_ReleaseSpecReadLock(ss);
7952 if (weakCipher) {
7953 SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher",
7954 SSL_GETPID(), ss->fd));
7955 goto no_false_start;
7956 }
7957
7958 if (ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn)) {
7959 SSL_TRC(3, ("%d: SSL[%d]: no false start due to lower version after ECH",
7960 SSL_GETPID(), ss->fd));
7961 goto no_false_start;
7962 }
7963
7964 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
7965 ssl_preinfo_all);
7966 rv = (ss->canFalseStartCallback)(ss->fd,
7967 ss->canFalseStartCallbackData,
7968 &ss->ssl3.hs.canFalseStart);
7969 if (rv == SECSuccess) {
7970 SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s",
7971 SSL_GETPID(), ss->fd,
7972 ss->ssl3.hs.canFalseStart ? "TRUE"
7973 : "FALSE"));
7974 } else {
7975 SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)",
7976 SSL_GETPID(), ss->fd,
7977 PR_ErrorToName(PR_GetError())));
7978 }
7979 return rv;
7980 }
7981
7982 no_false_start:
7983 ss->ssl3.hs.canFalseStart = PR_FALSE;
7984 return SECSuccess;
7985 }
7986
7987 PRBool
ssl3_WaitingForServerSecondRound(sslSocket * ss)7988 ssl3_WaitingForServerSecondRound(sslSocket *ss)
7989 {
7990 PRBool result;
7991
7992 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7993
7994 switch (ss->ssl3.hs.ws) {
7995 case wait_new_session_ticket:
7996 case wait_change_cipher:
7997 case wait_finished:
7998 result = PR_TRUE;
7999 break;
8000 default:
8001 result = PR_FALSE;
8002 break;
8003 }
8004
8005 return result;
8006 }
8007
8008 static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
8009
8010 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
8011 * a complete ssl3 Server Hello Done message.
8012 * Caller must hold Handshake and RecvBuf locks.
8013 */
8014 static SECStatus
ssl3_HandleServerHelloDone(sslSocket * ss)8015 ssl3_HandleServerHelloDone(sslSocket *ss)
8016 {
8017 SECStatus rv;
8018 SSL3WaitState ws = ss->ssl3.hs.ws;
8019
8020 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
8021 SSL_GETPID(), ss->fd));
8022 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
8023 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8024
8025 /* Skipping CertificateRequest is always permitted. */
8026 if (ws != wait_hello_done &&
8027 ws != wait_cert_request) {
8028 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8029 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
8030 return SECFailure;
8031 }
8032
8033 rv = ssl3_SendClientSecondRound(ss);
8034
8035 return rv;
8036 }
8037
8038 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
8039 *
8040 * Caller must hold Handshake and RecvBuf locks.
8041 */
8042 static SECStatus
ssl3_SendClientSecondRound(sslSocket * ss)8043 ssl3_SendClientSecondRound(sslSocket *ss)
8044 {
8045 SECStatus rv;
8046 PRBool sendClientCert;
8047
8048 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
8049 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8050
8051 sendClientCert = !ss->ssl3.sendEmptyCert &&
8052 ss->ssl3.clientCertChain != NULL &&
8053 ss->ssl3.clientPrivateKey != NULL;
8054
8055 /* We must wait for the server's certificate to be authenticated before
8056 * sending the client certificate in order to disclosing the client
8057 * certificate to an attacker that does not have a valid cert for the
8058 * domain we are connecting to.
8059 *
8060 * During the initial handshake on a connection, we never send/receive
8061 * application data until we have authenticated the server's certificate;
8062 * i.e. we have fully authenticated the handshake before using the cipher
8063 * specs agreed upon for that handshake. During a renegotiation, we may
8064 * continue sending and receiving application data during the handshake
8065 * interleaved with the handshake records. If we were to send the client's
8066 * second round for a renegotiation before the server's certificate was
8067 * authenticated, then the application data sent/received after this point
8068 * would be using cipher spec that hadn't been authenticated. By waiting
8069 * until the server's certificate has been authenticated during
8070 * renegotiations, we ensure that renegotiations have the same property
8071 * as initial handshakes; i.e. we have fully authenticated the handshake
8072 * before using the cipher specs agreed upon for that handshake for
8073 * application data.
8074 */
8075 if (ss->ssl3.hs.restartTarget) {
8076 PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
8077 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
8078 return SECFailure;
8079 }
8080 if (ss->ssl3.hs.authCertificatePending &&
8081 (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) {
8082 SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"
8083 " certificate authentication is still pending.",
8084 SSL_GETPID(), ss->fd));
8085 ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
8086 PORT_SetError(PR_WOULD_BLOCK_ERROR);
8087 return SECFailure;
8088 }
8089
8090 ssl_GetXmitBufLock(ss); /*******************************/
8091
8092 if (ss->ssl3.sendEmptyCert) {
8093 ss->ssl3.sendEmptyCert = PR_FALSE;
8094 rv = ssl3_SendEmptyCertificate(ss);
8095 /* Don't send verify */
8096 if (rv != SECSuccess) {
8097 goto loser; /* error code is set. */
8098 }
8099 } else if (sendClientCert) {
8100 rv = ssl3_SendCertificate(ss);
8101 if (rv != SECSuccess) {
8102 goto loser; /* error code is set. */
8103 }
8104 }
8105
8106 rv = ssl3_SendClientKeyExchange(ss);
8107 if (rv != SECSuccess) {
8108 goto loser; /* err is set. */
8109 }
8110
8111 if (sendClientCert) {
8112 rv = ssl3_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
8113 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
8114 ss->ssl3.clientPrivateKey = NULL;
8115 if (rv != SECSuccess) {
8116 goto loser; /* err is set. */
8117 }
8118 }
8119
8120 rv = ssl3_SendChangeCipherSpecs(ss);
8121 if (rv != SECSuccess) {
8122 goto loser; /* err code was set. */
8123 }
8124
8125 /* This must be done after we've set ss->ssl3.cwSpec in
8126 * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information
8127 * from cwSpec. This must be done before we call ssl3_CheckFalseStart
8128 * because the false start callback (if any) may need the information from
8129 * the functions that depend on this being set.
8130 */
8131 ss->enoughFirstHsDone = PR_TRUE;
8132
8133 if (!ss->firstHsDone) {
8134 if (ss->opt.enableFalseStart) {
8135 if (!ss->ssl3.hs.authCertificatePending) {
8136 /* When we fix bug 589047, we will need to know whether we are
8137 * false starting before we try to flush the client second
8138 * round to the network. With that in mind, we purposefully
8139 * call ssl3_CheckFalseStart before calling ssl3_SendFinished,
8140 * which includes a call to ssl3_FlushHandshake, so that
8141 * no application develops a reliance on such flushing being
8142 * done before its false start callback is called.
8143 */
8144 ssl_ReleaseXmitBufLock(ss);
8145 rv = ssl3_CheckFalseStart(ss);
8146 ssl_GetXmitBufLock(ss);
8147 if (rv != SECSuccess) {
8148 goto loser;
8149 }
8150 } else {
8151 /* The certificate authentication and the server's Finished
8152 * message are racing each other. If the certificate
8153 * authentication wins, then we will try to false start in
8154 * ssl3_AuthCertificateComplete.
8155 */
8156 SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because"
8157 " certificate authentication is still pending.",
8158 SSL_GETPID(), ss->fd));
8159 }
8160 }
8161 }
8162
8163 rv = ssl3_SendFinished(ss, 0);
8164 if (rv != SECSuccess) {
8165 goto loser; /* err code was set. */
8166 }
8167
8168 ssl_ReleaseXmitBufLock(ss); /*******************************/
8169
8170 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
8171 ss->ssl3.hs.ws = wait_new_session_ticket;
8172 else
8173 ss->ssl3.hs.ws = wait_change_cipher;
8174
8175 PORT_Assert(ssl3_WaitingForServerSecondRound(ss));
8176
8177 return SECSuccess;
8178
8179 loser:
8180 ssl_ReleaseXmitBufLock(ss);
8181 return rv;
8182 }
8183
8184 /*
8185 * Routines used by servers
8186 */
8187 static SECStatus
ssl3_SendHelloRequest(sslSocket * ss)8188 ssl3_SendHelloRequest(sslSocket *ss)
8189 {
8190 SECStatus rv;
8191
8192 SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
8193 ss->fd));
8194
8195 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8196 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8197
8198 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_hello_request, 0);
8199 if (rv != SECSuccess) {
8200 return rv; /* err set by AppendHandshake */
8201 }
8202 rv = ssl3_FlushHandshake(ss, 0);
8203 if (rv != SECSuccess) {
8204 return rv; /* error code set by ssl3_FlushHandshake */
8205 }
8206 ss->ssl3.hs.ws = wait_client_hello;
8207 return SECSuccess;
8208 }
8209
8210 /*
8211 * Called from:
8212 * ssl3_HandleClientHello()
8213 */
8214 static SECComparison
ssl3_ServerNameCompare(const SECItem * name1,const SECItem * name2)8215 ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
8216 {
8217 if (!name1 != !name2) {
8218 return SECLessThan;
8219 }
8220 if (!name1) {
8221 return SECEqual;
8222 }
8223 if (name1->type != name2->type) {
8224 return SECLessThan;
8225 }
8226 return SECITEM_CompareItem(name1, name2);
8227 }
8228
8229 /* Sets memory error when returning NULL.
8230 * Called from:
8231 * ssl3_SendClientHello()
8232 * ssl3_HandleServerHello()
8233 * ssl3_HandleClientHello()
8234 * ssl3_HandleV2ClientHello()
8235 */
8236 sslSessionID *
ssl3_NewSessionID(sslSocket * ss,PRBool is_server)8237 ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
8238 {
8239 sslSessionID *sid;
8240
8241 sid = PORT_ZNew(sslSessionID);
8242 if (sid == NULL)
8243 return sid;
8244
8245 if (is_server) {
8246 const SECItem *srvName;
8247 SECStatus rv = SECSuccess;
8248
8249 ssl_GetSpecReadLock(ss); /********************************/
8250 srvName = &ss->ssl3.hs.srvVirtName;
8251 if (srvName->len && srvName->data) {
8252 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
8253 }
8254 ssl_ReleaseSpecReadLock(ss); /************************************/
8255 if (rv != SECSuccess) {
8256 PORT_Free(sid);
8257 return NULL;
8258 }
8259 }
8260 sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
8261 sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url);
8262 sid->addr = ss->sec.ci.peer;
8263 sid->port = ss->sec.ci.port;
8264 sid->references = 1;
8265 sid->cached = never_cached;
8266 sid->version = ss->version;
8267 sid->sigScheme = ssl_sig_none;
8268
8269 sid->u.ssl3.keys.resumable = PR_TRUE;
8270 sid->u.ssl3.policy = SSL_ALLOWED;
8271 sid->u.ssl3.keys.extendedMasterSecretUsed = PR_FALSE;
8272
8273 if (is_server) {
8274 SECStatus rv;
8275 int pid = SSL_GETPID();
8276
8277 sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
8278 sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff;
8279 sid->u.ssl3.sessionID[1] = pid & 0xff;
8280 rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
8281 SSL3_SESSIONID_BYTES - 2);
8282 if (rv != SECSuccess) {
8283 ssl_FreeSID(sid);
8284 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
8285 return NULL;
8286 }
8287 }
8288 return sid;
8289 }
8290
8291 /* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
8292 static SECStatus
ssl3_SendServerHelloSequence(sslSocket * ss)8293 ssl3_SendServerHelloSequence(sslSocket *ss)
8294 {
8295 const ssl3KEADef *kea_def;
8296 SECStatus rv;
8297
8298 SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
8299 SSL_GETPID(), ss->fd));
8300
8301 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8302 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8303
8304 rv = ssl3_SendServerHello(ss);
8305 if (rv != SECSuccess) {
8306 return rv; /* err code is set. */
8307 }
8308 rv = ssl3_SendCertificate(ss);
8309 if (rv != SECSuccess) {
8310 return rv; /* error code is set. */
8311 }
8312 rv = ssl3_SendCertificateStatus(ss);
8313 if (rv != SECSuccess) {
8314 return rv; /* error code is set. */
8315 }
8316 /* We have to do this after the call to ssl3_SendServerHello,
8317 * because kea_def is set up by ssl3_SendServerHello().
8318 */
8319 kea_def = ss->ssl3.hs.kea_def;
8320
8321 if (kea_def->ephemeral) {
8322 rv = ssl3_SendServerKeyExchange(ss);
8323 if (rv != SECSuccess) {
8324 return rv; /* err code was set. */
8325 }
8326 }
8327
8328 if (ss->opt.requestCertificate) {
8329 rv = ssl3_SendCertificateRequest(ss);
8330 if (rv != SECSuccess) {
8331 return rv; /* err code is set. */
8332 }
8333 }
8334 rv = ssl3_SendServerHelloDone(ss);
8335 if (rv != SECSuccess) {
8336 return rv; /* err code is set. */
8337 }
8338
8339 ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
8340 : wait_client_key;
8341 return SECSuccess;
8342 }
8343
8344 /* An empty TLS Renegotiation Info (RI) extension */
8345 static const PRUint8 emptyRIext[5] = { 0xff, 0x01, 0x00, 0x01, 0x00 };
8346
8347 static PRBool
ssl3_KEASupportsTickets(const ssl3KEADef * kea_def)8348 ssl3_KEASupportsTickets(const ssl3KEADef *kea_def)
8349 {
8350 if (kea_def->signKeyType == dsaKey) {
8351 /* TODO: Fix session tickets for DSS. The server code rejects the
8352 * session ticket received from the client. Bug 1174677 */
8353 return PR_FALSE;
8354 }
8355 return PR_TRUE;
8356 }
8357
8358 static PRBool
ssl3_PeerSupportsCipherSuite(const SECItem * peerSuites,uint16_t suite)8359 ssl3_PeerSupportsCipherSuite(const SECItem *peerSuites, uint16_t suite)
8360 {
8361 for (unsigned int i = 0; i + 1 < peerSuites->len; i += 2) {
8362 PRUint16 suite_i = (peerSuites->data[i] << 8) | peerSuites->data[i + 1];
8363 if (suite_i == suite) {
8364 return PR_TRUE;
8365 }
8366 }
8367 return PR_FALSE;
8368 }
8369
8370 SECStatus
ssl3_NegotiateCipherSuiteInner(sslSocket * ss,const SECItem * suites,PRUint16 version,PRUint16 * suitep)8371 ssl3_NegotiateCipherSuiteInner(sslSocket *ss, const SECItem *suites,
8372 PRUint16 version, PRUint16 *suitep)
8373 {
8374 unsigned int i;
8375 SSLVersionRange vrange = { version, version };
8376
8377 /* If we negotiated an External PSK and that PSK has a ciphersuite
8378 * configured, we need to constrain our choice. If the client does
8379 * not support it, negotiate a certificate auth suite and fall back.
8380 */
8381 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
8382 ss->xtnData.selectedPsk &&
8383 ss->xtnData.selectedPsk->type == ssl_psk_external &&
8384 ss->xtnData.selectedPsk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL) {
8385 PRUint16 pskSuite = ss->xtnData.selectedPsk->zeroRttSuite;
8386 ssl3CipherSuiteCfg *pskSuiteCfg = ssl_LookupCipherSuiteCfgMutable(pskSuite,
8387 ss->cipherSuites);
8388 if (ssl3_config_match(pskSuiteCfg, ss->ssl3.policy, &vrange, ss) &&
8389 ssl3_PeerSupportsCipherSuite(suites, pskSuite)) {
8390 *suitep = pskSuite;
8391 return SECSuccess;
8392 }
8393 }
8394
8395 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
8396 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
8397 if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
8398 continue;
8399 }
8400 if (!ssl3_PeerSupportsCipherSuite(suites, suite->cipher_suite)) {
8401 continue;
8402 }
8403 *suitep = suite->cipher_suite;
8404 return SECSuccess;
8405 }
8406 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8407 return SECFailure;
8408 }
8409
8410 /* Select a cipher suite.
8411 **
8412 ** NOTE: This suite selection algorithm should be the same as the one in
8413 ** ssl3_HandleV2ClientHello().
8414 **
8415 ** If TLS 1.0 is enabled, we could handle the case where the client
8416 ** offered TLS 1.1 but offered only export cipher suites by choosing TLS
8417 ** 1.0 and selecting one of those export cipher suites. However, a secure
8418 ** TLS 1.1 client should not have export cipher suites enabled at all,
8419 ** and a TLS 1.1 client should definitely not be offering *only* export
8420 ** cipher suites. Therefore, we refuse to negotiate export cipher suites
8421 ** with any client that indicates support for TLS 1.1 or higher when we
8422 ** (the server) have TLS 1.1 support enabled.
8423 */
8424 SECStatus
ssl3_NegotiateCipherSuite(sslSocket * ss,const SECItem * suites,PRBool initHashes)8425 ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites,
8426 PRBool initHashes)
8427 {
8428 PRUint16 selected;
8429 SECStatus rv;
8430
8431 /* Ensure that only valid cipher suites are enabled. */
8432 if (ssl3_config_match_init(ss) == 0) {
8433 /* No configured cipher is both supported by PK11 and allowed.
8434 * This is a configuration error, so report handshake failure.*/
8435 FATAL_ERROR(ss, PORT_GetError(), handshake_failure);
8436 return SECFailure;
8437 }
8438
8439 rv = ssl3_NegotiateCipherSuiteInner(ss, suites, ss->version, &selected);
8440 if (rv != SECSuccess) {
8441 return SECFailure;
8442 }
8443
8444 ss->ssl3.hs.cipher_suite = selected;
8445 return ssl3_SetupCipherSuite(ss, initHashes);
8446 }
8447
8448 /*
8449 * Call the SNI config hook.
8450 *
8451 * Called from:
8452 * ssl3_HandleClientHello
8453 * tls13_HandleClientHelloPart2
8454 */
8455 SECStatus
ssl3_ServerCallSNICallback(sslSocket * ss)8456 ssl3_ServerCallSNICallback(sslSocket *ss)
8457 {
8458 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8459 SSL3AlertDescription desc = illegal_parameter;
8460 int ret = 0;
8461
8462 #ifdef SSL_SNI_ALLOW_NAME_CHANGE_2HS
8463 #error("No longer allowed to set SSL_SNI_ALLOW_NAME_CHANGE_2HS")
8464 #endif
8465 if (!ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
8466 if (ss->firstHsDone) {
8467 /* Check that we don't have the name is current spec
8468 * if this extension was not negotiated on the 2d hs. */
8469 PRBool passed = PR_TRUE;
8470 ssl_GetSpecReadLock(ss); /*******************************/
8471 if (ss->ssl3.hs.srvVirtName.data) {
8472 passed = PR_FALSE;
8473 }
8474 ssl_ReleaseSpecReadLock(ss); /***************************/
8475 if (!passed) {
8476 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8477 desc = handshake_failure;
8478 goto alert_loser;
8479 }
8480 }
8481 return SECSuccess;
8482 }
8483
8484 if (ss->sniSocketConfig)
8485 do { /* not a loop */
8486 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
8487 ssl_preinfo_all);
8488
8489 ret = SSL_SNI_SEND_ALERT;
8490 /* If extension is negotiated, the len of names should > 0. */
8491 if (ss->xtnData.sniNameArrSize) {
8492 /* Calling client callback to reconfigure the socket. */
8493 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
8494 ss->xtnData.sniNameArr,
8495 ss->xtnData.sniNameArrSize,
8496 ss->sniSocketConfigArg);
8497 }
8498 if (ret <= SSL_SNI_SEND_ALERT) {
8499 /* Application does not know the name or was not able to
8500 * properly reconfigure the socket. */
8501 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8502 desc = unrecognized_name;
8503 break;
8504 } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
8505 SECStatus rv = SECSuccess;
8506 SECItem pwsNameBuf = { 0, NULL, 0 };
8507 SECItem *pwsName = &pwsNameBuf;
8508 SECItem *cwsName;
8509
8510 ssl_GetSpecWriteLock(ss); /*******************************/
8511 cwsName = &ss->ssl3.hs.srvVirtName;
8512 /* not allow name change on the 2d HS */
8513 if (ss->firstHsDone) {
8514 if (ssl3_ServerNameCompare(pwsName, cwsName)) {
8515 ssl_ReleaseSpecWriteLock(ss); /******************/
8516 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8517 desc = handshake_failure;
8518 ret = SSL_SNI_SEND_ALERT;
8519 break;
8520 }
8521 }
8522 if (pwsName->data) {
8523 SECITEM_FreeItem(pwsName, PR_FALSE);
8524 }
8525 if (cwsName->data) {
8526 rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
8527 }
8528 ssl_ReleaseSpecWriteLock(ss); /**************************/
8529 if (rv != SECSuccess) {
8530 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8531 desc = internal_error;
8532 ret = SSL_SNI_SEND_ALERT;
8533 break;
8534 }
8535 } else if ((unsigned int)ret < ss->xtnData.sniNameArrSize) {
8536 /* Application has configured new socket info. Lets check it
8537 * and save the name. */
8538 SECStatus rv;
8539 SECItem *name = &ss->xtnData.sniNameArr[ret];
8540 SECItem *pwsName;
8541
8542 /* get rid of the old name and save the newly picked. */
8543 /* This code is protected by ssl3HandshakeLock. */
8544 ssl_GetSpecWriteLock(ss); /*******************************/
8545 /* not allow name change on the 2d HS */
8546 if (ss->firstHsDone) {
8547 SECItem *cwsName = &ss->ssl3.hs.srvVirtName;
8548 if (ssl3_ServerNameCompare(name, cwsName)) {
8549 ssl_ReleaseSpecWriteLock(ss); /******************/
8550 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8551 desc = handshake_failure;
8552 ret = SSL_SNI_SEND_ALERT;
8553 break;
8554 }
8555 }
8556 pwsName = &ss->ssl3.hs.srvVirtName;
8557 if (pwsName->data) {
8558 SECITEM_FreeItem(pwsName, PR_FALSE);
8559 }
8560 rv = SECITEM_CopyItem(NULL, pwsName, name);
8561 ssl_ReleaseSpecWriteLock(ss); /***************************/
8562 if (rv != SECSuccess) {
8563 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8564 desc = internal_error;
8565 ret = SSL_SNI_SEND_ALERT;
8566 break;
8567 }
8568 /* Need to tell the client that application has picked
8569 * the name from the offered list and reconfigured the socket.
8570 */
8571 ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_server_name_xtn,
8572 ssl_SendEmptyExtension);
8573 } else {
8574 /* Callback returned index outside of the boundary. */
8575 PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize);
8576 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8577 desc = internal_error;
8578 ret = SSL_SNI_SEND_ALERT;
8579 break;
8580 }
8581 } while (0);
8582 ssl3_FreeSniNameArray(&ss->xtnData);
8583 if (ret <= SSL_SNI_SEND_ALERT) {
8584 /* desc and errCode should be set. */
8585 goto alert_loser;
8586 }
8587
8588 return SECSuccess;
8589
8590 alert_loser:
8591 (void)SSL3_SendAlert(ss, alert_fatal, desc);
8592 PORT_SetError(errCode);
8593 return SECFailure;
8594 }
8595
8596 SECStatus
ssl3_SelectServerCert(sslSocket * ss)8597 ssl3_SelectServerCert(sslSocket *ss)
8598 {
8599 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
8600 PRCList *cursor;
8601 SECStatus rv;
8602
8603 /* If the client didn't include the supported groups extension, assume just
8604 * P-256 support and disable all the other ECDHE groups. This also affects
8605 * ECDHE group selection, but this function is called first. */
8606 if (!ssl3_ExtensionNegotiated(ss, ssl_supported_groups_xtn)) {
8607 unsigned int i;
8608 for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
8609 if (ss->namedGroupPreferences[i] &&
8610 ss->namedGroupPreferences[i]->keaType == ssl_kea_ecdh &&
8611 ss->namedGroupPreferences[i]->name != ssl_grp_ec_secp256r1) {
8612 ss->namedGroupPreferences[i] = NULL;
8613 }
8614 }
8615 }
8616
8617 /* This picks the first certificate that has:
8618 * a) the right authentication method, and
8619 * b) the right named curve (EC only)
8620 *
8621 * We might want to do some sort of ranking here later. For now, it's all
8622 * based on what order they are configured in. */
8623 for (cursor = PR_NEXT_LINK(&ss->serverCerts);
8624 cursor != &ss->serverCerts;
8625 cursor = PR_NEXT_LINK(cursor)) {
8626 sslServerCert *cert = (sslServerCert *)cursor;
8627 if (kea_def->authKeyType == ssl_auth_rsa_sign) {
8628 /* We consider PSS certificates here as well for TLS 1.2. */
8629 if (!SSL_CERT_IS(cert, ssl_auth_rsa_sign) &&
8630 (!SSL_CERT_IS(cert, ssl_auth_rsa_pss) ||
8631 ss->version < SSL_LIBRARY_VERSION_TLS_1_2)) {
8632 continue;
8633 }
8634 } else {
8635 if (!SSL_CERT_IS(cert, kea_def->authKeyType)) {
8636 continue;
8637 }
8638 if (SSL_CERT_IS_EC(cert) &&
8639 !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
8640 continue;
8641 }
8642 }
8643
8644 /* Found one. */
8645 ss->sec.serverCert = cert;
8646 ss->sec.authKeyBits = cert->serverKeyBits;
8647
8648 /* Don't pick a signature scheme if we aren't going to use it. */
8649 if (kea_def->signKeyType == nullKey) {
8650 ss->sec.authType = kea_def->authKeyType;
8651 return SECSuccess;
8652 }
8653
8654 rv = ssl3_PickServerSignatureScheme(ss);
8655 if (rv != SECSuccess) {
8656 return SECFailure;
8657 }
8658 ss->sec.authType =
8659 ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme);
8660 return SECSuccess;
8661 }
8662
8663 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8664 return SECFailure;
8665 }
8666
8667 static SECStatus
ssl_GenerateServerRandom(sslSocket * ss)8668 ssl_GenerateServerRandom(sslSocket *ss)
8669 {
8670 SECStatus rv;
8671 PRUint8 *downgradeSentinel;
8672
8673 rv = ssl3_GetNewRandom(ss->ssl3.hs.server_random);
8674 if (rv != SECSuccess) {
8675 return SECFailure;
8676 }
8677
8678 if (ss->version == ss->vrange.max) {
8679 return SECSuccess;
8680 }
8681 #ifdef DTLS_1_3_DRAFT_VERSION
8682 if (IS_DTLS(ss)) {
8683 return SECSuccess;
8684 }
8685 #endif
8686
8687 /*
8688 * [RFC 8446 Section 4.1.3].
8689 *
8690 * TLS 1.3 servers which negotiate TLS 1.2 or below in response to a
8691 * ClientHello MUST set the last 8 bytes of their Random value specially in
8692 * their ServerHello.
8693 *
8694 * If negotiating TLS 1.2, TLS 1.3 servers MUST set the last 8 bytes of
8695 * their Random value to the bytes:
8696 *
8697 * 44 4F 57 4E 47 52 44 01
8698 *
8699 * If negotiating TLS 1.1 or below, TLS 1.3 servers MUST, and TLS 1.2
8700 * servers SHOULD, set the last 8 bytes of their ServerHello.Random value to
8701 * the bytes:
8702 *
8703 * 44 4F 57 4E 47 52 44 00
8704 */
8705 downgradeSentinel =
8706 ss->ssl3.hs.server_random +
8707 SSL3_RANDOM_LENGTH - sizeof(tls12_downgrade_random);
8708 if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_2) {
8709 switch (ss->version) {
8710 case SSL_LIBRARY_VERSION_TLS_1_2:
8711 /* vrange.max > 1.2, since we didn't early exit above. */
8712 PORT_Memcpy(downgradeSentinel,
8713 tls12_downgrade_random, sizeof(tls12_downgrade_random));
8714 break;
8715 case SSL_LIBRARY_VERSION_TLS_1_1:
8716 case SSL_LIBRARY_VERSION_TLS_1_0:
8717 PORT_Memcpy(downgradeSentinel,
8718 tls1_downgrade_random, sizeof(tls1_downgrade_random));
8719 break;
8720 default:
8721 /* Do not change random. */
8722 break;
8723 }
8724 }
8725
8726 return SECSuccess;
8727 }
8728
8729 SECStatus
ssl3_HandleClientHelloPreamble(sslSocket * ss,PRUint8 ** b,PRUint32 * length,SECItem * sidBytes,SECItem * cookieBytes,SECItem * suites,SECItem * comps)8730 ssl3_HandleClientHelloPreamble(sslSocket *ss, PRUint8 **b, PRUint32 *length, SECItem *sidBytes,
8731 SECItem *cookieBytes, SECItem *suites, SECItem *comps)
8732 {
8733 SECStatus rv;
8734 PRUint32 tmp;
8735 rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
8736 if (rv != SECSuccess) {
8737 return SECFailure; /* malformed, alert already sent */
8738 }
8739
8740 /* Translate the version. */
8741 if (IS_DTLS(ss)) {
8742 ss->clientHelloVersion = dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
8743 } else {
8744 ss->clientHelloVersion = (SSL3ProtocolVersion)tmp;
8745 }
8746
8747 /* Grab the client random data. */
8748 rv = ssl3_ConsumeHandshake(
8749 ss, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, b, length);
8750 if (rv != SECSuccess) {
8751 return SECFailure; /* malformed */
8752 }
8753
8754 /* Grab the client's SID, if present. */
8755 rv = ssl3_ConsumeHandshakeVariable(ss, sidBytes, 1, b, length);
8756 if (rv != SECSuccess) {
8757 return SECFailure; /* malformed */
8758 }
8759
8760 /* Grab the client's cookie, if present. It is checked after version negotiation. */
8761 if (IS_DTLS(ss)) {
8762 rv = ssl3_ConsumeHandshakeVariable(ss, cookieBytes, 1, b, length);
8763 if (rv != SECSuccess) {
8764 return SECFailure; /* malformed */
8765 }
8766 }
8767
8768 /* Grab the list of cipher suites. */
8769 rv = ssl3_ConsumeHandshakeVariable(ss, suites, 2, b, length);
8770 if (rv != SECSuccess) {
8771 return SECFailure; /* malformed */
8772 }
8773
8774 /* Grab the list of compression methods. */
8775 rv = ssl3_ConsumeHandshakeVariable(ss, comps, 1, b, length);
8776 if (rv != SECSuccess) {
8777 return SECFailure; /* malformed */
8778 }
8779 return SECSuccess;
8780 }
8781
8782 static SECStatus
ssl3_ValidatePreambleWithVersion(sslSocket * ss,const SECItem * sidBytes,const SECItem * comps,const SECItem * cookieBytes)8783 ssl3_ValidatePreambleWithVersion(sslSocket *ss, const SECItem *sidBytes, const SECItem *comps,
8784 const SECItem *cookieBytes)
8785 {
8786 SECStatus rv;
8787 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
8788 if (sidBytes->len > 0 && !IS_DTLS(ss)) {
8789 SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
8790 rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.fakeSid, sidBytes);
8791 if (rv != SECSuccess) {
8792 FATAL_ERROR(ss, PORT_GetError(), internal_error);
8793 return SECFailure;
8794 }
8795 }
8796
8797 /* TLS 1.3 requires that compression include only null. */
8798 if (comps->len != 1 || comps->data[0] != ssl_compression_null) {
8799 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
8800 return SECFailure;
8801 }
8802
8803 /* receivedCcs is only valid if we sent an HRR. */
8804 if (ss->ssl3.hs.receivedCcs && !ss->ssl3.hs.helloRetry) {
8805 FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message);
8806 return SECFailure;
8807 }
8808
8809 /* A DTLS 1.3-only client MUST set the legacy_cookie field to zero length.
8810 * If a DTLS 1.3 ClientHello is received with any other value in this field,
8811 * the server MUST abort the handshake with an "illegal_parameter" alert. */
8812 if (IS_DTLS(ss) && cookieBytes->len != 0) {
8813 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
8814 return SECFailure;
8815 }
8816 } else {
8817 /* ECH not possible here. */
8818 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
8819
8820 /* HRR and ECH are TLS1.3-only. We ignore the Cookie extension here. */
8821 if (ss->ssl3.hs.helloRetry) {
8822 FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, protocol_version);
8823 return SECFailure;
8824 }
8825
8826 /* receivedCcs is only valid if we sent an HRR. */
8827 if (ss->ssl3.hs.receivedCcs) {
8828 FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message);
8829 return SECFailure;
8830 }
8831
8832 /* TLS versions prior to 1.3 must include null somewhere. */
8833 if (comps->len < 1 ||
8834 !memchr(comps->data, ssl_compression_null, comps->len)) {
8835 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
8836 return SECFailure;
8837 }
8838
8839 /* We never send cookies in DTLS 1.2. */
8840 if (IS_DTLS(ss) && cookieBytes->len != 0) {
8841 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
8842 return SECFailure;
8843 }
8844 }
8845
8846 return SECSuccess;
8847 }
8848
8849 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
8850 * ssl3 Client Hello message.
8851 * Caller must hold Handshake and RecvBuf locks.
8852 */
8853 static SECStatus
ssl3_HandleClientHello(sslSocket * ss,PRUint8 * b,PRUint32 length)8854 ssl3_HandleClientHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
8855 {
8856 sslSessionID *sid = NULL;
8857 unsigned int i;
8858 SECStatus rv;
8859 PRUint32 extensionLength;
8860 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8861 SSL3AlertDescription desc = illegal_parameter;
8862 SSL3AlertLevel level = alert_fatal;
8863 TLSExtension *versionExtension;
8864 SECItem sidBytes = { siBuffer, NULL, 0 };
8865 SECItem cookieBytes = { siBuffer, NULL, 0 };
8866 SECItem suites = { siBuffer, NULL, 0 };
8867 SECItem comps = { siBuffer, NULL, 0 };
8868 SECItem *echInner = NULL;
8869 PRBool isTLS13;
8870 const PRUint8 *savedMsg = b;
8871 const PRUint32 savedLen = length;
8872
8873 SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
8874 SSL_GETPID(), ss->fd));
8875
8876 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
8877 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8878 ss->ssl3.hs.preliminaryInfo = 0;
8879
8880 if (!ss->sec.isServer ||
8881 (ss->ssl3.hs.ws != wait_client_hello &&
8882 ss->ssl3.hs.ws != idle_handshake)) {
8883 desc = unexpected_message;
8884 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
8885 goto alert_loser;
8886 }
8887 if (ss->ssl3.hs.ws == idle_handshake) {
8888 /* Refuse re-handshake when we have already negotiated TLS 1.3. */
8889 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
8890 desc = unexpected_message;
8891 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
8892 goto alert_loser;
8893 }
8894 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
8895 desc = no_renegotiation;
8896 level = alert_warning;
8897 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
8898 goto alert_loser;
8899 }
8900 }
8901
8902 /* We should always be in a fresh state. */
8903 SSL_ASSERT_HASHES_EMPTY(ss);
8904
8905 /* Get peer name of client */
8906 rv = ssl_GetPeerInfo(ss);
8907 if (rv != SECSuccess) {
8908 return rv; /* error code is set. */
8909 }
8910
8911 /* We might be starting session renegotiation in which case we should
8912 * clear previous state.
8913 */
8914 ssl3_ResetExtensionData(&ss->xtnData, ss);
8915 ss->statelessResume = PR_FALSE;
8916
8917 if (IS_DTLS(ss)) {
8918 dtls_RehandshakeCleanup(ss);
8919 }
8920
8921 rv = ssl3_HandleClientHelloPreamble(ss, &b, &length, &sidBytes,
8922 &cookieBytes, &suites, &comps);
8923 if (rv != SECSuccess) {
8924 goto loser; /* malformed */
8925 }
8926
8927 /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
8928 * we are restarting a previous session until extensions have been
8929 * parsed, since we might have received a SessionTicket extension.
8930 * Note: we allow extensions even when negotiating SSL3 for the sake
8931 * of interoperability (and backwards compatibility).
8932 */
8933 if (length) {
8934 /* Get length of hello extensions */
8935 rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
8936 if (rv != SECSuccess) {
8937 goto loser; /* alert already sent */
8938 }
8939 if (extensionLength != length) {
8940 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8941 desc = decode_error;
8942 goto alert_loser;
8943 }
8944
8945 rv = ssl3_ParseExtensions(ss, &b, &length);
8946 if (rv != SECSuccess) {
8947 goto loser; /* malformed */
8948 }
8949 }
8950
8951 versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
8952 if (versionExtension) {
8953 rv = tls13_NegotiateVersion(ss, versionExtension);
8954 if (rv != SECSuccess) {
8955 errCode = PORT_GetError();
8956 desc = (errCode == SSL_ERROR_UNSUPPORTED_VERSION) ? protocol_version : illegal_parameter;
8957 goto alert_loser;
8958 }
8959 } else {
8960 /* The PR_MIN here ensures that we never negotiate 1.3 if the
8961 * peer didn't offer "supported_versions". */
8962 rv = ssl3_NegotiateVersion(ss,
8963 PR_MIN(ss->clientHelloVersion,
8964 SSL_LIBRARY_VERSION_TLS_1_2),
8965 PR_TRUE);
8966 if (rv != SECSuccess) {
8967 desc = (ss->clientHelloVersion > SSL_LIBRARY_VERSION_3_0) ? protocol_version
8968 : handshake_failure;
8969 errCode = SSL_ERROR_UNSUPPORTED_VERSION;
8970 goto alert_loser;
8971 }
8972 }
8973 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
8974
8975 /* Update the write spec to match the selected version. */
8976 if (!ss->firstHsDone) {
8977 ssl_GetSpecWriteLock(ss);
8978 ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
8979 ssl_ReleaseSpecWriteLock(ss);
8980 }
8981
8982 isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
8983 if (isTLS13) {
8984 if (ss->firstHsDone) {
8985 desc = unexpected_message;
8986 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
8987 goto alert_loser;
8988 }
8989
8990 /* If there is a cookie, then this is a second ClientHello (TLS 1.3). */
8991 if (ssl3_FindExtension(ss, ssl_tls13_cookie_xtn)) {
8992 ss->ssl3.hs.helloRetry = PR_TRUE;
8993 }
8994
8995 rv = tls13_MaybeHandleEch(ss, savedMsg, savedLen, &sidBytes,
8996 &comps, &cookieBytes, &suites, &echInner);
8997 if (rv != SECSuccess) {
8998 errCode = PORT_GetError();
8999 goto loser; /* code set, alert sent. */
9000 }
9001 }
9002
9003 rv = ssl3_ValidatePreambleWithVersion(ss, &sidBytes, &comps, &cookieBytes);
9004 if (rv != SECSuccess) {
9005 errCode = PORT_GetError();
9006 goto loser; /* code set, alert sent. */
9007 }
9008
9009 /* Now parse the rest of the extensions. */
9010 rv = ssl3_HandleParsedExtensions(ss, ssl_hs_client_hello);
9011 ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
9012 if (rv != SECSuccess) {
9013 if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
9014 errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
9015 }
9016 goto loser; /* malformed */
9017 }
9018
9019 /* If the ClientHello version is less than our maximum version, check for a
9020 * TLS_FALLBACK_SCSV and reject the connection if found. */
9021 if (ss->vrange.max > ss->version) {
9022 for (i = 0; i + 1 < suites.len; i += 2) {
9023 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
9024 if (suite_i != TLS_FALLBACK_SCSV)
9025 continue;
9026 desc = inappropriate_fallback;
9027 errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
9028 goto alert_loser;
9029 }
9030 }
9031
9032 if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9033 /* If we didn't receive an RI extension, look for the SCSV,
9034 * and if found, treat it just like an empty RI extension
9035 * by processing a local copy of an empty RI extension.
9036 */
9037 for (i = 0; i + 1 < suites.len; i += 2) {
9038 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
9039 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
9040 PRUint8 *b2 = (PRUint8 *)emptyRIext;
9041 PRUint32 L2 = sizeof emptyRIext;
9042 (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
9043 break;
9044 }
9045 }
9046 }
9047
9048 /* The check for renegotiation in TLS 1.3 is earlier. */
9049 if (!isTLS13) {
9050 if (ss->firstHsDone &&
9051 (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
9052 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) &&
9053 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9054 desc = no_renegotiation;
9055 level = alert_warning;
9056 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9057 goto alert_loser;
9058 }
9059 if ((ss->opt.requireSafeNegotiation ||
9060 (ss->firstHsDone && ss->peerRequestedProtection)) &&
9061 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9062 desc = handshake_failure;
9063 errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
9064 goto alert_loser;
9065 }
9066 }
9067
9068 /* We do stateful resumes only if we are in TLS < 1.3 and
9069 * either of the following conditions are satisfied:
9070 * (1) the client does not support the session ticket extension, or
9071 * (2) the client support the session ticket extension, but sent an
9072 * empty ticket.
9073 */
9074 if (!isTLS13 &&
9075 (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
9076 ss->xtnData.emptySessionTicket)) {
9077 if (sidBytes.len > 0 && !ss->opt.noCache) {
9078 SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
9079 SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
9080 ss->sec.ci.peer.pr_s6_addr32[1],
9081 ss->sec.ci.peer.pr_s6_addr32[2],
9082 ss->sec.ci.peer.pr_s6_addr32[3]));
9083 if (ssl_sid_lookup) {
9084 sid = (*ssl_sid_lookup)(ssl_Time(ss), &ss->sec.ci.peer,
9085 sidBytes.data, sidBytes.len, ss->dbHandle);
9086 } else {
9087 errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
9088 goto loser;
9089 }
9090 }
9091 } else if (ss->statelessResume) {
9092 /* Fill in the client's session ID if doing a stateless resume.
9093 * (When doing stateless resumes, server echos client's SessionID.)
9094 * This branch also handles TLS 1.3 resumption-PSK.
9095 */
9096 sid = ss->sec.ci.sid;
9097 PORT_Assert(sid != NULL); /* Should have already been filled in.*/
9098
9099 if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
9100 sid->u.ssl3.sessionIDLength = sidBytes.len;
9101 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
9102 sidBytes.len);
9103 sid->u.ssl3.sessionIDLength = sidBytes.len;
9104 } else {
9105 sid->u.ssl3.sessionIDLength = 0;
9106 }
9107 ss->sec.ci.sid = NULL;
9108 }
9109
9110 /* Free a potentially leftover session ID from a previous handshake. */
9111 if (ss->sec.ci.sid) {
9112 ssl_FreeSID(ss->sec.ci.sid);
9113 ss->sec.ci.sid = NULL;
9114 }
9115
9116 if (sid != NULL) {
9117 /* We've found a session cache entry for this client.
9118 * Now, if we're going to require a client-auth cert,
9119 * and we don't already have this client's cert in the session cache,
9120 * and this is the first handshake on this connection (not a redo),
9121 * then drop this old cache entry and start a new session.
9122 */
9123 if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
9124 ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
9125 (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
9126 ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) &&
9127 !ss->firstHsDone))) {
9128
9129 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
9130 ssl_FreeSID(sid);
9131 sid = NULL;
9132 ss->statelessResume = PR_FALSE;
9133 }
9134 }
9135
9136 if (IS_DTLS(ss)) {
9137 ssl3_DisableNonDTLSSuites(ss);
9138 dtls_ReceivedFirstMessageInFlight(ss);
9139 }
9140
9141 if (isTLS13) {
9142 rv = tls13_HandleClientHelloPart2(ss, &suites, sid,
9143 ss->ssl3.hs.echAccepted ? echInner->data : savedMsg,
9144 ss->ssl3.hs.echAccepted ? echInner->len : savedLen);
9145 SECITEM_FreeItem(echInner, PR_TRUE);
9146 echInner = NULL;
9147 } else {
9148 rv = ssl3_HandleClientHelloPart2(ss, &suites, sid,
9149 savedMsg, savedLen);
9150 }
9151 if (rv != SECSuccess) {
9152 errCode = PORT_GetError();
9153 goto loser;
9154 }
9155 return SECSuccess;
9156
9157 alert_loser:
9158 (void)SSL3_SendAlert(ss, level, desc);
9159 /* FALLTHRU */
9160 loser:
9161 SECITEM_FreeItem(echInner, PR_TRUE);
9162 PORT_SetError(errCode);
9163 return SECFailure;
9164 }
9165
9166 /* unwrap helper function to handle the case where the wrapKey doesn't wind
9167 * up in the correct token for the master secret */
9168 PK11SymKey *
ssl_unwrapSymKey(PK11SymKey * wrapKey,CK_MECHANISM_TYPE wrapType,SECItem * param,SECItem * wrappedKey,CK_MECHANISM_TYPE target,CK_ATTRIBUTE_TYPE operation,int keySize,CK_FLAGS keyFlags,void * pinArg)9169 ssl_unwrapSymKey(PK11SymKey *wrapKey,
9170 CK_MECHANISM_TYPE wrapType, SECItem *param,
9171 SECItem *wrappedKey,
9172 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
9173 int keySize, CK_FLAGS keyFlags, void *pinArg)
9174 {
9175 PK11SymKey *unwrappedKey;
9176
9177 /* unwrap the master secret. */
9178 unwrappedKey = PK11_UnwrapSymKeyWithFlags(wrapKey, wrapType, param,
9179 wrappedKey, target, operation, keySize,
9180 keyFlags);
9181 if (!unwrappedKey) {
9182 PK11SlotInfo *targetSlot = PK11_GetBestSlot(target, pinArg);
9183 PK11SymKey *newWrapKey;
9184
9185 /* it's possible that we failed to unwrap because the wrapKey is in
9186 * a slot that can't handle target. Move the wrapKey to a slot that
9187 * can handle this mechanism and retry the operation */
9188 if (targetSlot == NULL) {
9189 return NULL;
9190 }
9191 newWrapKey = PK11_MoveSymKey(targetSlot, CKA_UNWRAP, 0,
9192 PR_FALSE, wrapKey);
9193 PK11_FreeSlot(targetSlot);
9194 if (newWrapKey == NULL) {
9195 return NULL;
9196 }
9197 unwrappedKey = PK11_UnwrapSymKeyWithFlags(newWrapKey, wrapType, param,
9198 wrappedKey, target, operation, keySize,
9199 keyFlags);
9200 PK11_FreeSymKey(newWrapKey);
9201 }
9202 return unwrappedKey;
9203 }
9204
9205 static SECStatus
ssl3_UnwrapMasterSecretServer(sslSocket * ss,sslSessionID * sid,PK11SymKey ** ms)9206 ssl3_UnwrapMasterSecretServer(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
9207 {
9208 PK11SymKey *wrapKey;
9209 CK_FLAGS keyFlags = 0;
9210 SECItem wrappedMS = {
9211 siBuffer,
9212 sid->u.ssl3.keys.wrapped_master_secret,
9213 sid->u.ssl3.keys.wrapped_master_secret_len
9214 };
9215
9216 wrapKey = ssl3_GetWrappingKey(ss, NULL, sid->u.ssl3.masterWrapMech,
9217 ss->pkcs11PinArg);
9218 if (!wrapKey) {
9219 return SECFailure;
9220 }
9221
9222 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
9223 keyFlags = CKF_SIGN | CKF_VERIFY;
9224 }
9225
9226 *ms = ssl_unwrapSymKey(wrapKey, sid->u.ssl3.masterWrapMech, NULL,
9227 &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
9228 CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH,
9229 keyFlags, ss->pkcs11PinArg);
9230 PK11_FreeSymKey(wrapKey);
9231 if (!*ms) {
9232 SSL_TRC(10, ("%d: SSL3[%d]: server wrapping key found, but couldn't unwrap MasterSecret. wrapMech=0x%0lx",
9233 SSL_GETPID(), ss->fd, sid->u.ssl3.masterWrapMech));
9234 return SECFailure;
9235 }
9236 return SECSuccess;
9237 }
9238
9239 static SECStatus
ssl3_HandleClientHelloPart2(sslSocket * ss,SECItem * suites,sslSessionID * sid,const PRUint8 * msg,unsigned int len)9240 ssl3_HandleClientHelloPart2(sslSocket *ss,
9241 SECItem *suites,
9242 sslSessionID *sid,
9243 const PRUint8 *msg,
9244 unsigned int len)
9245 {
9246 PRBool haveXmitBufLock = PR_FALSE;
9247 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9248 SSL3AlertDescription desc = illegal_parameter;
9249 SECStatus rv;
9250 unsigned int i;
9251 unsigned int j;
9252
9253 rv = ssl_HashHandshakeMessage(ss, ssl_hs_client_hello, msg, len);
9254 if (rv != SECSuccess) {
9255 errCode = SEC_ERROR_LIBRARY_FAILURE;
9256 desc = internal_error;
9257 goto alert_loser;
9258 }
9259
9260 /* If we already have a session for this client, be sure to pick the same
9261 ** cipher suite we picked before. This is not a loop, despite appearances.
9262 */
9263 if (sid)
9264 do {
9265 ssl3CipherSuiteCfg *suite;
9266 SSLVersionRange vrange = { ss->version, ss->version };
9267
9268 suite = ss->cipherSuites;
9269 /* Find the entry for the cipher suite used in the cached session. */
9270 for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
9271 if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
9272 break;
9273 }
9274 PORT_Assert(j > 0);
9275 if (j == 0)
9276 break;
9277
9278 /* Double check that the cached cipher suite is still enabled,
9279 * implemented, and allowed by policy. Might have been disabled.
9280 */
9281 if (ssl3_config_match_init(ss) == 0) {
9282 desc = handshake_failure;
9283 errCode = PORT_GetError();
9284 goto alert_loser;
9285 }
9286 if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss))
9287 break;
9288
9289 /* Double check that the cached cipher suite is in the client's
9290 * list. If it isn't, fall through and start a new session. */
9291 for (i = 0; i + 1 < suites->len; i += 2) {
9292 PRUint16 suite_i = (suites->data[i] << 8) | suites->data[i + 1];
9293 if (suite_i == suite->cipher_suite) {
9294 ss->ssl3.hs.cipher_suite = suite_i;
9295 rv = ssl3_SetupCipherSuite(ss, PR_TRUE);
9296 if (rv != SECSuccess) {
9297 desc = internal_error;
9298 errCode = PORT_GetError();
9299 goto alert_loser;
9300 }
9301
9302 goto cipher_found;
9303 }
9304 }
9305 } while (0);
9306 /* START A NEW SESSION */
9307
9308 rv = ssl3_NegotiateCipherSuite(ss, suites, PR_TRUE);
9309 if (rv != SECSuccess) {
9310 desc = handshake_failure;
9311 errCode = PORT_GetError();
9312 goto alert_loser;
9313 }
9314
9315 cipher_found:
9316 suites->data = NULL;
9317
9318 /* If there are any failures while processing the old sid,
9319 * we don't consider them to be errors. Instead, We just behave
9320 * as if the client had sent us no sid to begin with, and make a new one.
9321 * The exception here is attempts to resume extended_master_secret
9322 * sessions without the extension, which causes an alert.
9323 */
9324 if (sid != NULL)
9325 do {
9326 PK11SymKey *masterSecret;
9327
9328 if (sid->version != ss->version ||
9329 sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
9330 break; /* not an error */
9331 }
9332
9333 /* server sids don't remember the server cert we previously sent,
9334 ** but they do remember the slot we originally used, so we
9335 ** can locate it again, provided that the current ssl socket
9336 ** has had its server certs configured the same as the previous one.
9337 */
9338 ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType, sid->namedCurve);
9339 if (!ss->sec.serverCert || !ss->sec.serverCert->serverCert) {
9340 /* A compatible certificate must not have been configured. It
9341 * might not be the same certificate, but we only find that out
9342 * when the ticket fails to decrypt. */
9343 break;
9344 }
9345
9346 /* [draft-ietf-tls-session-hash-06; Section 5.3]
9347 * o If the original session did not use the "extended_master_secret"
9348 * extension but the new ClientHello contains the extension, then the
9349 * server MUST NOT perform the abbreviated handshake. Instead, it
9350 * SHOULD continue with a full handshake (as described in
9351 * Section 5.2) to negotiate a new session.
9352 *
9353 * o If the original session used the "extended_master_secret"
9354 * extension but the new ClientHello does not contain the extension,
9355 * the server MUST abort the abbreviated handshake.
9356 */
9357 if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
9358 if (!sid->u.ssl3.keys.extendedMasterSecretUsed) {
9359 break; /* not an error */
9360 }
9361 } else {
9362 if (sid->u.ssl3.keys.extendedMasterSecretUsed) {
9363 /* Note: we do not destroy the session */
9364 desc = handshake_failure;
9365 errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
9366 goto alert_loser;
9367 }
9368 }
9369
9370 if (ss->sec.ci.sid) {
9371 ssl_UncacheSessionID(ss);
9372 PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */
9373 if (ss->sec.ci.sid != sid) {
9374 ssl_FreeSID(ss->sec.ci.sid);
9375 }
9376 ss->sec.ci.sid = NULL;
9377 }
9378
9379 /* we need to resurrect the master secret.... */
9380 rv = ssl3_UnwrapMasterSecretServer(ss, sid, &masterSecret);
9381 if (rv != SECSuccess) {
9382 break; /* not an error */
9383 }
9384
9385 ss->sec.ci.sid = sid;
9386 if (sid->peerCert != NULL) {
9387 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
9388 }
9389
9390 /*
9391 * Old SID passed all tests, so resume this old session.
9392 */
9393 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_hits);
9394 if (ss->statelessResume)
9395 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_stateless_resumes);
9396 ss->ssl3.hs.isResuming = PR_TRUE;
9397
9398 ss->sec.authType = sid->authType;
9399 ss->sec.authKeyBits = sid->authKeyBits;
9400 ss->sec.keaType = sid->keaType;
9401 ss->sec.keaKeyBits = sid->keaKeyBits;
9402 ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
9403 ss->sec.signatureScheme = sid->sigScheme;
9404
9405 ss->sec.localCert =
9406 CERT_DupCertificate(ss->sec.serverCert->serverCert);
9407
9408 /* Copy cached name in to pending spec */
9409 if (sid != NULL &&
9410 sid->version > SSL_LIBRARY_VERSION_3_0 &&
9411 sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
9412 /* Set server name from sid */
9413 SECItem *sidName = &sid->u.ssl3.srvName;
9414 SECItem *pwsName = &ss->ssl3.hs.srvVirtName;
9415 if (pwsName->data) {
9416 SECITEM_FreeItem(pwsName, PR_FALSE);
9417 }
9418 rv = SECITEM_CopyItem(NULL, pwsName, sidName);
9419 if (rv != SECSuccess) {
9420 errCode = PORT_GetError();
9421 desc = internal_error;
9422 goto alert_loser;
9423 }
9424 }
9425
9426 /* Clean up sni name array */
9427 ssl3_FreeSniNameArray(&ss->xtnData);
9428
9429 ssl_GetXmitBufLock(ss);
9430 haveXmitBufLock = PR_TRUE;
9431
9432 rv = ssl3_SendServerHello(ss);
9433 if (rv != SECSuccess) {
9434 errCode = PORT_GetError();
9435 goto loser;
9436 }
9437
9438 /* We are re-using the old MS, so no need to derive again. */
9439 rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE);
9440 if (rv != SECSuccess) {
9441 errCode = PORT_GetError();
9442 goto loser;
9443 }
9444
9445 rv = ssl3_SendChangeCipherSpecs(ss);
9446 if (rv != SECSuccess) {
9447 errCode = PORT_GetError();
9448 goto loser;
9449 }
9450 rv = ssl3_SendFinished(ss, 0);
9451 ss->ssl3.hs.ws = wait_change_cipher;
9452 if (rv != SECSuccess) {
9453 errCode = PORT_GetError();
9454 goto loser;
9455 }
9456
9457 if (haveXmitBufLock) {
9458 ssl_ReleaseXmitBufLock(ss);
9459 }
9460
9461 return SECSuccess;
9462 } while (0);
9463
9464 if (sid) { /* we had a sid, but it's no longer valid, free it */
9465 ss->statelessResume = PR_FALSE;
9466 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
9467 ssl_UncacheSessionID(ss);
9468 ssl_FreeSID(sid);
9469 sid = NULL;
9470 }
9471 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
9472
9473 /* We only send a session ticket extension if the client supports
9474 * the extension and we are unable to resume.
9475 *
9476 * TODO: send a session ticket if performing a stateful
9477 * resumption. (As per RFC4507, a server may issue a session
9478 * ticket while doing a (stateless or stateful) session resume,
9479 * but OpenSSL-0.9.8g does not accept session tickets while
9480 * resuming.)
9481 */
9482 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
9483 ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
9484 ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_session_ticket_xtn,
9485 ssl_SendEmptyExtension);
9486 }
9487
9488 rv = ssl3_ServerCallSNICallback(ss);
9489 if (rv != SECSuccess) {
9490 /* The alert has already been sent. */
9491 errCode = PORT_GetError();
9492 goto loser;
9493 }
9494
9495 rv = ssl3_SelectServerCert(ss);
9496 if (rv != SECSuccess) {
9497 errCode = PORT_GetError();
9498 desc = handshake_failure;
9499 goto alert_loser;
9500 }
9501
9502 sid = ssl3_NewSessionID(ss, PR_TRUE);
9503 if (sid == NULL) {
9504 errCode = PORT_GetError();
9505 goto loser; /* memory error is set. */
9506 }
9507 ss->sec.ci.sid = sid;
9508
9509 sid->u.ssl3.keys.extendedMasterSecretUsed =
9510 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
9511 ss->ssl3.hs.isResuming = PR_FALSE;
9512
9513 ssl_GetXmitBufLock(ss);
9514 rv = ssl3_SendServerHelloSequence(ss);
9515 ssl_ReleaseXmitBufLock(ss);
9516 if (rv != SECSuccess) {
9517 errCode = PORT_GetError();
9518 desc = handshake_failure;
9519 goto alert_loser;
9520 }
9521
9522 if (haveXmitBufLock) {
9523 ssl_ReleaseXmitBufLock(ss);
9524 }
9525
9526 return SECSuccess;
9527
9528 alert_loser:
9529 (void)SSL3_SendAlert(ss, alert_fatal, desc);
9530 /* FALLTHRU */
9531 loser:
9532 if (sid && sid != ss->sec.ci.sid) {
9533 ssl_UncacheSessionID(ss);
9534 ssl_FreeSID(sid);
9535 }
9536
9537 if (haveXmitBufLock) {
9538 ssl_ReleaseXmitBufLock(ss);
9539 }
9540
9541 PORT_SetError(errCode);
9542 return SECFailure;
9543 }
9544
9545 /*
9546 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
9547 * in asking to use the V3 handshake.
9548 */
9549 SECStatus
ssl3_HandleV2ClientHello(sslSocket * ss,unsigned char * buffer,unsigned int length,PRUint8 padding)9550 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, unsigned int length,
9551 PRUint8 padding)
9552 {
9553 sslSessionID *sid = NULL;
9554 unsigned char *suites;
9555 unsigned char *random;
9556 SSL3ProtocolVersion version;
9557 SECStatus rv;
9558 unsigned int i;
9559 unsigned int j;
9560 unsigned int sid_length;
9561 unsigned int suite_length;
9562 unsigned int rand_length;
9563 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9564 SSL3AlertDescription desc = handshake_failure;
9565 unsigned int total = SSL_HL_CLIENT_HELLO_HBYTES;
9566
9567 SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
9568
9569 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
9570
9571 ssl_GetSSL3HandshakeLock(ss);
9572
9573 version = (buffer[1] << 8) | buffer[2];
9574 if (version < SSL_LIBRARY_VERSION_3_0) {
9575 goto loser;
9576 }
9577
9578 ssl3_RestartHandshakeHashes(ss);
9579
9580 if (ss->ssl3.hs.ws != wait_client_hello) {
9581 desc = unexpected_message;
9582 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
9583 goto alert_loser;
9584 }
9585
9586 total += suite_length = (buffer[3] << 8) | buffer[4];
9587 total += sid_length = (buffer[5] << 8) | buffer[6];
9588 total += rand_length = (buffer[7] << 8) | buffer[8];
9589 total += padding;
9590 ss->clientHelloVersion = version;
9591
9592 if (version >= SSL_LIBRARY_VERSION_TLS_1_3) {
9593 /* [draft-ietf-tls-tls-11; C.3] forbids sending a TLS 1.3
9594 * ClientHello using the backwards-compatible format. */
9595 desc = illegal_parameter;
9596 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9597 goto alert_loser;
9598 }
9599
9600 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
9601 if (rv != SECSuccess) {
9602 /* send back which ever alert client will understand. */
9603 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
9604 : handshake_failure;
9605 errCode = SSL_ERROR_UNSUPPORTED_VERSION;
9606 goto alert_loser;
9607 }
9608 /* ECH not possible here. */
9609 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
9610 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
9611 if (!ss->firstHsDone) {
9612 ssl_GetSpecWriteLock(ss);
9613 ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
9614 ssl_ReleaseSpecWriteLock(ss);
9615 }
9616
9617 /* if we get a non-zero SID, just ignore it. */
9618 if (length != total) {
9619 SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
9620 SSL_GETPID(), ss->fd, length, total));
9621 desc = illegal_parameter;
9622 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9623 goto alert_loser;
9624 }
9625
9626 suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
9627 random = suites + suite_length + sid_length;
9628
9629 if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
9630 rand_length > SSL_MAX_CHALLENGE_BYTES) {
9631 desc = illegal_parameter;
9632 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9633 goto alert_loser;
9634 }
9635
9636 PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
9637
9638 PORT_Memset(ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
9639 PORT_Memcpy(&ss->ssl3.hs.client_random[SSL3_RANDOM_LENGTH - rand_length],
9640 random, rand_length);
9641
9642 PRINT_BUF(60, (ss, "client random:", ss->ssl3.hs.client_random,
9643 SSL3_RANDOM_LENGTH));
9644
9645 if (ssl3_config_match_init(ss) == 0) {
9646 errCode = PORT_GetError(); /* error code is already set. */
9647 goto alert_loser;
9648 }
9649
9650 /* Select a cipher suite.
9651 **
9652 ** NOTE: This suite selection algorithm should be the same as the one in
9653 ** ssl3_HandleClientHello().
9654 */
9655 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
9656 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
9657 SSLVersionRange vrange = { ss->version, ss->version };
9658 if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
9659 continue;
9660 }
9661 for (i = 0; i + 2 < suite_length; i += 3) {
9662 PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9663 if (suite_i == suite->cipher_suite) {
9664 ss->ssl3.hs.cipher_suite = suite_i;
9665 rv = ssl3_SetupCipherSuite(ss, PR_TRUE);
9666 if (rv != SECSuccess) {
9667 desc = internal_error;
9668 errCode = PORT_GetError();
9669 goto alert_loser;
9670 }
9671 goto suite_found;
9672 }
9673 }
9674 }
9675 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
9676 goto alert_loser;
9677
9678 suite_found:
9679
9680 /* If the ClientHello version is less than our maximum version, check for a
9681 * TLS_FALLBACK_SCSV and reject the connection if found. */
9682 if (ss->vrange.max > ss->clientHelloVersion) {
9683 for (i = 0; i + 2 < suite_length; i += 3) {
9684 PRUint16 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9685 if (suite_i == TLS_FALLBACK_SCSV) {
9686 desc = inappropriate_fallback;
9687 errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
9688 goto alert_loser;
9689 }
9690 }
9691 }
9692
9693 /* Look for the SCSV, and if found, treat it just like an empty RI
9694 * extension by processing a local copy of an empty RI extension.
9695 */
9696 for (i = 0; i + 2 < suite_length; i += 3) {
9697 PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9698 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
9699 PRUint8 *b2 = (PRUint8 *)emptyRIext;
9700 PRUint32 L2 = sizeof emptyRIext;
9701 (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
9702 break;
9703 }
9704 }
9705
9706 if (ss->opt.requireSafeNegotiation &&
9707 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9708 desc = handshake_failure;
9709 errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
9710 goto alert_loser;
9711 }
9712
9713 rv = ssl3_SelectServerCert(ss);
9714 if (rv != SECSuccess) {
9715 errCode = PORT_GetError();
9716 desc = handshake_failure;
9717 goto alert_loser;
9718 }
9719
9720 /* we don't even search for a cache hit here. It's just a miss. */
9721 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
9722 sid = ssl3_NewSessionID(ss, PR_TRUE);
9723 if (sid == NULL) {
9724 errCode = PORT_GetError();
9725 goto loser; /* memory error is set. */
9726 }
9727 ss->sec.ci.sid = sid;
9728 /* do not worry about memory leak of sid since it now belongs to ci */
9729
9730 /* We have to update the handshake hashes before we can send stuff */
9731 rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
9732 if (rv != SECSuccess) {
9733 errCode = PORT_GetError();
9734 goto loser;
9735 }
9736
9737 ssl_GetXmitBufLock(ss);
9738 rv = ssl3_SendServerHelloSequence(ss);
9739 ssl_ReleaseXmitBufLock(ss);
9740 if (rv != SECSuccess) {
9741 errCode = PORT_GetError();
9742 goto loser;
9743 }
9744
9745 ssl_ReleaseSSL3HandshakeLock(ss);
9746 return SECSuccess;
9747
9748 alert_loser:
9749 SSL3_SendAlert(ss, alert_fatal, desc);
9750 loser:
9751 ssl_ReleaseSSL3HandshakeLock(ss);
9752 PORT_SetError(errCode);
9753 return SECFailure;
9754 }
9755
9756 SECStatus
ssl_ConstructServerHello(sslSocket * ss,PRBool helloRetry,const sslBuffer * extensionBuf,sslBuffer * messageBuf)9757 ssl_ConstructServerHello(sslSocket *ss, PRBool helloRetry,
9758 const sslBuffer *extensionBuf, sslBuffer *messageBuf)
9759 {
9760 SECStatus rv;
9761 SSL3ProtocolVersion version;
9762 sslSessionID *sid = ss->sec.ci.sid;
9763 const PRUint8 *random;
9764
9765 version = PR_MIN(ss->version, SSL_LIBRARY_VERSION_TLS_1_2);
9766 if (IS_DTLS(ss)) {
9767 version = dtls_TLSVersionToDTLSVersion(version);
9768 }
9769 rv = sslBuffer_AppendNumber(messageBuf, version, 2);
9770 if (rv != SECSuccess) {
9771 return SECFailure;
9772 }
9773
9774 if (helloRetry) {
9775 random = ssl_hello_retry_random;
9776 } else {
9777 rv = ssl_GenerateServerRandom(ss);
9778 if (rv != SECSuccess) {
9779 return SECFailure;
9780 }
9781 random = ss->ssl3.hs.server_random;
9782 }
9783 rv = sslBuffer_Append(messageBuf, random, SSL3_RANDOM_LENGTH);
9784 if (rv != SECSuccess) {
9785 return SECFailure;
9786 }
9787
9788 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
9789 if (sid) {
9790 rv = sslBuffer_AppendVariable(messageBuf, sid->u.ssl3.sessionID,
9791 sid->u.ssl3.sessionIDLength, 1);
9792 } else {
9793 rv = sslBuffer_AppendNumber(messageBuf, 0, 1);
9794 }
9795 } else {
9796 rv = sslBuffer_AppendVariable(messageBuf, ss->ssl3.hs.fakeSid.data,
9797 ss->ssl3.hs.fakeSid.len, 1);
9798 }
9799 if (rv != SECSuccess) {
9800 return SECFailure;
9801 }
9802
9803 rv = sslBuffer_AppendNumber(messageBuf, ss->ssl3.hs.cipher_suite, 2);
9804 if (rv != SECSuccess) {
9805 return SECFailure;
9806 }
9807 rv = sslBuffer_AppendNumber(messageBuf, ssl_compression_null, 1);
9808 if (rv != SECSuccess) {
9809 return SECFailure;
9810 }
9811 if (SSL_BUFFER_LEN(extensionBuf)) {
9812 rv = sslBuffer_AppendBufferVariable(messageBuf, extensionBuf, 2);
9813 if (rv != SECSuccess) {
9814 return SECFailure;
9815 }
9816 }
9817
9818 if (!helloRetry && ssl3_ExtensionNegotiated(ss, ssl_tls13_ech_is_inner_xtn)) {
9819 /* Signal ECH acceptance if we handled handled both CHOuter/CHInner (i.e.
9820 * in shared mode), or if we received a CHInner in split/backend mode. */
9821 if (ss->ssl3.hs.echAccepted || ss->opt.enableTls13BackendEch) {
9822 return tls13_WriteServerEchSignal(ss, SSL_BUFFER_BASE(messageBuf),
9823 SSL_BUFFER_LEN(messageBuf));
9824 }
9825 }
9826
9827 return SECSuccess;
9828 }
9829
9830 /* The negotiated version number has been already placed in ss->version.
9831 **
9832 ** Called from: ssl3_HandleClientHello (resuming session),
9833 ** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session),
9834 ** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
9835 */
9836 SECStatus
ssl3_SendServerHello(sslSocket * ss)9837 ssl3_SendServerHello(sslSocket *ss)
9838 {
9839 SECStatus rv;
9840 sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
9841 sslBuffer messageBuf = SSL_BUFFER_EMPTY;
9842
9843 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
9844 ss->fd));
9845
9846 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9847 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9848
9849 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
9850 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
9851 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
9852 return SECFailure;
9853 }
9854
9855 rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_server_hello);
9856 if (rv != SECSuccess) {
9857 goto loser;
9858 }
9859
9860 rv = ssl_ConstructServerHello(ss, PR_FALSE, &extensionBuf, &messageBuf);
9861 if (rv != SECSuccess) {
9862 goto loser;
9863 }
9864
9865 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello,
9866 SSL_BUFFER_LEN(&messageBuf));
9867 if (rv != SECSuccess) {
9868 goto loser; /* err set by AppendHandshake. */
9869 }
9870
9871 rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&messageBuf),
9872 SSL_BUFFER_LEN(&messageBuf));
9873 if (rv != SECSuccess) {
9874 goto loser; /* err set by AppendHandshake. */
9875 }
9876
9877 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
9878 rv = ssl3_SetupBothPendingCipherSpecs(ss);
9879 if (rv != SECSuccess) {
9880 goto loser; /* err set */
9881 }
9882 }
9883
9884 sslBuffer_Clear(&extensionBuf);
9885 sslBuffer_Clear(&messageBuf);
9886 return SECSuccess;
9887
9888 loser:
9889 sslBuffer_Clear(&extensionBuf);
9890 sslBuffer_Clear(&messageBuf);
9891 return SECFailure;
9892 }
9893
9894 SECStatus
ssl_CreateDHEKeyPair(const sslNamedGroupDef * groupDef,const ssl3DHParams * params,sslEphemeralKeyPair ** keyPair)9895 ssl_CreateDHEKeyPair(const sslNamedGroupDef *groupDef,
9896 const ssl3DHParams *params,
9897 sslEphemeralKeyPair **keyPair)
9898 {
9899 SECKEYDHParams dhParam;
9900 SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */
9901 SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */
9902 sslEphemeralKeyPair *pair;
9903
9904 dhParam.prime.data = params->prime.data;
9905 dhParam.prime.len = params->prime.len;
9906 dhParam.base.data = params->base.data;
9907 dhParam.base.len = params->base.len;
9908
9909 PRINT_BUF(60, (NULL, "Server DH p", dhParam.prime.data,
9910 dhParam.prime.len));
9911 PRINT_BUF(60, (NULL, "Server DH g", dhParam.base.data,
9912 dhParam.base.len));
9913
9914 /* Generate ephemeral DH keypair */
9915 privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
9916 if (!privKey || !pubKey) {
9917 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
9918 return SECFailure;
9919 }
9920
9921 pair = ssl_NewEphemeralKeyPair(groupDef, privKey, pubKey);
9922 if (!pair) {
9923 SECKEY_DestroyPrivateKey(privKey);
9924 SECKEY_DestroyPublicKey(pubKey);
9925
9926 return SECFailure;
9927 }
9928
9929 *keyPair = pair;
9930 return SECSuccess;
9931 }
9932
9933 static SECStatus
ssl3_SendDHServerKeyExchange(sslSocket * ss)9934 ssl3_SendDHServerKeyExchange(sslSocket *ss)
9935 {
9936 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
9937 SECStatus rv = SECFailure;
9938 int length;
9939 SECItem signed_hash = { siBuffer, NULL, 0 };
9940 SSL3Hashes hashes;
9941 SSLHashType hashAlg;
9942
9943 const ssl3DHParams *params;
9944 sslEphemeralKeyPair *keyPair;
9945 SECKEYPublicKey *pubKey;
9946 SECKEYPrivateKey *certPrivateKey;
9947 const sslNamedGroupDef *groupDef;
9948 /* Do this on the heap, this could be over 2k long. */
9949 sslBuffer dhBuf = SSL_BUFFER_EMPTY;
9950
9951 if (kea_def->kea != kea_dhe_dss && kea_def->kea != kea_dhe_rsa) {
9952 /* TODO: Support DH_anon. It might be sufficient to drop the signature.
9953 See bug 1170510. */
9954 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9955 return SECFailure;
9956 }
9957
9958 rv = ssl_SelectDHEGroup(ss, &groupDef);
9959 if (rv == SECFailure) {
9960 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
9961 return SECFailure;
9962 }
9963 ss->sec.keaGroup = groupDef;
9964
9965 params = ssl_GetDHEParams(groupDef);
9966 rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
9967 if (rv == SECFailure) {
9968 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
9969 return SECFailure;
9970 }
9971 PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs);
9972
9973 if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
9974 hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
9975 } else {
9976 /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
9977 hashAlg = ssl_hash_none;
9978 }
9979
9980 pubKey = keyPair->keys->pubKey;
9981 PRINT_BUF(50, (ss, "DH public value:",
9982 pubKey->u.dh.publicValue.data,
9983 pubKey->u.dh.publicValue.len));
9984 rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
9985 pubKey->u.dh.prime,
9986 pubKey->u.dh.base,
9987 pubKey->u.dh.publicValue,
9988 PR_TRUE /* padY */);
9989 if (rv != SECSuccess) {
9990 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9991 goto loser;
9992 }
9993
9994 certPrivateKey = ss->sec.serverCert->serverKeyPair->privKey;
9995 rv = ssl3_SignHashes(ss, &hashes, certPrivateKey, &signed_hash);
9996 if (rv != SECSuccess) {
9997 goto loser; /* ssl3_SignHashes has set err. */
9998 }
9999
10000 length = 2 + pubKey->u.dh.prime.len +
10001 2 + pubKey->u.dh.base.len +
10002 2 + pubKey->u.dh.prime.len +
10003 2 + signed_hash.len;
10004
10005 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
10006 length += 2;
10007 }
10008
10009 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_key_exchange, length);
10010 if (rv != SECSuccess) {
10011 goto loser; /* err set by AppendHandshake. */
10012 }
10013
10014 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.prime.data,
10015 pubKey->u.dh.prime.len, 2);
10016 if (rv != SECSuccess) {
10017 goto loser; /* err set by AppendHandshake. */
10018 }
10019
10020 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.base.data,
10021 pubKey->u.dh.base.len, 2);
10022 if (rv != SECSuccess) {
10023 goto loser; /* err set by AppendHandshake. */
10024 }
10025
10026 rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE);
10027 if (rv != SECSuccess) {
10028 goto loser; /* err set by AppendPaddedDHKeyShare. */
10029 }
10030 rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
10031 if (rv != SECSuccess) {
10032 goto loser; /* err set by AppendHandshake. */
10033 }
10034
10035 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
10036 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
10037 if (rv != SECSuccess) {
10038 goto loser; /* err set by AppendHandshake. */
10039 }
10040 }
10041
10042 rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
10043 signed_hash.len, 2);
10044 if (rv != SECSuccess) {
10045 goto loser; /* err set by AppendHandshake. */
10046 }
10047
10048 sslBuffer_Clear(&dhBuf);
10049 PORT_Free(signed_hash.data);
10050 return SECSuccess;
10051
10052 loser:
10053 if (signed_hash.data)
10054 PORT_Free(signed_hash.data);
10055 sslBuffer_Clear(&dhBuf);
10056 return SECFailure;
10057 }
10058
10059 static SECStatus
ssl3_SendServerKeyExchange(sslSocket * ss)10060 ssl3_SendServerKeyExchange(sslSocket *ss)
10061 {
10062 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
10063
10064 SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
10065 SSL_GETPID(), ss->fd));
10066
10067 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10068 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10069
10070 switch (kea_def->exchKeyType) {
10071 case ssl_kea_dh: {
10072 return ssl3_SendDHServerKeyExchange(ss);
10073 }
10074
10075 case ssl_kea_ecdh: {
10076 return ssl3_SendECDHServerKeyExchange(ss);
10077 }
10078
10079 case ssl_kea_rsa:
10080 case ssl_kea_null:
10081 default:
10082 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10083 break;
10084 }
10085
10086 return SECFailure;
10087 }
10088
10089 SECStatus
ssl3_EncodeSigAlgs(const sslSocket * ss,PRUint16 minVersion,PRBool forCert,sslBuffer * buf)10090 ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool forCert,
10091 sslBuffer *buf)
10092 {
10093 SSLSignatureScheme filtered[MAX_SIGNATURE_SCHEMES] = { 0 };
10094 unsigned int filteredCount = 0;
10095
10096 SECStatus rv = ssl3_FilterSigAlgs(ss, minVersion, PR_FALSE, forCert,
10097 PR_ARRAY_SIZE(filtered),
10098 filtered, &filteredCount);
10099 if (rv != SECSuccess) {
10100 return SECFailure;
10101 }
10102 return ssl3_EncodeFilteredSigAlgs(ss, filtered, filteredCount, buf);
10103 }
10104
10105 SECStatus
ssl3_EncodeFilteredSigAlgs(const sslSocket * ss,const SSLSignatureScheme * schemes,PRUint32 numSchemes,sslBuffer * buf)10106 ssl3_EncodeFilteredSigAlgs(const sslSocket *ss, const SSLSignatureScheme *schemes,
10107 PRUint32 numSchemes, sslBuffer *buf)
10108 {
10109 if (!numSchemes) {
10110 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
10111 return SECFailure;
10112 }
10113
10114 unsigned int lengthOffset;
10115 SECStatus rv;
10116
10117 rv = sslBuffer_Skip(buf, 2, &lengthOffset);
10118 if (rv != SECSuccess) {
10119 return SECFailure;
10120 }
10121
10122 for (unsigned int i = 0; i < numSchemes; ++i) {
10123 rv = sslBuffer_AppendNumber(buf, schemes[i], 2);
10124 if (rv != SECSuccess) {
10125 return SECFailure;
10126 }
10127 }
10128 return sslBuffer_InsertLength(buf, lengthOffset, 2);
10129 }
10130
10131 /*
10132 * In TLS 1.3 we are permitted to advertise support for PKCS#1
10133 * schemes. This doesn't affect the signatures in TLS itself, just
10134 * those on certificates. Not advertising PKCS#1 signatures creates a
10135 * serious compatibility risk as it excludes many certificate chains
10136 * that include PKCS#1. Hence, forCert is used to enable advertising
10137 * PKCS#1 support. Note that we include these in signature_algorithms
10138 * because we don't yet support signature_algorithms_cert. TLS 1.3
10139 * requires that PKCS#1 schemes are placed last in the list if they
10140 * are present. This sorting can be removed once we support
10141 * signature_algorithms_cert.
10142 */
10143 SECStatus
ssl3_FilterSigAlgs(const sslSocket * ss,PRUint16 minVersion,PRBool disableRsae,PRBool forCert,unsigned int maxSchemes,SSLSignatureScheme * filteredSchemes,unsigned int * numFilteredSchemes)10144 ssl3_FilterSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool disableRsae,
10145 PRBool forCert,
10146 unsigned int maxSchemes, SSLSignatureScheme *filteredSchemes,
10147 unsigned int *numFilteredSchemes)
10148 {
10149 PORT_Assert(filteredSchemes);
10150 PORT_Assert(numFilteredSchemes);
10151 PORT_Assert(maxSchemes >= ss->ssl3.signatureSchemeCount);
10152 if (maxSchemes < ss->ssl3.signatureSchemeCount) {
10153 return SECFailure;
10154 }
10155
10156 *numFilteredSchemes = 0;
10157 PRBool allowUnsortedPkcs1 = forCert && minVersion < SSL_LIBRARY_VERSION_TLS_1_3;
10158 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
10159 if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
10160 continue;
10161 }
10162 if (ssl_SignatureSchemeAccepted(minVersion,
10163 ss->ssl3.signatureSchemes[i],
10164 allowUnsortedPkcs1)) {
10165 filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
10166 }
10167 }
10168 if (forCert && !allowUnsortedPkcs1) {
10169 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
10170 if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
10171 continue;
10172 }
10173 if (!ssl_SignatureSchemeAccepted(minVersion,
10174 ss->ssl3.signatureSchemes[i],
10175 PR_FALSE) &&
10176 ssl_SignatureSchemeAccepted(minVersion,
10177 ss->ssl3.signatureSchemes[i],
10178 PR_TRUE)) {
10179 filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
10180 }
10181 }
10182 }
10183 return SECSuccess;
10184 }
10185
10186 static SECStatus
ssl3_SendCertificateRequest(sslSocket * ss)10187 ssl3_SendCertificateRequest(sslSocket *ss)
10188 {
10189 PRBool isTLS12;
10190 const PRUint8 *certTypes;
10191 SECStatus rv;
10192 PRUint32 length;
10193 const SECItem *names;
10194 unsigned int calen;
10195 unsigned int nnames;
10196 const SECItem *name;
10197 unsigned int i;
10198 int certTypesLength;
10199 PRUint8 sigAlgs[2 + MAX_SIGNATURE_SCHEMES * 2];
10200 sslBuffer sigAlgsBuf = SSL_BUFFER(sigAlgs);
10201
10202 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
10203 SSL_GETPID(), ss->fd));
10204
10205 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10206 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10207
10208 isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
10209
10210 rv = ssl_GetCertificateRequestCAs(ss, &calen, &names, &nnames);
10211 if (rv != SECSuccess) {
10212 return rv;
10213 }
10214 certTypes = certificate_types;
10215 certTypesLength = sizeof certificate_types;
10216
10217 length = 1 + certTypesLength + 2 + calen;
10218 if (isTLS12) {
10219 rv = ssl3_EncodeSigAlgs(ss, ss->version, PR_TRUE /* forCert */, &sigAlgsBuf);
10220 if (rv != SECSuccess) {
10221 return rv;
10222 }
10223 length += SSL_BUFFER_LEN(&sigAlgsBuf);
10224 }
10225
10226 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request, length);
10227 if (rv != SECSuccess) {
10228 return rv; /* err set by AppendHandshake. */
10229 }
10230 rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
10231 if (rv != SECSuccess) {
10232 return rv; /* err set by AppendHandshake. */
10233 }
10234 if (isTLS12) {
10235 rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&sigAlgsBuf),
10236 SSL_BUFFER_LEN(&sigAlgsBuf));
10237 if (rv != SECSuccess) {
10238 return rv; /* err set by AppendHandshake. */
10239 }
10240 }
10241 rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
10242 if (rv != SECSuccess) {
10243 return rv; /* err set by AppendHandshake. */
10244 }
10245 for (i = 0, name = names; i < nnames; i++, name++) {
10246 rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
10247 if (rv != SECSuccess) {
10248 return rv; /* err set by AppendHandshake. */
10249 }
10250 }
10251
10252 return SECSuccess;
10253 }
10254
10255 static SECStatus
ssl3_SendServerHelloDone(sslSocket * ss)10256 ssl3_SendServerHelloDone(sslSocket *ss)
10257 {
10258 SECStatus rv;
10259
10260 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
10261 SSL_GETPID(), ss->fd));
10262
10263 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10264 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10265
10266 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello_done, 0);
10267 if (rv != SECSuccess) {
10268 return rv; /* err set by AppendHandshake. */
10269 }
10270 rv = ssl3_FlushHandshake(ss, 0);
10271 if (rv != SECSuccess) {
10272 return rv; /* error code set by ssl3_FlushHandshake */
10273 }
10274 return SECSuccess;
10275 }
10276
10277 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10278 * a complete ssl3 Certificate Verify message
10279 * Caller must hold Handshake and RecvBuf locks.
10280 */
10281 static SECStatus
ssl3_HandleCertificateVerify(sslSocket * ss,PRUint8 * b,PRUint32 length)10282 ssl3_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
10283 {
10284 SECItem signed_hash = { siBuffer, NULL, 0 };
10285 SECStatus rv;
10286 int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
10287 SSL3AlertDescription desc = handshake_failure;
10288 PRBool isTLS;
10289 SSLSignatureScheme sigScheme;
10290 SSL3Hashes hashes;
10291 const PRUint8 *savedMsg = b;
10292 const PRUint32 savedLen = length;
10293
10294 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
10295 SSL_GETPID(), ss->fd));
10296 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10297 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10298
10299 if (ss->ssl3.hs.ws != wait_cert_verify) {
10300 desc = unexpected_message;
10301 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
10302 goto alert_loser;
10303 }
10304
10305 /* TLS 1.3 is handled by tls13_HandleCertificateVerify */
10306 PORT_Assert(ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2);
10307
10308 if (ss->ssl3.prSpec->version == SSL_LIBRARY_VERSION_TLS_1_2) {
10309 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_record);
10310 rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
10311 if (rv != SECSuccess) {
10312 if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
10313 errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
10314 }
10315 goto loser; /* alert already sent */
10316 }
10317 rv = ssl_CheckSignatureSchemeConsistency(
10318 ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo);
10319 if (rv != SECSuccess) {
10320 errCode = PORT_GetError();
10321 desc = illegal_parameter;
10322 goto alert_loser;
10323 }
10324
10325 rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
10326 ss->ssl3.hs.messages.len,
10327 ssl_SignatureSchemeToHashType(sigScheme),
10328 &hashes);
10329 } else {
10330 PORT_Assert(ss->ssl3.hs.hashType != handshake_hash_record);
10331 sigScheme = ssl_sig_none;
10332 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.prSpec, &hashes, 0);
10333 }
10334
10335 if (rv != SECSuccess) {
10336 errCode = SSL_ERROR_DIGEST_FAILURE;
10337 desc = decrypt_error;
10338 goto alert_loser;
10339 }
10340
10341 rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
10342 if (rv != SECSuccess) {
10343 goto loser; /* malformed. */
10344 }
10345
10346 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
10347
10348 /* XXX verify that the key & kea match */
10349 rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signed_hash);
10350 if (rv != SECSuccess) {
10351 errCode = PORT_GetError();
10352 desc = isTLS ? decrypt_error : handshake_failure;
10353 goto alert_loser;
10354 }
10355
10356 signed_hash.data = NULL;
10357
10358 if (length != 0) {
10359 desc = isTLS ? decode_error : illegal_parameter;
10360 goto alert_loser; /* malformed */
10361 }
10362
10363 rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify,
10364 savedMsg, savedLen);
10365 if (rv != SECSuccess) {
10366 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10367 return rv;
10368 }
10369
10370 ss->ssl3.hs.ws = wait_change_cipher;
10371 return SECSuccess;
10372
10373 alert_loser:
10374 SSL3_SendAlert(ss, alert_fatal, desc);
10375 loser:
10376 PORT_SetError(errCode);
10377 return SECFailure;
10378 }
10379
10380 /* find a slot that is able to generate a PMS and wrap it with RSA.
10381 * Then generate and return the PMS.
10382 * If the serverKeySlot parameter is non-null, this function will use
10383 * that slot to do the job, otherwise it will find a slot.
10384 *
10385 * Called from ssl3_DeriveConnectionKeys() (above)
10386 * ssl3_SendRSAClientKeyExchange() (above)
10387 * ssl3_HandleRSAClientKeyExchange() (below)
10388 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
10389 */
10390 static PK11SymKey *
ssl3_GenerateRSAPMS(sslSocket * ss,ssl3CipherSpec * spec,PK11SlotInfo * serverKeySlot)10391 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
10392 PK11SlotInfo *serverKeySlot)
10393 {
10394 PK11SymKey *pms = NULL;
10395 PK11SlotInfo *slot = serverKeySlot;
10396 void *pwArg = ss->pkcs11PinArg;
10397 SECItem param;
10398 CK_VERSION version;
10399 CK_MECHANISM_TYPE mechanism_array[3];
10400
10401 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10402
10403 if (slot == NULL) {
10404 SSLCipherAlgorithm calg;
10405 /* The specReadLock would suffice here, but we cannot assert on
10406 ** read locks. Also, all the callers who call with a non-null
10407 ** slot already hold the SpecWriteLock.
10408 */
10409 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
10410 PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
10411
10412 calg = spec->cipherDef->calg;
10413
10414 /* First get an appropriate slot. */
10415 mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
10416 mechanism_array[1] = CKM_RSA_PKCS;
10417 mechanism_array[2] = ssl3_Alg2Mech(calg);
10418
10419 slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
10420 if (slot == NULL) {
10421 /* can't find a slot with all three, find a slot with the minimum */
10422 slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
10423 if (slot == NULL) {
10424 PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
10425 return pms; /* which is NULL */
10426 }
10427 }
10428 }
10429
10430 /* Generate the pre-master secret ... */
10431 if (IS_DTLS(ss)) {
10432 SSL3ProtocolVersion temp;
10433
10434 temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
10435 version.major = MSB(temp);
10436 version.minor = LSB(temp);
10437 } else {
10438 version.major = MSB(ss->clientHelloVersion);
10439 version.minor = LSB(ss->clientHelloVersion);
10440 }
10441
10442 param.data = (unsigned char *)&version;
10443 param.len = sizeof version;
10444
10445 pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, ¶m, 0, pwArg);
10446 if (!serverKeySlot)
10447 PK11_FreeSlot(slot);
10448 if (pms == NULL) {
10449 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10450 }
10451 return pms;
10452 }
10453
10454 static void
ssl3_CSwapPK11SymKey(PK11SymKey ** x,PK11SymKey ** y,PRBool c)10455 ssl3_CSwapPK11SymKey(PK11SymKey **x, PK11SymKey **y, PRBool c)
10456 {
10457 uintptr_t mask = (uintptr_t)c;
10458 unsigned int i;
10459 for (i = 1; i < sizeof(uintptr_t) * 8; i <<= 1) {
10460 mask |= mask << i;
10461 }
10462 uintptr_t x_ptr = (uintptr_t)*x;
10463 uintptr_t y_ptr = (uintptr_t)*y;
10464 uintptr_t tmp = (x_ptr ^ y_ptr) & mask;
10465 x_ptr = x_ptr ^ tmp;
10466 y_ptr = y_ptr ^ tmp;
10467 *x = (PK11SymKey *)x_ptr;
10468 *y = (PK11SymKey *)y_ptr;
10469 }
10470
10471 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
10472 * return any indication of failure of the Client Key Exchange message,
10473 * where that failure is caused by the content of the client's message.
10474 * This function must not return SECFailure for any reason that is directly
10475 * or indirectly caused by the content of the client's encrypted PMS.
10476 * We must not send an alert and also not drop the connection.
10477 * Instead, we generate a random PMS. This will cause a failure
10478 * in the processing the finished message, which is exactly where
10479 * the failure must occur.
10480 *
10481 * Called from ssl3_HandleClientKeyExchange
10482 */
10483 static SECStatus
ssl3_HandleRSAClientKeyExchange(sslSocket * ss,PRUint8 * b,PRUint32 length,sslKeyPair * serverKeyPair)10484 ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
10485 PRUint8 *b,
10486 PRUint32 length,
10487 sslKeyPair *serverKeyPair)
10488 {
10489 SECStatus rv;
10490 SECItem enc_pms;
10491 PK11SymKey *pms = NULL;
10492 PK11SymKey *fauxPms = NULL;
10493 PK11SlotInfo *slot = NULL;
10494
10495 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10496 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10497 PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
10498
10499 enc_pms.data = b;
10500 enc_pms.len = length;
10501
10502 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
10503 PRUint32 kLen;
10504 rv = ssl3_ConsumeHandshakeNumber(ss, &kLen, 2, &enc_pms.data, &enc_pms.len);
10505 if (rv != SECSuccess) {
10506 PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10507 return SECFailure;
10508 }
10509 if ((unsigned)kLen < enc_pms.len) {
10510 enc_pms.len = kLen;
10511 }
10512 }
10513
10514 /*
10515 * Get as close to algorithm 2 from RFC 5246; Section 7.4.7.1
10516 * as we can within the constraints of the PKCS#11 interface.
10517 *
10518 * 1. Unconditionally generate a bogus PMS (what RFC 5246
10519 * calls R).
10520 * 2. Attempt the RSA decryption to recover the PMS (what
10521 * RFC 5246 calls M).
10522 * 3. Set PMS = (M == NULL) ? R : M
10523 * 4. Use ssl3_ComputeMasterSecret(PMS) to attempt to derive
10524 * the MS from PMS. This includes performing the version
10525 * check and length check.
10526 * 5. If either the initial RSA decryption failed or
10527 * ssl3_ComputeMasterSecret(PMS) failed, then discard
10528 * M and set PMS = R. Else, discard R and set PMS = M.
10529 *
10530 * We do two derivations here because we can't rely on having
10531 * a function that only performs the PMS version and length
10532 * check. The only redundant cost is that this runs the PRF,
10533 * which isn't necessary here.
10534 */
10535
10536 /* Generate the bogus PMS (R) */
10537 slot = PK11_GetSlotFromPrivateKey(serverKeyPair->privKey);
10538 if (!slot) {
10539 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10540 return SECFailure;
10541 }
10542
10543 if (!PK11_DoesMechanism(slot, CKM_SSL3_MASTER_KEY_DERIVE)) {
10544 PK11_FreeSlot(slot);
10545 slot = PK11_GetBestSlot(CKM_SSL3_MASTER_KEY_DERIVE, NULL);
10546 if (!slot) {
10547 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10548 return SECFailure;
10549 }
10550 }
10551
10552 ssl_GetSpecWriteLock(ss);
10553 fauxPms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
10554 ssl_ReleaseSpecWriteLock(ss);
10555 PK11_FreeSlot(slot);
10556
10557 if (fauxPms == NULL) {
10558 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10559 return SECFailure;
10560 }
10561
10562 /*
10563 * unwrap pms out of the incoming buffer
10564 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
10565 * the unwrap. Rather, it is the mechanism with which the
10566 * unwrapped pms will be used.
10567 */
10568 pms = PK11_PubUnwrapSymKey(serverKeyPair->privKey, &enc_pms,
10569 CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
10570 /* Temporarily use the PMS if unwrapping the real PMS fails. */
10571 ssl3_CSwapPK11SymKey(&pms, &fauxPms, pms == NULL);
10572
10573 /* Attempt to derive the MS from the PMS. This is the only way to
10574 * check the version field in the RSA PMS. If this fails, we
10575 * then use the faux PMS in place of the PMS. Note that this
10576 * operation should never fail if we are using the faux PMS
10577 * since it is correctly formatted. */
10578 rv = ssl3_ComputeMasterSecret(ss, pms, NULL);
10579
10580 /* If we succeeded, then select the true PMS, else select the FPMS. */
10581 ssl3_CSwapPK11SymKey(&pms, &fauxPms, (rv != SECSuccess) & (fauxPms != NULL));
10582
10583 /* This step will derive the MS from the PMS, among other things. */
10584 rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
10585
10586 /* Clear both PMS. */
10587 PK11_FreeSymKey(pms);
10588 PK11_FreeSymKey(fauxPms);
10589
10590 if (rv != SECSuccess) {
10591 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10592 return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
10593 }
10594
10595 return SECSuccess;
10596 }
10597
10598 static SECStatus
ssl3_HandleDHClientKeyExchange(sslSocket * ss,PRUint8 * b,PRUint32 length,sslKeyPair * serverKeyPair)10599 ssl3_HandleDHClientKeyExchange(sslSocket *ss,
10600 PRUint8 *b,
10601 PRUint32 length,
10602 sslKeyPair *serverKeyPair)
10603 {
10604 PK11SymKey *pms;
10605 SECStatus rv;
10606 SECKEYPublicKey clntPubKey;
10607 CK_MECHANISM_TYPE target;
10608 PRBool isTLS;
10609
10610 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10611 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10612
10613 clntPubKey.keyType = dhKey;
10614 clntPubKey.u.dh.prime.len = serverKeyPair->pubKey->u.dh.prime.len;
10615 clntPubKey.u.dh.prime.data = serverKeyPair->pubKey->u.dh.prime.data;
10616 clntPubKey.u.dh.base.len = serverKeyPair->pubKey->u.dh.base.len;
10617 clntPubKey.u.dh.base.data = serverKeyPair->pubKey->u.dh.base.data;
10618
10619 rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.dh.publicValue,
10620 2, &b, &length);
10621 if (rv != SECSuccess) {
10622 return SECFailure;
10623 }
10624
10625 if (!ssl_IsValidDHEShare(&serverKeyPair->pubKey->u.dh.prime,
10626 &clntPubKey.u.dh.publicValue)) {
10627 PORT_SetError(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE);
10628 return SECFailure;
10629 }
10630
10631 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
10632
10633 if (isTLS)
10634 target = CKM_TLS_MASTER_KEY_DERIVE_DH;
10635 else
10636 target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
10637
10638 /* Determine the PMS */
10639 pms = PK11_PubDerive(serverKeyPair->privKey, &clntPubKey, PR_FALSE, NULL, NULL,
10640 CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
10641 if (pms == NULL) {
10642 ssl_FreeEphemeralKeyPairs(ss);
10643 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10644 return SECFailure;
10645 }
10646
10647 rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
10648 PK11_FreeSymKey(pms);
10649 ssl_FreeEphemeralKeyPairs(ss);
10650 return rv;
10651 }
10652
10653 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10654 * a complete ssl3 ClientKeyExchange message from the remote client
10655 * Caller must hold Handshake and RecvBuf locks.
10656 */
10657 static SECStatus
ssl3_HandleClientKeyExchange(sslSocket * ss,PRUint8 * b,PRUint32 length)10658 ssl3_HandleClientKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
10659 {
10660 sslKeyPair *serverKeyPair = NULL;
10661 SECStatus rv;
10662 const ssl3KEADef *kea_def;
10663
10664 SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
10665 SSL_GETPID(), ss->fd));
10666
10667 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10668 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10669
10670 if (ss->ssl3.hs.ws != wait_client_key) {
10671 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10672 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
10673 return SECFailure;
10674 }
10675
10676 kea_def = ss->ssl3.hs.kea_def;
10677
10678 if (kea_def->ephemeral) {
10679 sslEphemeralKeyPair *keyPair;
10680 /* There should be exactly one pair. */
10681 PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
10682 PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==
10683 PR_NEXT_LINK(&ss->ephemeralKeyPairs));
10684 keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs);
10685 serverKeyPair = keyPair->keys;
10686 ss->sec.keaKeyBits =
10687 SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
10688 } else {
10689 serverKeyPair = ss->sec.serverCert->serverKeyPair;
10690 ss->sec.keaKeyBits = ss->sec.serverCert->serverKeyBits;
10691 }
10692
10693 if (!serverKeyPair) {
10694 SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10695 PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
10696 return SECFailure;
10697 }
10698 PORT_Assert(serverKeyPair->pubKey);
10699 PORT_Assert(serverKeyPair->privKey);
10700
10701 ss->sec.keaType = kea_def->exchKeyType;
10702
10703 switch (kea_def->exchKeyType) {
10704 case ssl_kea_rsa:
10705 rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKeyPair);
10706 break;
10707
10708 case ssl_kea_dh:
10709 rv = ssl3_HandleDHClientKeyExchange(ss, b, length, serverKeyPair);
10710 break;
10711
10712 case ssl_kea_ecdh:
10713 rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, serverKeyPair);
10714 break;
10715
10716 default:
10717 (void)ssl3_HandshakeFailure(ss);
10718 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
10719 return SECFailure;
10720 }
10721 ssl_FreeEphemeralKeyPairs(ss);
10722 if (rv == SECSuccess) {
10723 ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
10724 } else {
10725 /* PORT_SetError has been called by all the Handle*ClientKeyExchange
10726 * functions above. However, not all error paths result in an alert, so
10727 * this ensures that the server knows about the error. Note that if an
10728 * alert was already sent, SSL3_SendAlert() is a noop. */
10729 PRErrorCode errCode = PORT_GetError();
10730 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10731 PORT_SetError(errCode);
10732 }
10733 return rv;
10734 }
10735
10736 /* This is TLS's equivalent of sending a no_certificate alert. */
10737 SECStatus
ssl3_SendEmptyCertificate(sslSocket * ss)10738 ssl3_SendEmptyCertificate(sslSocket *ss)
10739 {
10740 SECStatus rv;
10741 unsigned int len = 0;
10742 PRBool isTLS13 = PR_FALSE;
10743 const SECItem *context;
10744
10745 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
10746 PORT_Assert(ss->ssl3.hs.clientCertRequested);
10747 context = &ss->xtnData.certReqContext;
10748 len = context->len + 1;
10749 isTLS13 = PR_TRUE;
10750 }
10751
10752 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate, len + 3);
10753 if (rv != SECSuccess) {
10754 return rv;
10755 }
10756
10757 if (isTLS13) {
10758 rv = ssl3_AppendHandshakeVariable(ss, context->data, context->len, 1);
10759 if (rv != SECSuccess) {
10760 return rv;
10761 }
10762 }
10763
10764 return ssl3_AppendHandshakeNumber(ss, 0, 3);
10765 }
10766
10767 /*
10768 * NewSessionTicket
10769 * Called from ssl3_HandleFinished
10770 */
10771 static SECStatus
ssl3_SendNewSessionTicket(sslSocket * ss)10772 ssl3_SendNewSessionTicket(sslSocket *ss)
10773 {
10774 SECItem ticket = { 0, NULL, 0 };
10775 SECStatus rv;
10776 NewSessionTicket nticket = { 0 };
10777
10778 rv = ssl3_EncodeSessionTicket(ss, &nticket, NULL, 0,
10779 ss->ssl3.pwSpec->masterSecret, &ticket);
10780 if (rv != SECSuccess)
10781 goto loser;
10782
10783 /* Serialize the handshake message. Length =
10784 * lifetime (4) + ticket length (2) + ticket. */
10785 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
10786 4 + 2 + ticket.len);
10787 if (rv != SECSuccess)
10788 goto loser;
10789
10790 /* This is a fixed value. */
10791 rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
10792 if (rv != SECSuccess)
10793 goto loser;
10794
10795 /* Encode the ticket. */
10796 rv = ssl3_AppendHandshakeVariable(ss, ticket.data, ticket.len, 2);
10797 if (rv != SECSuccess)
10798 goto loser;
10799
10800 rv = SECSuccess;
10801
10802 loser:
10803 if (ticket.data) {
10804 SECITEM_FreeItem(&ticket, PR_FALSE);
10805 }
10806 return rv;
10807 }
10808
10809 static SECStatus
ssl3_HandleNewSessionTicket(sslSocket * ss,PRUint8 * b,PRUint32 length)10810 ssl3_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
10811 {
10812 SECStatus rv;
10813 SECItem ticketData;
10814 PRUint32 temp;
10815
10816 SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
10817 SSL_GETPID(), ss->fd));
10818
10819 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10820 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10821
10822 PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
10823 PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket);
10824
10825 if (ss->ssl3.hs.ws != wait_new_session_ticket) {
10826 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10827 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
10828 return SECFailure;
10829 }
10830
10831 /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid
10832 * until it has verified the server's Finished message." See the comment in
10833 * ssl3_FinishHandshake for more details.
10834 */
10835 ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(ss);
10836 if (length < 4) {
10837 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
10838 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
10839 return SECFailure;
10840 }
10841
10842 rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 4, &b, &length);
10843 if (rv != SECSuccess) {
10844 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
10845 return SECFailure;
10846 }
10847 ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = temp;
10848
10849 rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length);
10850 if (rv != SECSuccess || length != 0) {
10851 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
10852 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
10853 return SECFailure; /* malformed */
10854 }
10855 /* If the server sent a zero-length ticket, ignore it and keep the
10856 * existing ticket. */
10857 if (ticketData.len != 0) {
10858 rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket,
10859 &ticketData);
10860 if (rv != SECSuccess) {
10861 return rv;
10862 }
10863 ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE;
10864 }
10865
10866 ss->ssl3.hs.ws = wait_change_cipher;
10867 return SECSuccess;
10868 }
10869
10870 #ifdef NISCC_TEST
10871 static PRInt32 connNum = 0;
10872
10873 static SECStatus
get_fake_cert(SECItem * pCertItem,int * pIndex)10874 get_fake_cert(SECItem *pCertItem, int *pIndex)
10875 {
10876 PRFileDesc *cf;
10877 char *testdir;
10878 char *startat;
10879 char *stopat;
10880 const char *extension;
10881 int fileNum;
10882 PRInt32 numBytes = 0;
10883 PRStatus prStatus;
10884 PRFileInfo info;
10885 char cfn[100];
10886
10887 pCertItem->data = 0;
10888 if ((testdir = PR_GetEnvSecure("NISCC_TEST")) == NULL) {
10889 return SECSuccess;
10890 }
10891 *pIndex = (NULL != strstr(testdir, "root"));
10892 extension = (strstr(testdir, "simple") ? "" : ".der");
10893 fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1;
10894 if ((startat = PR_GetEnvSecure("START_AT")) != NULL) {
10895 fileNum += atoi(startat);
10896 }
10897 if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL &&
10898 fileNum >= atoi(stopat)) {
10899 *pIndex = -1;
10900 return SECSuccess;
10901 }
10902 sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension);
10903 cf = PR_Open(cfn, PR_RDONLY, 0);
10904 if (!cf) {
10905 goto loser;
10906 }
10907 prStatus = PR_GetOpenFileInfo(cf, &info);
10908 if (prStatus != PR_SUCCESS) {
10909 PR_Close(cf);
10910 goto loser;
10911 }
10912 pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
10913 if (pCertItem) {
10914 numBytes = PR_Read(cf, pCertItem->data, info.size);
10915 }
10916 PR_Close(cf);
10917 if (numBytes != info.size) {
10918 SECITEM_FreeItem(pCertItem, PR_FALSE);
10919 PORT_SetError(SEC_ERROR_IO);
10920 goto loser;
10921 }
10922 fprintf(stderr, "using %s\n", cfn);
10923 return SECSuccess;
10924
10925 loser:
10926 fprintf(stderr, "failed to use %s\n", cfn);
10927 *pIndex = -1;
10928 return SECFailure;
10929 }
10930 #endif
10931
10932 /*
10933 * Used by both client and server.
10934 * Called from HandleServerHelloDone and from SendServerHelloSequence.
10935 */
10936 static SECStatus
ssl3_SendCertificate(sslSocket * ss)10937 ssl3_SendCertificate(sslSocket *ss)
10938 {
10939 SECStatus rv;
10940 CERTCertificateList *certChain;
10941 int certChainLen = 0;
10942 int i;
10943 #ifdef NISCC_TEST
10944 SECItem fakeCert;
10945 int ndex = -1;
10946 #endif
10947 PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
10948 SECItem context = { siBuffer, NULL, 0 };
10949 unsigned int contextLen = 0;
10950
10951 SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
10952 SSL_GETPID(), ss->fd));
10953
10954 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10955 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10956
10957 if (ss->sec.localCert)
10958 CERT_DestroyCertificate(ss->sec.localCert);
10959 if (ss->sec.isServer) {
10960 /* A server certificate is selected in ssl3_HandleClientHello. */
10961 PORT_Assert(ss->sec.serverCert);
10962
10963 certChain = ss->sec.serverCert->serverCertChain;
10964 ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
10965 } else {
10966 certChain = ss->ssl3.clientCertChain;
10967 ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
10968 }
10969
10970 #ifdef NISCC_TEST
10971 rv = get_fake_cert(&fakeCert, &ndex);
10972 #endif
10973
10974 if (isTLS13) {
10975 contextLen = 1; /* Size of the context length */
10976 if (!ss->sec.isServer) {
10977 PORT_Assert(ss->ssl3.hs.clientCertRequested);
10978 context = ss->xtnData.certReqContext;
10979 contextLen += context.len;
10980 }
10981 }
10982 if (certChain) {
10983 for (i = 0; i < certChain->len; i++) {
10984 #ifdef NISCC_TEST
10985 if (fakeCert.len > 0 && i == ndex) {
10986 certChainLen += fakeCert.len + 3;
10987 } else {
10988 certChainLen += certChain->certs[i].len + 3;
10989 }
10990 #else
10991 certChainLen += certChain->certs[i].len + 3;
10992 #endif
10993 }
10994 }
10995
10996 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate,
10997 contextLen + certChainLen + 3);
10998 if (rv != SECSuccess) {
10999 return rv; /* err set by AppendHandshake. */
11000 }
11001
11002 if (isTLS13) {
11003 rv = ssl3_AppendHandshakeVariable(ss, context.data,
11004 context.len, 1);
11005 if (rv != SECSuccess) {
11006 return rv; /* err set by AppendHandshake. */
11007 }
11008 }
11009
11010 rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3);
11011 if (rv != SECSuccess) {
11012 return rv; /* err set by AppendHandshake. */
11013 }
11014 if (certChain) {
11015 for (i = 0; i < certChain->len; i++) {
11016 #ifdef NISCC_TEST
11017 if (fakeCert.len > 0 && i == ndex) {
11018 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
11019 fakeCert.len, 3);
11020 SECITEM_FreeItem(&fakeCert, PR_FALSE);
11021 } else {
11022 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
11023 certChain->certs[i].len, 3);
11024 }
11025 #else
11026 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
11027 certChain->certs[i].len, 3);
11028 #endif
11029 if (rv != SECSuccess) {
11030 return rv; /* err set by AppendHandshake. */
11031 }
11032 }
11033 }
11034
11035 return SECSuccess;
11036 }
11037
11038 /*
11039 * Used by server only.
11040 * single-stapling, send only a single cert status
11041 */
11042 SECStatus
ssl3_SendCertificateStatus(sslSocket * ss)11043 ssl3_SendCertificateStatus(sslSocket *ss)
11044 {
11045 SECStatus rv;
11046 int len = 0;
11047 SECItemArray *statusToSend = NULL;
11048 const sslServerCert *serverCert;
11049
11050 SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
11051 SSL_GETPID(), ss->fd));
11052
11053 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11054 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11055 PORT_Assert(ss->sec.isServer);
11056
11057 if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
11058 return SECSuccess;
11059
11060 /* Use certStatus based on the cert being used. */
11061 serverCert = ss->sec.serverCert;
11062 if (serverCert->certStatusArray && serverCert->certStatusArray->len) {
11063 statusToSend = serverCert->certStatusArray;
11064 }
11065 if (!statusToSend)
11066 return SECSuccess;
11067
11068 /* Use the array's first item only (single stapling) */
11069 len = 1 + statusToSend->items[0].len + 3;
11070
11071 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_status, len);
11072 if (rv != SECSuccess) {
11073 return rv; /* err set by AppendHandshake. */
11074 }
11075 rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
11076 if (rv != SECSuccess)
11077 return rv; /* err set by AppendHandshake. */
11078
11079 rv = ssl3_AppendHandshakeVariable(ss,
11080 statusToSend->items[0].data,
11081 statusToSend->items[0].len,
11082 3);
11083 if (rv != SECSuccess)
11084 return rv; /* err set by AppendHandshake. */
11085
11086 return SECSuccess;
11087 }
11088
11089 /* This is used to delete the CA certificates in the peer certificate chain
11090 * from the cert database after they've been validated.
11091 */
11092 void
ssl3_CleanupPeerCerts(sslSocket * ss)11093 ssl3_CleanupPeerCerts(sslSocket *ss)
11094 {
11095 PLArenaPool *arena = ss->ssl3.peerCertArena;
11096 ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
11097
11098 for (; certs; certs = certs->next) {
11099 CERT_DestroyCertificate(certs->cert);
11100 }
11101 if (arena)
11102 PORT_FreeArena(arena, PR_FALSE);
11103 ss->ssl3.peerCertArena = NULL;
11104 ss->ssl3.peerCertChain = NULL;
11105
11106 if (ss->sec.peerCert != NULL) {
11107 if (ss->sec.peerKey) {
11108 SECKEY_DestroyPublicKey(ss->sec.peerKey);
11109 ss->sec.peerKey = NULL;
11110 }
11111 CERT_DestroyCertificate(ss->sec.peerCert);
11112 ss->sec.peerCert = NULL;
11113 }
11114 }
11115
11116 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11117 * a complete ssl3 CertificateStatus message.
11118 * Caller must hold Handshake and RecvBuf locks.
11119 */
11120 static SECStatus
ssl3_HandleCertificateStatus(sslSocket * ss,PRUint8 * b,PRUint32 length)11121 ssl3_HandleCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
11122 {
11123 SECStatus rv;
11124
11125 if (ss->ssl3.hs.ws != wait_certificate_status) {
11126 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11127 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
11128 return SECFailure;
11129 }
11130
11131 rv = ssl_ReadCertificateStatus(ss, b, length);
11132 if (rv != SECSuccess) {
11133 return SECFailure; /* code already set */
11134 }
11135
11136 return ssl3_AuthCertificate(ss);
11137 }
11138
11139 SECStatus
ssl_ReadCertificateStatus(sslSocket * ss,PRUint8 * b,PRUint32 length)11140 ssl_ReadCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
11141 {
11142 PRUint32 status, len;
11143 SECStatus rv;
11144
11145 PORT_Assert(!ss->sec.isServer);
11146
11147 /* Consume the CertificateStatusType enum */
11148 rv = ssl3_ConsumeHandshakeNumber(ss, &status, 1, &b, &length);
11149 if (rv != SECSuccess || status != 1 /* ocsp */) {
11150 return ssl3_DecodeError(ss);
11151 }
11152
11153 rv = ssl3_ConsumeHandshakeNumber(ss, &len, 3, &b, &length);
11154 if (rv != SECSuccess || len != length) {
11155 return ssl3_DecodeError(ss);
11156 }
11157
11158 #define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */
11159 if (length > MAX_CERTSTATUS_LEN) {
11160 ssl3_DecodeError(ss); /* sets error code */
11161 return SECFailure;
11162 }
11163 #undef MAX_CERTSTATUS_LEN
11164
11165 /* Array size 1, because we currently implement single-stapling only */
11166 SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
11167 if (!ss->sec.ci.sid->peerCertStatus.items)
11168 return SECFailure; /* code already set */
11169
11170 ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
11171
11172 if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
11173 SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
11174 return SECFailure; /* code already set */
11175 }
11176
11177 PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
11178 ss->sec.ci.sid->peerCertStatus.items[0].len = length;
11179 ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
11180 return SECSuccess;
11181 }
11182
11183 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11184 * a complete ssl3 Certificate message.
11185 * Caller must hold Handshake and RecvBuf locks.
11186 */
11187 static SECStatus
ssl3_HandleCertificate(sslSocket * ss,PRUint8 * b,PRUint32 length)11188 ssl3_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
11189 {
11190 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
11191 SSL_GETPID(), ss->fd));
11192 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11193 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11194
11195 if ((ss->sec.isServer && ss->ssl3.hs.ws != wait_client_cert) ||
11196 (!ss->sec.isServer && ss->ssl3.hs.ws != wait_server_cert)) {
11197 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11198 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE);
11199 return SECFailure;
11200 }
11201
11202 if (ss->sec.isServer) {
11203 dtls_ReceivedFirstMessageInFlight(ss);
11204 }
11205
11206 return ssl3_CompleteHandleCertificate(ss, b, length);
11207 }
11208
11209 /* Called from ssl3_HandleCertificate
11210 */
11211 SECStatus
ssl3_CompleteHandleCertificate(sslSocket * ss,PRUint8 * b,PRUint32 length)11212 ssl3_CompleteHandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
11213 {
11214 ssl3CertNode *c;
11215 ssl3CertNode *lastCert = NULL;
11216 PRUint32 remaining = 0;
11217 PRUint32 size;
11218 SECStatus rv;
11219 PRBool isServer = ss->sec.isServer;
11220 PRBool isTLS;
11221 SSL3AlertDescription desc;
11222 int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
11223 SECItem certItem;
11224
11225 ssl3_CleanupPeerCerts(ss);
11226 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
11227
11228 /* It is reported that some TLS client sends a Certificate message
11229 ** with a zero-length message body. We'll treat that case like a
11230 ** normal no_certificates message to maximize interoperability.
11231 */
11232 if (length) {
11233 rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 3, &b, &length);
11234 if (rv != SECSuccess)
11235 goto loser; /* fatal alert already sent by ConsumeHandshake. */
11236 if (remaining > length)
11237 goto decode_loser;
11238 }
11239
11240 if (!remaining) {
11241 if (!(isTLS && isServer)) {
11242 desc = bad_certificate;
11243 goto alert_loser;
11244 }
11245 /* This is TLS's version of a no_certificate alert. */
11246 /* I'm a server. I've requested a client cert. He hasn't got one. */
11247 rv = ssl3_HandleNoCertificate(ss);
11248 if (rv != SECSuccess) {
11249 errCode = PORT_GetError();
11250 goto loser;
11251 }
11252
11253 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11254 ss->ssl3.hs.ws = wait_client_key;
11255 } else {
11256 TLS13_SET_HS_STATE(ss, wait_finished);
11257 }
11258 return SECSuccess;
11259 }
11260
11261 ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
11262 if (ss->ssl3.peerCertArena == NULL) {
11263 goto loser; /* don't send alerts on memory errors */
11264 }
11265
11266 /* First get the peer cert. */
11267 if (remaining < 3)
11268 goto decode_loser;
11269
11270 remaining -= 3;
11271 rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
11272 if (rv != SECSuccess)
11273 goto loser; /* fatal alert already sent by ConsumeHandshake. */
11274 if (size == 0 || remaining < size)
11275 goto decode_loser;
11276
11277 certItem.data = b;
11278 certItem.len = size;
11279 b += size;
11280 length -= size;
11281 remaining -= size;
11282
11283 ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
11284 PR_FALSE, PR_TRUE);
11285 if (ss->sec.peerCert == NULL) {
11286 /* We should report an alert if the cert was bad, but not if the
11287 * problem was just some local problem, like memory error.
11288 */
11289 goto ambiguous_err;
11290 }
11291
11292 /* Now get all of the CA certs. */
11293 while (remaining > 0) {
11294 if (remaining < 3)
11295 goto decode_loser;
11296
11297 remaining -= 3;
11298 rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
11299 if (rv != SECSuccess)
11300 goto loser; /* fatal alert already sent by ConsumeHandshake. */
11301 if (size == 0 || remaining < size)
11302 goto decode_loser;
11303
11304 certItem.data = b;
11305 certItem.len = size;
11306 b += size;
11307 length -= size;
11308 remaining -= size;
11309
11310 c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
11311 if (c == NULL) {
11312 goto loser; /* don't send alerts on memory errors */
11313 }
11314
11315 c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
11316 PR_FALSE, PR_TRUE);
11317 if (c->cert == NULL) {
11318 goto ambiguous_err;
11319 }
11320
11321 c->next = NULL;
11322 if (lastCert) {
11323 lastCert->next = c;
11324 } else {
11325 ss->ssl3.peerCertChain = c;
11326 }
11327 lastCert = c;
11328 }
11329
11330 SECKEY_UpdateCertPQG(ss->sec.peerCert);
11331
11332 if (!isServer &&
11333 ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
11334 ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
11335 ss->ssl3.hs.ws = wait_certificate_status;
11336 rv = SECSuccess;
11337 } else {
11338 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
11339 }
11340
11341 return rv;
11342
11343 ambiguous_err:
11344 errCode = PORT_GetError();
11345 switch (errCode) {
11346 case PR_OUT_OF_MEMORY_ERROR:
11347 case SEC_ERROR_BAD_DATABASE:
11348 case SEC_ERROR_NO_MEMORY:
11349 if (isTLS) {
11350 desc = internal_error;
11351 goto alert_loser;
11352 }
11353 goto loser;
11354 }
11355 ssl3_SendAlertForCertError(ss, errCode);
11356 goto loser;
11357
11358 decode_loser:
11359 desc = isTLS ? decode_error : bad_certificate;
11360
11361 alert_loser:
11362 (void)SSL3_SendAlert(ss, alert_fatal, desc);
11363
11364 loser:
11365 (void)ssl_MapLowLevelError(errCode);
11366 return SECFailure;
11367 }
11368
11369 SECStatus
ssl_SetAuthKeyBits(sslSocket * ss,const SECKEYPublicKey * pubKey)11370 ssl_SetAuthKeyBits(sslSocket *ss, const SECKEYPublicKey *pubKey)
11371 {
11372 SECStatus rv;
11373 PRUint32 minKey;
11374 PRInt32 optval;
11375
11376 ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(pubKey);
11377 switch (SECKEY_GetPublicKeyType(pubKey)) {
11378 case rsaKey:
11379 case rsaPssKey:
11380 case rsaOaepKey:
11381 rv = NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &optval);
11382 if (rv == SECSuccess && optval > 0) {
11383 minKey = (PRUint32)optval;
11384 } else {
11385 minKey = SSL_RSA_MIN_MODULUS_BITS;
11386 }
11387 break;
11388
11389 case dsaKey:
11390 rv = NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &optval);
11391 if (rv == SECSuccess && optval > 0) {
11392 minKey = (PRUint32)optval;
11393 } else {
11394 minKey = SSL_DSA_MIN_P_BITS;
11395 }
11396 break;
11397
11398 case dhKey:
11399 rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &optval);
11400 if (rv == SECSuccess && optval > 0) {
11401 minKey = (PRUint32)optval;
11402 } else {
11403 minKey = SSL_DH_MIN_P_BITS;
11404 }
11405 break;
11406
11407 case ecKey:
11408 /* Don't check EC strength here on the understanding that we only
11409 * support curves we like. */
11410 minKey = ss->sec.authKeyBits;
11411 break;
11412
11413 default:
11414 FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
11415 return SECFailure;
11416 }
11417
11418 /* Too small: not good enough. Send a fatal alert. */
11419 if (ss->sec.authKeyBits < minKey) {
11420 FATAL_ERROR(ss, SSL_ERROR_WEAK_SERVER_CERT_KEY,
11421 ss->version >= SSL_LIBRARY_VERSION_TLS_1_0
11422 ? insufficient_security
11423 : illegal_parameter);
11424 return SECFailure;
11425 }
11426
11427 /* PreliminaryChannelInfo.authKeyBits, scheme, and peerDelegCred are now valid. */
11428 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_peer_auth;
11429
11430 return SECSuccess;
11431 }
11432
11433 SECStatus
ssl3_HandleServerSpki(sslSocket * ss)11434 ssl3_HandleServerSpki(sslSocket *ss)
11435 {
11436 PORT_Assert(!ss->sec.isServer);
11437 SECKEYPublicKey *pubKey;
11438
11439 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
11440 tls13_IsVerifyingWithDelegatedCredential(ss)) {
11441 sslDelegatedCredential *dc = ss->xtnData.peerDelegCred;
11442 pubKey = SECKEY_ExtractPublicKey(dc->spki);
11443 if (!pubKey) {
11444 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
11445 return SECFailure;
11446 }
11447
11448 /* Because we have only a single authType (ssl_auth_tls13_any)
11449 * for TLS 1.3 at this point, set the scheme so that the
11450 * callback can interpret |authKeyBits| correctly.
11451 */
11452 ss->sec.signatureScheme = dc->expectedCertVerifyAlg;
11453 } else {
11454 pubKey = CERT_ExtractPublicKey(ss->sec.peerCert);
11455 if (!pubKey) {
11456 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
11457 return SECFailure;
11458 }
11459 }
11460
11461 SECStatus rv = ssl_SetAuthKeyBits(ss, pubKey);
11462 SECKEY_DestroyPublicKey(pubKey);
11463 if (rv != SECSuccess) {
11464 return rv; /* Alert sent and code set. */
11465 }
11466
11467 return SECSuccess;
11468 }
11469
11470 SECStatus
ssl3_AuthCertificate(sslSocket * ss)11471 ssl3_AuthCertificate(sslSocket *ss)
11472 {
11473 SECStatus rv;
11474 PRBool isServer = ss->sec.isServer;
11475 int errCode;
11476
11477 ss->ssl3.hs.authCertificatePending = PR_FALSE;
11478
11479 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
11480 ssl_preinfo_all);
11481
11482 if (!ss->sec.isServer) {
11483 /* Set the |spki| used to verify the handshake. When verifying with a
11484 * delegated credential (DC), this corresponds to the DC public key;
11485 * otherwise it correspond to the public key of the peer's end-entity
11486 * certificate. */
11487 rv = ssl3_HandleServerSpki(ss);
11488 if (rv != SECSuccess) {
11489 /* Alert sent and code set (if not SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE).
11490 * In either case, we're done here. */
11491 errCode = PORT_GetError();
11492 goto loser;
11493 }
11494
11495 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11496 ss->sec.authType = ss->ssl3.hs.kea_def->authKeyType;
11497 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
11498 }
11499 }
11500
11501 /*
11502 * Ask caller-supplied callback function to validate cert chain.
11503 */
11504 rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
11505 PR_TRUE, isServer);
11506 if (rv != SECSuccess) {
11507 errCode = PORT_GetError();
11508 if (errCode == 0) {
11509 errCode = SSL_ERROR_BAD_CERTIFICATE;
11510 }
11511 if (rv != SECWouldBlock) {
11512 if (ss->handleBadCert) {
11513 rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
11514 }
11515 }
11516
11517 if (rv == SECWouldBlock) {
11518 if (ss->sec.isServer) {
11519 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
11520 goto loser;
11521 }
11522
11523 ss->ssl3.hs.authCertificatePending = PR_TRUE;
11524 rv = SECSuccess;
11525 }
11526
11527 if (rv != SECSuccess) {
11528 ssl3_SendAlertForCertError(ss, errCode);
11529 goto loser;
11530 }
11531 }
11532
11533 if (ss->sec.ci.sid->peerCert) {
11534 CERT_DestroyCertificate(ss->sec.ci.sid->peerCert);
11535 }
11536 ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
11537
11538 if (!ss->sec.isServer) {
11539 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
11540 TLS13_SET_HS_STATE(ss, wait_cert_verify);
11541 } else {
11542 /* Ephemeral suites require ServerKeyExchange. */
11543 if (ss->ssl3.hs.kea_def->ephemeral) {
11544 /* require server_key_exchange */
11545 ss->ssl3.hs.ws = wait_server_key;
11546 } else {
11547 /* disallow server_key_exchange */
11548 ss->ssl3.hs.ws = wait_cert_request;
11549 /* This is static RSA key exchange so set the key exchange
11550 * details to compensate for that. */
11551 ss->sec.keaKeyBits = ss->sec.authKeyBits;
11552 ss->sec.signatureScheme = ssl_sig_none;
11553 ss->sec.keaGroup = NULL;
11554 }
11555 }
11556 } else {
11557 /* Server */
11558 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11559 ss->ssl3.hs.ws = wait_client_key;
11560 } else {
11561 TLS13_SET_HS_STATE(ss, wait_cert_verify);
11562 }
11563 }
11564
11565 PORT_Assert(rv == SECSuccess);
11566 if (rv != SECSuccess) {
11567 errCode = SEC_ERROR_LIBRARY_FAILURE;
11568 goto loser;
11569 }
11570
11571 return SECSuccess;
11572
11573 loser:
11574 (void)ssl_MapLowLevelError(errCode);
11575 return SECFailure;
11576 }
11577
11578 static SECStatus ssl3_FinishHandshake(sslSocket *ss);
11579
11580 static SECStatus
ssl3_AlwaysFail(sslSocket * ss)11581 ssl3_AlwaysFail(sslSocket *ss)
11582 {
11583 /* The caller should have cleared the callback. */
11584 ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
11585 PORT_SetError(PR_INVALID_STATE_ERROR);
11586 return SECFailure;
11587 }
11588
11589 /* Caller must hold 1stHandshakeLock.
11590 */
11591 SECStatus
ssl3_AuthCertificateComplete(sslSocket * ss,PRErrorCode error)11592 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
11593 {
11594 SECStatus rv;
11595
11596 PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
11597
11598 if (ss->sec.isServer) {
11599 PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
11600 return SECFailure;
11601 }
11602
11603 ssl_GetRecvBufLock(ss);
11604 ssl_GetSSL3HandshakeLock(ss);
11605
11606 if (!ss->ssl3.hs.authCertificatePending) {
11607 PORT_SetError(PR_INVALID_STATE_ERROR);
11608 rv = SECFailure;
11609 goto done;
11610 }
11611
11612 ss->ssl3.hs.authCertificatePending = PR_FALSE;
11613
11614 if (error != 0) {
11615 ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
11616 ssl3_SendAlertForCertError(ss, error);
11617 rv = SECSuccess;
11618 } else if (ss->ssl3.hs.restartTarget != NULL) {
11619 sslRestartTarget target = ss->ssl3.hs.restartTarget;
11620 ss->ssl3.hs.restartTarget = NULL;
11621
11622 if (target == ssl3_FinishHandshake) {
11623 SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication lost the race"
11624 " with peer's finished message",
11625 SSL_GETPID(), ss->fd));
11626 }
11627
11628 rv = target(ss);
11629 } else {
11630 SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with"
11631 " peer's finished message",
11632 SSL_GETPID(), ss->fd));
11633
11634 PORT_Assert(!ss->ssl3.hs.isResuming);
11635 PORT_Assert(ss->ssl3.hs.ws != idle_handshake);
11636
11637 if (ss->opt.enableFalseStart &&
11638 !ss->firstHsDone &&
11639 !ss->ssl3.hs.isResuming &&
11640 ssl3_WaitingForServerSecondRound(ss)) {
11641 /* ssl3_SendClientSecondRound deferred the false start check because
11642 * certificate authentication was pending, so we do it now if we still
11643 * haven't received all of the server's second round yet.
11644 */
11645 rv = ssl3_CheckFalseStart(ss);
11646 } else {
11647 rv = SECSuccess;
11648 }
11649 }
11650
11651 done:
11652 ssl_ReleaseSSL3HandshakeLock(ss);
11653 ssl_ReleaseRecvBufLock(ss);
11654
11655 return rv;
11656 }
11657
11658 static SECStatus
ssl3_ComputeTLSFinished(sslSocket * ss,ssl3CipherSpec * spec,PRBool isServer,const SSL3Hashes * hashes,TLSFinished * tlsFinished)11659 ssl3_ComputeTLSFinished(sslSocket *ss, ssl3CipherSpec *spec,
11660 PRBool isServer,
11661 const SSL3Hashes *hashes,
11662 TLSFinished *tlsFinished)
11663 {
11664 SECStatus rv;
11665 CK_TLS_MAC_PARAMS tls_mac_params;
11666 SECItem param = { siBuffer, NULL, 0 };
11667 PK11Context *prf_context;
11668 unsigned int retLen;
11669
11670 PORT_Assert(spec->masterSecret);
11671 if (!spec->masterSecret) {
11672 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11673 return SECFailure;
11674 }
11675
11676 if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) {
11677 tls_mac_params.prfHashMechanism = CKM_TLS_PRF;
11678 } else {
11679 tls_mac_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
11680 }
11681 tls_mac_params.ulMacLength = 12;
11682 tls_mac_params.ulServerOrClient = isServer ? 1 : 2;
11683 param.data = (unsigned char *)&tls_mac_params;
11684 param.len = sizeof(tls_mac_params);
11685 prf_context = PK11_CreateContextBySymKey(CKM_TLS_MAC, CKA_SIGN,
11686 spec->masterSecret, ¶m);
11687 if (!prf_context)
11688 return SECFailure;
11689
11690 rv = PK11_DigestBegin(prf_context);
11691 rv |= PK11_DigestOp(prf_context, hashes->u.raw, hashes->len);
11692 rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data, &retLen,
11693 sizeof tlsFinished->verify_data);
11694 PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data);
11695
11696 PK11_DestroyContext(prf_context, PR_TRUE);
11697
11698 return rv;
11699 }
11700
11701 /* The calling function must acquire and release the appropriate
11702 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
11703 * ss->ssl3.crSpec).
11704 */
11705 SECStatus
ssl3_TLSPRFWithMasterSecret(sslSocket * ss,ssl3CipherSpec * spec,const char * label,unsigned int labelLen,const unsigned char * val,unsigned int valLen,unsigned char * out,unsigned int outLen)11706 ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec,
11707 const char *label, unsigned int labelLen,
11708 const unsigned char *val, unsigned int valLen,
11709 unsigned char *out, unsigned int outLen)
11710 {
11711 SECItem param = { siBuffer, NULL, 0 };
11712 CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
11713 PK11Context *prf_context;
11714 unsigned int retLen;
11715 SECStatus rv;
11716
11717 if (!spec->masterSecret) {
11718 PORT_Assert(spec->masterSecret);
11719 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11720 return SECFailure;
11721 }
11722
11723 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
11724 /* Bug 1312976 non-SHA256 exporters are broken. */
11725 if (ssl3_GetPrfHashMechanism(ss) != CKM_SHA256) {
11726 PORT_Assert(0);
11727 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11728 return SECFailure;
11729 }
11730 mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
11731 }
11732 prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
11733 spec->masterSecret, ¶m);
11734 if (!prf_context)
11735 return SECFailure;
11736
11737 rv = PK11_DigestBegin(prf_context);
11738 rv |= PK11_DigestOp(prf_context, (unsigned char *)label, labelLen);
11739 rv |= PK11_DigestOp(prf_context, val, valLen);
11740 rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
11741 PORT_Assert(rv != SECSuccess || retLen == outLen);
11742
11743 PK11_DestroyContext(prf_context, PR_TRUE);
11744 return rv;
11745 }
11746
11747 /* called from ssl3_SendClientSecondRound
11748 * ssl3_HandleFinished
11749 */
11750 static SECStatus
ssl3_SendNextProto(sslSocket * ss)11751 ssl3_SendNextProto(sslSocket *ss)
11752 {
11753 SECStatus rv;
11754 int padding_len;
11755 static const unsigned char padding[32] = { 0 };
11756
11757 if (ss->xtnData.nextProto.len == 0 ||
11758 ss->xtnData.nextProtoState == SSL_NEXT_PROTO_SELECTED) {
11759 return SECSuccess;
11760 }
11761
11762 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11763 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11764
11765 padding_len = 32 - ((ss->xtnData.nextProto.len + 2) % 32);
11766
11767 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_next_proto, ss->xtnData.nextProto.len + 2 + padding_len);
11768 if (rv != SECSuccess) {
11769 return rv; /* error code set by AppendHandshakeHeader */
11770 }
11771 rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.nextProto.data,
11772 ss->xtnData.nextProto.len, 1);
11773 if (rv != SECSuccess) {
11774 return rv; /* error code set by AppendHandshake */
11775 }
11776 rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
11777 if (rv != SECSuccess) {
11778 return rv; /* error code set by AppendHandshake */
11779 }
11780 return rv;
11781 }
11782
11783 /* called from ssl3_SendFinished and tls13_DeriveSecret.
11784 *
11785 * This function is simply a debugging aid and therefore does not return a
11786 * SECStatus. */
11787 void
ssl3_RecordKeyLog(sslSocket * ss,const char * label,PK11SymKey * secret)11788 ssl3_RecordKeyLog(sslSocket *ss, const char *label, PK11SymKey *secret)
11789 {
11790 #ifdef NSS_ALLOW_SSLKEYLOGFILE
11791 SECStatus rv;
11792 SECItem *keyData;
11793 /* Longest label is "CLIENT_HANDSHAKE_TRAFFIC_SECRET", master secret is 48
11794 * bytes which happens to be the largest in TLS 1.3 as well (SHA384).
11795 * Maximum line length: "CLIENT_HANDSHAKE_TRAFFIC_SECRET" (31) + " " (1) +
11796 * client_random (32*2) + " " (1) +
11797 * traffic_secret (48*2) + "\n" (1) = 194. */
11798 char buf[200];
11799 unsigned int offset, len;
11800
11801 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11802
11803 if (!ssl_keylog_iob)
11804 return;
11805
11806 rv = PK11_ExtractKeyValue(secret);
11807 if (rv != SECSuccess)
11808 return;
11809
11810 /* keyData does not need to be freed. */
11811 keyData = PK11_GetKeyData(secret);
11812 if (!keyData || !keyData->data)
11813 return;
11814
11815 len = strlen(label) + 1 + /* label + space */
11816 SSL3_RANDOM_LENGTH * 2 + 1 + /* client random (hex) + space */
11817 keyData->len * 2 + 1; /* secret (hex) + newline */
11818 PORT_Assert(len <= sizeof(buf));
11819 if (len > sizeof(buf))
11820 return;
11821
11822 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
11823
11824 /* There could be multiple, concurrent writers to the
11825 * keylog, so we have to do everything in a single call to
11826 * fwrite. */
11827
11828 strcpy(buf, label);
11829 offset = strlen(label);
11830 buf[offset++] += ' ';
11831 hexEncode(buf + offset, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
11832 offset += SSL3_RANDOM_LENGTH * 2;
11833 buf[offset++] = ' ';
11834 hexEncode(buf + offset, keyData->data, keyData->len);
11835 offset += keyData->len * 2;
11836 buf[offset++] = '\n';
11837
11838 PORT_Assert(offset == len);
11839
11840 PZ_Lock(ssl_keylog_lock);
11841 if (fwrite(buf, len, 1, ssl_keylog_iob) == 1)
11842 fflush(ssl_keylog_iob);
11843 PZ_Unlock(ssl_keylog_lock);
11844 #endif
11845 }
11846
11847 /* called from ssl3_SendClientSecondRound
11848 * ssl3_HandleClientHello
11849 * ssl3_HandleFinished
11850 */
11851 static SECStatus
ssl3_SendFinished(sslSocket * ss,PRInt32 flags)11852 ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
11853 {
11854 ssl3CipherSpec *cwSpec;
11855 PRBool isTLS;
11856 PRBool isServer = ss->sec.isServer;
11857 SECStatus rv;
11858 SSL3Sender sender = isServer ? sender_server : sender_client;
11859 SSL3Hashes hashes;
11860 TLSFinished tlsFinished;
11861
11862 SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
11863
11864 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11865 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11866
11867 ssl_GetSpecReadLock(ss);
11868 cwSpec = ss->ssl3.cwSpec;
11869 isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
11870 rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
11871 if (isTLS && rv == SECSuccess) {
11872 rv = ssl3_ComputeTLSFinished(ss, cwSpec, isServer, &hashes, &tlsFinished);
11873 }
11874 ssl_ReleaseSpecReadLock(ss);
11875 if (rv != SECSuccess) {
11876 goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */
11877 }
11878
11879 if (isTLS) {
11880 if (isServer)
11881 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
11882 else
11883 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
11884 ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
11885 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof tlsFinished);
11886 if (rv != SECSuccess)
11887 goto fail; /* err set by AppendHandshake. */
11888 rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
11889 if (rv != SECSuccess)
11890 goto fail; /* err set by AppendHandshake. */
11891 } else {
11892 if (isServer)
11893 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
11894 else
11895 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
11896 PORT_Assert(hashes.len == sizeof hashes.u.s);
11897 ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
11898 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof hashes.u.s);
11899 if (rv != SECSuccess)
11900 goto fail; /* err set by AppendHandshake. */
11901 rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
11902 if (rv != SECSuccess)
11903 goto fail; /* err set by AppendHandshake. */
11904 }
11905 rv = ssl3_FlushHandshake(ss, flags);
11906 if (rv != SECSuccess) {
11907 goto fail; /* error code set by ssl3_FlushHandshake */
11908 }
11909
11910 ssl3_RecordKeyLog(ss, "CLIENT_RANDOM", ss->ssl3.cwSpec->masterSecret);
11911
11912 return SECSuccess;
11913
11914 fail:
11915 return rv;
11916 }
11917
11918 /* wrap the master secret, and put it into the SID.
11919 * Caller holds the Spec read lock.
11920 */
11921 SECStatus
ssl3_CacheWrappedSecret(sslSocket * ss,sslSessionID * sid,PK11SymKey * secret)11922 ssl3_CacheWrappedSecret(sslSocket *ss, sslSessionID *sid,
11923 PK11SymKey *secret)
11924 {
11925 PK11SymKey *wrappingKey = NULL;
11926 PK11SlotInfo *symKeySlot;
11927 void *pwArg = ss->pkcs11PinArg;
11928 SECStatus rv = SECFailure;
11929 PRBool isServer = ss->sec.isServer;
11930 CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
11931
11932 symKeySlot = PK11_GetSlotFromKey(secret);
11933 if (!isServer) {
11934 int wrapKeyIndex;
11935 int incarnation;
11936
11937 /* these next few functions are mere accessors and don't fail. */
11938 sid->u.ssl3.masterWrapIndex = wrapKeyIndex =
11939 PK11_GetCurrentWrapIndex(symKeySlot);
11940 PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
11941
11942 sid->u.ssl3.masterWrapSeries = incarnation =
11943 PK11_GetSlotSeries(symKeySlot);
11944 sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot);
11945 sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
11946 sid->u.ssl3.masterValid = PR_TRUE;
11947 /* Get the default wrapping key, for wrapping the master secret before
11948 * placing it in the SID cache entry. */
11949 wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
11950 CKM_INVALID_MECHANISM, incarnation,
11951 pwArg);
11952 if (wrappingKey) {
11953 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
11954 } else {
11955 int keyLength;
11956 /* if the wrappingKey doesn't exist, attempt to create it.
11957 * Note: we intentionally ignore errors here. If we cannot
11958 * generate a wrapping key, it is not fatal to this SSL connection,
11959 * but we will not be able to restart this session.
11960 */
11961 mechanism = PK11_GetBestWrapMechanism(symKeySlot);
11962 keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
11963 /* Zero length means fixed key length algorithm, or error.
11964 * It's ambiguous.
11965 */
11966 wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
11967 keyLength, pwArg);
11968 if (wrappingKey) {
11969 /* The thread safety characteristics of PK11_[SG]etWrapKey is
11970 * abominable. This protects against races in calling
11971 * PK11_SetWrapKey by dropping and re-acquiring the canonical
11972 * value once it is set. The mutex in PK11_[SG]etWrapKey will
11973 * ensure that races produce the same value in the end. */
11974 PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
11975 PK11_FreeSymKey(wrappingKey);
11976 wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
11977 CKM_INVALID_MECHANISM, incarnation, pwArg);
11978 if (!wrappingKey) {
11979 PK11_FreeSlot(symKeySlot);
11980 return SECFailure;
11981 }
11982 }
11983 }
11984 } else {
11985 /* server socket using session cache. */
11986 mechanism = PK11_GetBestWrapMechanism(symKeySlot);
11987 if (mechanism != CKM_INVALID_MECHANISM) {
11988 wrappingKey =
11989 ssl3_GetWrappingKey(ss, symKeySlot, mechanism, pwArg);
11990 if (wrappingKey) {
11991 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
11992 }
11993 }
11994 }
11995
11996 sid->u.ssl3.masterWrapMech = mechanism;
11997 PK11_FreeSlot(symKeySlot);
11998
11999 if (wrappingKey) {
12000 SECItem wmsItem;
12001
12002 wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
12003 wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret;
12004 rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
12005 secret, &wmsItem);
12006 /* rv is examined below. */
12007 sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
12008 PK11_FreeSymKey(wrappingKey);
12009 }
12010 return rv;
12011 }
12012
12013 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
12014 * a complete ssl3 Finished message from the peer.
12015 * Caller must hold Handshake and RecvBuf locks.
12016 */
12017 static SECStatus
ssl3_HandleFinished(sslSocket * ss,PRUint8 * b,PRUint32 length)12018 ssl3_HandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
12019 {
12020 SECStatus rv = SECSuccess;
12021 PRBool isServer = ss->sec.isServer;
12022 PRBool isTLS;
12023 SSL3Hashes hashes;
12024
12025 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12026 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12027
12028 SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
12029 SSL_GETPID(), ss->fd));
12030
12031 if (ss->ssl3.hs.ws != wait_finished) {
12032 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12033 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
12034 return SECFailure;
12035 }
12036
12037 if (!ss->sec.isServer || !ss->opt.requestCertificate) {
12038 dtls_ReceivedFirstMessageInFlight(ss);
12039 }
12040
12041 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.crSpec, &hashes,
12042 isServer ? sender_client : sender_server);
12043 if (rv != SECSuccess) {
12044 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12045 return SECFailure;
12046 }
12047
12048 rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
12049 if (rv != SECSuccess) {
12050 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12051 return rv;
12052 }
12053
12054 isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
12055 if (isTLS) {
12056 TLSFinished tlsFinished;
12057
12058 if (length != sizeof(tlsFinished)) {
12059 #ifndef UNSAFE_FUZZER_MODE
12060 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
12061 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12062 return SECFailure;
12063 #endif
12064 }
12065 rv = ssl3_ComputeTLSFinished(ss, ss->ssl3.crSpec, !isServer,
12066 &hashes, &tlsFinished);
12067 if (!isServer)
12068 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
12069 else
12070 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
12071 ss->ssl3.hs.finishedBytes = sizeof(tlsFinished);
12072 if (rv != SECSuccess ||
12073 0 != NSS_SecureMemcmp(&tlsFinished, b,
12074 PR_MIN(length, ss->ssl3.hs.finishedBytes))) {
12075 #ifndef UNSAFE_FUZZER_MODE
12076 (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
12077 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12078 return SECFailure;
12079 #endif
12080 }
12081 } else {
12082 if (length != sizeof(SSL3Finished)) {
12083 (void)ssl3_IllegalParameter(ss);
12084 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12085 return SECFailure;
12086 }
12087
12088 if (!isServer)
12089 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
12090 else
12091 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
12092 PORT_Assert(hashes.len == sizeof hashes.u.s);
12093 ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
12094 if (0 != NSS_SecureMemcmp(&hashes.u.s, b, length)) {
12095 (void)ssl3_HandshakeFailure(ss);
12096 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12097 return SECFailure;
12098 }
12099 }
12100
12101 ssl_GetXmitBufLock(ss); /*************************************/
12102
12103 if ((isServer && !ss->ssl3.hs.isResuming) ||
12104 (!isServer && ss->ssl3.hs.isResuming)) {
12105 PRInt32 flags = 0;
12106
12107 /* Send a NewSessionTicket message if the client sent us
12108 * either an empty session ticket, or one that did not verify.
12109 * (Note that if either of these conditions was met, then the
12110 * server has sent a SessionTicket extension in the
12111 * ServerHello message.)
12112 */
12113 if (isServer && !ss->ssl3.hs.isResuming &&
12114 ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
12115 ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
12116 /* RFC 5077 Section 3.3: "In the case of a full handshake, the
12117 * server MUST verify the client's Finished message before sending
12118 * the ticket." Presumably, this also means that the client's
12119 * certificate, if any, must be verified beforehand too.
12120 */
12121 rv = ssl3_SendNewSessionTicket(ss);
12122 if (rv != SECSuccess) {
12123 goto xmit_loser;
12124 }
12125 }
12126
12127 rv = ssl3_SendChangeCipherSpecs(ss);
12128 if (rv != SECSuccess) {
12129 goto xmit_loser; /* err is set. */
12130 }
12131 /* If this thread is in SSL_SecureSend (trying to write some data)
12132 ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
12133 ** last two handshake messages (change cipher spec and finished)
12134 ** will be sent in the same send/write call as the application data.
12135 */
12136 if (ss->writerThread == PR_GetCurrentThread()) {
12137 flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
12138 }
12139
12140 if (!isServer && !ss->firstHsDone) {
12141 rv = ssl3_SendNextProto(ss);
12142 if (rv != SECSuccess) {
12143 goto xmit_loser; /* err code was set. */
12144 }
12145 }
12146
12147 if (IS_DTLS(ss)) {
12148 flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
12149 }
12150
12151 rv = ssl3_SendFinished(ss, flags);
12152 if (rv != SECSuccess) {
12153 goto xmit_loser; /* err is set. */
12154 }
12155 }
12156
12157 xmit_loser:
12158 ssl_ReleaseXmitBufLock(ss); /*************************************/
12159 if (rv != SECSuccess) {
12160 return rv;
12161 }
12162
12163 if (ss->ssl3.hs.authCertificatePending) {
12164 if (ss->ssl3.hs.restartTarget) {
12165 PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
12166 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12167 return SECFailure;
12168 }
12169
12170 ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
12171 PORT_SetError(PR_WOULD_BLOCK_ERROR);
12172 return SECFailure;
12173 }
12174
12175 rv = ssl3_FinishHandshake(ss);
12176 return rv;
12177 }
12178
12179 SECStatus
ssl3_FillInCachedSID(sslSocket * ss,sslSessionID * sid,PK11SymKey * secret)12180 ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid, PK11SymKey *secret)
12181 {
12182 PORT_Assert(secret);
12183
12184 /* fill in the sid */
12185 sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
12186 sid->u.ssl3.policy = ss->ssl3.policy;
12187 sid->version = ss->version;
12188 sid->authType = ss->sec.authType;
12189 sid->authKeyBits = ss->sec.authKeyBits;
12190 sid->keaType = ss->sec.keaType;
12191 sid->keaKeyBits = ss->sec.keaKeyBits;
12192 if (ss->sec.keaGroup) {
12193 sid->keaGroup = ss->sec.keaGroup->name;
12194 } else {
12195 sid->keaGroup = ssl_grp_none;
12196 }
12197 sid->sigScheme = ss->sec.signatureScheme;
12198 sid->lastAccessTime = sid->creationTime = ssl_Time(ss);
12199 sid->expirationTime = sid->creationTime + (ssl_ticket_lifetime * PR_USEC_PER_SEC);
12200 sid->localCert = CERT_DupCertificate(ss->sec.localCert);
12201 if (ss->sec.isServer) {
12202 sid->namedCurve = ss->sec.serverCert->namedCurve;
12203 }
12204
12205 if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
12206 ss->xtnData.nextProto.data) {
12207 SECITEM_FreeItem(&sid->u.ssl3.alpnSelection, PR_FALSE);
12208 if (SECITEM_CopyItem(
12209 NULL, &sid->u.ssl3.alpnSelection, &ss->xtnData.nextProto) != SECSuccess) {
12210 return SECFailure; /* error already set. */
12211 }
12212 }
12213
12214 /* Copy the master secret (wrapped or unwrapped) into the sid */
12215 return ssl3_CacheWrappedSecret(ss, ss->sec.ci.sid, secret);
12216 }
12217
12218 /* The return type is SECStatus instead of void because this function needs
12219 * to have type sslRestartTarget.
12220 */
12221 SECStatus
ssl3_FinishHandshake(sslSocket * ss)12222 ssl3_FinishHandshake(sslSocket *ss)
12223 {
12224 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12225 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12226 PORT_Assert(ss->ssl3.hs.restartTarget == NULL);
12227 sslSessionID *sid = ss->sec.ci.sid;
12228 SECStatus sidRv = SECFailure;
12229
12230 /* The first handshake is now completed. */
12231 ss->handshake = NULL;
12232
12233 if (sid->cached == never_cached && !ss->opt.noCache) {
12234 /* If the wrap fails, don't cache the sid. The connection proceeds
12235 * normally, so the rv is only used to determine whether we cache. */
12236 sidRv = ssl3_FillInCachedSID(ss, sid, ss->ssl3.crSpec->masterSecret);
12237 }
12238
12239 /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid
12240 * until it has verified the server's Finished message." When the server
12241 * sends a NewSessionTicket in a resumption handshake, we must wait until
12242 * the handshake is finished (we have verified the server's Finished
12243 * AND the server's certificate) before we update the ticket in the sid.
12244 *
12245 * This must be done before we call ssl_CacheSessionID(ss)
12246 * because CacheSID requires the session ticket to already be set, and also
12247 * because of the lazy lock creation scheme used by CacheSID and
12248 * ssl3_SetSIDSessionTicket. */
12249 if (ss->ssl3.hs.receivedNewSessionTicket) {
12250 PORT_Assert(!ss->sec.isServer);
12251 if (sidRv == SECSuccess) {
12252 /* The sid takes over the ticket data */
12253 ssl3_SetSIDSessionTicket(ss->sec.ci.sid,
12254 &ss->ssl3.hs.newSessionTicket);
12255 } else {
12256 PORT_Assert(ss->ssl3.hs.newSessionTicket.ticket.data);
12257 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket,
12258 PR_FALSE);
12259 }
12260 PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
12261 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
12262 }
12263 if (sidRv == SECSuccess) {
12264 PORT_Assert(ss->sec.ci.sid->cached == never_cached);
12265 ssl_CacheSessionID(ss);
12266 }
12267
12268 ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */
12269 ss->ssl3.hs.ws = idle_handshake;
12270
12271 ssl_FinishHandshake(ss);
12272
12273 return SECSuccess;
12274 }
12275
12276 SECStatus
ssl_HashHandshakeMessageInt(sslSocket * ss,SSLHandshakeType ct,PRUint32 dtlsSeq,const PRUint8 * b,PRUint32 length,sslUpdateHandshakeHashes updateHashes)12277 ssl_HashHandshakeMessageInt(sslSocket *ss, SSLHandshakeType ct,
12278 PRUint32 dtlsSeq,
12279 const PRUint8 *b, PRUint32 length,
12280 sslUpdateHandshakeHashes updateHashes)
12281 {
12282 PRUint8 hdr[4];
12283 PRUint8 dtlsData[8];
12284 SECStatus rv;
12285
12286 PRINT_BUF(50, (ss, "Hash handshake message:", b, length));
12287
12288 hdr[0] = (PRUint8)ct;
12289 hdr[1] = (PRUint8)(length >> 16);
12290 hdr[2] = (PRUint8)(length >> 8);
12291 hdr[3] = (PRUint8)(length);
12292
12293 rv = updateHashes(ss, (unsigned char *)hdr, 4);
12294 if (rv != SECSuccess)
12295 return rv; /* err code already set. */
12296
12297 /* Extra data to simulate a complete DTLS handshake fragment */
12298 if (IS_DTLS(ss)) {
12299 /* Sequence number */
12300 dtlsData[0] = MSB(dtlsSeq);
12301 dtlsData[1] = LSB(dtlsSeq);
12302
12303 /* Fragment offset */
12304 dtlsData[2] = 0;
12305 dtlsData[3] = 0;
12306 dtlsData[4] = 0;
12307
12308 /* Fragment length */
12309 dtlsData[5] = (PRUint8)(length >> 16);
12310 dtlsData[6] = (PRUint8)(length >> 8);
12311 dtlsData[7] = (PRUint8)(length);
12312
12313 rv = updateHashes(ss, (unsigned char *)dtlsData, sizeof(dtlsData));
12314 if (rv != SECSuccess)
12315 return rv; /* err code already set. */
12316 }
12317
12318 /* The message body */
12319 rv = updateHashes(ss, b, length);
12320 if (rv != SECSuccess)
12321 return rv; /* err code already set. */
12322
12323 return SECSuccess;
12324 }
12325
12326 SECStatus
ssl_HashHandshakeMessage(sslSocket * ss,SSLHandshakeType ct,const PRUint8 * b,PRUint32 length)12327 ssl_HashHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
12328 const PRUint8 *b, PRUint32 length)
12329 {
12330 return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12331 b, length, ssl3_UpdateHandshakeHashes);
12332 }
12333
12334 SECStatus
ssl_HashHandshakeMessageDefault(sslSocket * ss,SSLHandshakeType ct,const PRUint8 * b,PRUint32 length)12335 ssl_HashHandshakeMessageDefault(sslSocket *ss, SSLHandshakeType ct,
12336 const PRUint8 *b, PRUint32 length)
12337 {
12338 return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12339 b, length, ssl3_UpdateDefaultHandshakeHashes);
12340 }
12341 SECStatus
ssl_HashHandshakeMessageEchInner(sslSocket * ss,SSLHandshakeType ct,const PRUint8 * b,PRUint32 length)12342 ssl_HashHandshakeMessageEchInner(sslSocket *ss, SSLHandshakeType ct,
12343 const PRUint8 *b, PRUint32 length)
12344 {
12345 return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12346 b, length, ssl3_UpdateInnerHandshakeHashes);
12347 }
12348
12349 SECStatus
ssl_HashPostHandshakeMessage(sslSocket * ss,SSLHandshakeType ct,const PRUint8 * b,PRUint32 length)12350 ssl_HashPostHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
12351 const PRUint8 *b, PRUint32 length)
12352 {
12353 return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12354 b, length, ssl3_UpdatePostHandshakeHashes);
12355 }
12356
12357 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
12358 * handshake message.
12359 * Caller must hold Handshake and RecvBuf locks.
12360 */
12361 SECStatus
ssl3_HandleHandshakeMessage(sslSocket * ss,PRUint8 * b,PRUint32 length,PRBool endOfRecord)12362 ssl3_HandleHandshakeMessage(sslSocket *ss, PRUint8 *b, PRUint32 length,
12363 PRBool endOfRecord)
12364 {
12365 SECStatus rv = SECSuccess;
12366 PRUint16 epoch;
12367
12368 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12369 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12370
12371 SSL_TRC(30, ("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
12372 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
12373
12374 /* Start new handshake hashes when we start a new handshake. */
12375 if (ss->ssl3.hs.msg_type == ssl_hs_client_hello) {
12376 ssl3_RestartHandshakeHashes(ss);
12377 }
12378 switch (ss->ssl3.hs.msg_type) {
12379 case ssl_hs_hello_request:
12380 case ssl_hs_hello_verify_request:
12381 /* We don't include hello_request and hello_verify_request messages
12382 * in the handshake hashes */
12383 break;
12384
12385 /* Defer hashing of these messages until the message handlers. */
12386 case ssl_hs_client_hello:
12387 case ssl_hs_server_hello:
12388 case ssl_hs_certificate_verify:
12389 case ssl_hs_finished:
12390 break;
12391
12392 default:
12393 if (!tls13_IsPostHandshake(ss)) {
12394 rv = ssl_HashHandshakeMessage(ss, ss->ssl3.hs.msg_type, b, length);
12395 if (rv != SECSuccess) {
12396 return SECFailure;
12397 }
12398 }
12399 }
12400
12401 PORT_SetError(0); /* each message starts with no error. */
12402
12403 if (ss->ssl3.hs.ws == wait_certificate_status &&
12404 ss->ssl3.hs.msg_type != ssl_hs_certificate_status) {
12405 /* If we negotiated the certificate_status extension then we deferred
12406 * certificate validation until we get the CertificateStatus messsage.
12407 * But the CertificateStatus message is optional. If the server did
12408 * not send it then we need to validate the certificate now. If the
12409 * server does send the CertificateStatus message then we will
12410 * authenticate the certificate in ssl3_HandleCertificateStatus.
12411 */
12412 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
12413 if (rv != SECSuccess) {
12414 /* This can't block. */
12415 PORT_Assert(PORT_GetError() != PR_WOULD_BLOCK_ERROR);
12416 return SECFailure;
12417 }
12418 }
12419
12420 epoch = ss->ssl3.crSpec->epoch;
12421 switch (ss->ssl3.hs.msg_type) {
12422 case ssl_hs_client_hello:
12423 if (!ss->sec.isServer) {
12424 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12425 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
12426 return SECFailure;
12427 }
12428 rv = ssl3_HandleClientHello(ss, b, length);
12429 break;
12430 case ssl_hs_server_hello:
12431 if (ss->sec.isServer) {
12432 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12433 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
12434 return SECFailure;
12435 }
12436 rv = ssl3_HandleServerHello(ss, b, length);
12437 break;
12438 default:
12439 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
12440 rv = ssl3_HandlePostHelloHandshakeMessage(ss, b, length);
12441 } else {
12442 rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length);
12443 }
12444 break;
12445 }
12446 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
12447 (epoch != ss->ssl3.crSpec->epoch) && !endOfRecord) {
12448 /* If we changed read cipher states, there must not be any
12449 * data in the input queue. */
12450 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12451 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
12452 return SECFailure;
12453 }
12454
12455 if (IS_DTLS(ss) && (rv != SECFailure)) {
12456 /* Increment the expected sequence number */
12457 ss->ssl3.hs.recvMessageSeq++;
12458 }
12459
12460 /* Taint the message so that it's easier to detect UAFs. */
12461 PORT_Memset(b, 'N', length);
12462
12463 return rv;
12464 }
12465
12466 static SECStatus
ssl3_HandlePostHelloHandshakeMessage(sslSocket * ss,PRUint8 * b,PRUint32 length)12467 ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b,
12468 PRUint32 length)
12469 {
12470 SECStatus rv;
12471 PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
12472
12473 switch (ss->ssl3.hs.msg_type) {
12474 case ssl_hs_hello_request:
12475 if (length != 0) {
12476 (void)ssl3_DecodeError(ss);
12477 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
12478 return SECFailure;
12479 }
12480 if (ss->sec.isServer) {
12481 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12482 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
12483 return SECFailure;
12484 }
12485 rv = ssl3_HandleHelloRequest(ss);
12486 break;
12487
12488 case ssl_hs_hello_verify_request:
12489 if (!IS_DTLS(ss) || ss->sec.isServer) {
12490 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12491 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
12492 return SECFailure;
12493 }
12494 rv = dtls_HandleHelloVerifyRequest(ss, b, length);
12495 break;
12496 case ssl_hs_certificate:
12497 rv = ssl3_HandleCertificate(ss, b, length);
12498 break;
12499 case ssl_hs_certificate_status:
12500 rv = ssl3_HandleCertificateStatus(ss, b, length);
12501 break;
12502 case ssl_hs_server_key_exchange:
12503 if (ss->sec.isServer) {
12504 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12505 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
12506 return SECFailure;
12507 }
12508 rv = ssl3_HandleServerKeyExchange(ss, b, length);
12509 break;
12510 case ssl_hs_certificate_request:
12511 if (ss->sec.isServer) {
12512 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12513 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
12514 return SECFailure;
12515 }
12516 rv = ssl3_HandleCertificateRequest(ss, b, length);
12517 break;
12518 case ssl_hs_server_hello_done:
12519 if (length != 0) {
12520 (void)ssl3_DecodeError(ss);
12521 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
12522 return SECFailure;
12523 }
12524 if (ss->sec.isServer) {
12525 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12526 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
12527 return SECFailure;
12528 }
12529 rv = ssl3_HandleServerHelloDone(ss);
12530 break;
12531 case ssl_hs_certificate_verify:
12532 if (!ss->sec.isServer) {
12533 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12534 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
12535 return SECFailure;
12536 }
12537 rv = ssl3_HandleCertificateVerify(ss, b, length);
12538 break;
12539 case ssl_hs_client_key_exchange:
12540 if (!ss->sec.isServer) {
12541 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12542 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
12543 return SECFailure;
12544 }
12545 rv = ssl3_HandleClientKeyExchange(ss, b, length);
12546 break;
12547 case ssl_hs_new_session_ticket:
12548 if (ss->sec.isServer) {
12549 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12550 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
12551 return SECFailure;
12552 }
12553 rv = ssl3_HandleNewSessionTicket(ss, b, length);
12554 break;
12555 case ssl_hs_finished:
12556 rv = ssl3_HandleFinished(ss, b, length);
12557 break;
12558 default:
12559 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12560 PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
12561 rv = SECFailure;
12562 }
12563
12564 return rv;
12565 }
12566
12567 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
12568 * origBuf is the decrypted ssl record content.
12569 * Caller must hold the handshake and RecvBuf locks.
12570 */
12571 static SECStatus
ssl3_HandleHandshake(sslSocket * ss,sslBuffer * origBuf)12572 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
12573 {
12574 sslBuffer buf = *origBuf; /* Work from a copy. */
12575 SECStatus rv;
12576
12577 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12578 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12579
12580 while (buf.len > 0) {
12581 if (ss->ssl3.hs.header_bytes < 4) {
12582 PRUint8 t;
12583 t = *(buf.buf++);
12584 buf.len--;
12585 if (ss->ssl3.hs.header_bytes++ == 0)
12586 ss->ssl3.hs.msg_type = (SSLHandshakeType)t;
12587 else
12588 ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
12589 if (ss->ssl3.hs.header_bytes < 4)
12590 continue;
12591
12592 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
12593 if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
12594 (void)ssl3_DecodeError(ss);
12595 PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
12596 goto loser;
12597 }
12598 #undef MAX_HANDSHAKE_MSG_LEN
12599
12600 /* If msg_len is zero, be sure we fall through,
12601 ** even if buf.len is zero.
12602 */
12603 if (ss->ssl3.hs.msg_len > 0)
12604 continue;
12605 }
12606
12607 /*
12608 * Header has been gathered and there is at least one byte of new
12609 * data available for this message. If it can be done right out
12610 * of the original buffer, then use it from there.
12611 */
12612 if (ss->ssl3.hs.msg_body.len == 0 && buf.len >= ss->ssl3.hs.msg_len) {
12613 /* handle it from input buffer */
12614 rv = ssl3_HandleHandshakeMessage(ss, buf.buf, ss->ssl3.hs.msg_len,
12615 buf.len == ss->ssl3.hs.msg_len);
12616 buf.buf += ss->ssl3.hs.msg_len;
12617 buf.len -= ss->ssl3.hs.msg_len;
12618 ss->ssl3.hs.msg_len = 0;
12619 ss->ssl3.hs.header_bytes = 0;
12620 if (rv != SECSuccess) {
12621 goto loser;
12622 }
12623 } else {
12624 /* must be copied to msg_body and dealt with from there */
12625 unsigned int bytes;
12626
12627 PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
12628 bytes = PR_MIN(buf.len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
12629
12630 /* Grow the buffer if needed */
12631 rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
12632 if (rv != SECSuccess) {
12633 /* sslBuffer_Grow has set a memory error code. */
12634 goto loser;
12635 }
12636
12637 PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
12638 buf.buf, bytes);
12639 ss->ssl3.hs.msg_body.len += bytes;
12640 buf.buf += bytes;
12641 buf.len -= bytes;
12642
12643 PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
12644
12645 /* if we have a whole message, do it */
12646 if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
12647 rv = ssl3_HandleHandshakeMessage(
12648 ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len,
12649 buf.len == 0);
12650 ss->ssl3.hs.msg_body.len = 0;
12651 ss->ssl3.hs.msg_len = 0;
12652 ss->ssl3.hs.header_bytes = 0;
12653 if (rv != SECSuccess) {
12654 goto loser;
12655 }
12656 } else {
12657 PORT_Assert(buf.len == 0);
12658 break;
12659 }
12660 }
12661 } /* end loop */
12662
12663 origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
12664 return SECSuccess;
12665
12666 loser : {
12667 /* Make sure to remove any data that was consumed. */
12668 unsigned int consumed = origBuf->len - buf.len;
12669 PORT_Assert(consumed == buf.buf - origBuf->buf);
12670 if (consumed > 0) {
12671 memmove(origBuf->buf, origBuf->buf + consumed, buf.len);
12672 origBuf->len = buf.len;
12673 }
12674 }
12675 return SECFailure;
12676 }
12677
12678 /* SECStatusToMask returns, in constant time, a mask value of all ones if
12679 * rv == SECSuccess. Otherwise it returns zero. */
12680 static unsigned int
SECStatusToMask(SECStatus rv)12681 SECStatusToMask(SECStatus rv)
12682 {
12683 return PORT_CT_EQ(rv, SECSuccess);
12684 }
12685
12686 /* ssl_ConstantTimeGE returns 0xffffffff if a>=b and 0x00 otherwise. */
12687 static unsigned char
ssl_ConstantTimeGE(unsigned int a,unsigned int b)12688 ssl_ConstantTimeGE(unsigned int a, unsigned int b)
12689 {
12690 return PORT_CT_GE(a, b);
12691 }
12692
12693 /* ssl_ConstantTimeEQ returns 0xffffffff if a==b and 0x00 otherwise. */
12694 static unsigned char
ssl_ConstantTimeEQ(unsigned char a,unsigned char b)12695 ssl_ConstantTimeEQ(unsigned char a, unsigned char b)
12696 {
12697 return PORT_CT_EQ(a, b);
12698 }
12699
12700 /* ssl_constantTimeSelect return a if mask is 0xFF and b if mask is 0x00 */
12701 static unsigned char
ssl_constantTimeSelect(unsigned char mask,unsigned char a,unsigned char b)12702 ssl_constantTimeSelect(unsigned char mask, unsigned char a, unsigned char b)
12703 {
12704 return (mask & a) | (~mask & b);
12705 }
12706
12707 static SECStatus
ssl_RemoveSSLv3CBCPadding(sslBuffer * plaintext,unsigned int blockSize,unsigned int macSize)12708 ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
12709 unsigned int blockSize,
12710 unsigned int macSize)
12711 {
12712 unsigned int paddingLength, good;
12713 const unsigned int overhead = 1 /* padding length byte */ + macSize;
12714
12715 /* These lengths are all public so we can test them in non-constant
12716 * time. */
12717 if (overhead > plaintext->len) {
12718 return SECFailure;
12719 }
12720
12721 paddingLength = plaintext->buf[plaintext->len - 1];
12722 /* SSLv3 padding bytes are random and cannot be checked. */
12723 good = PORT_CT_GE(plaintext->len, paddingLength + overhead);
12724 /* SSLv3 requires that the padding is minimal. */
12725 good &= PORT_CT_GE(blockSize, paddingLength + 1);
12726 plaintext->len -= good & (paddingLength + 1);
12727 return (good & SECSuccess) | (~good & SECFailure);
12728 }
12729
12730 SECStatus
ssl_RemoveTLSCBCPadding(sslBuffer * plaintext,unsigned int macSize)12731 ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
12732 {
12733 unsigned int paddingLength, good, toCheck, i;
12734 const unsigned int overhead = 1 /* padding length byte */ + macSize;
12735
12736 /* These lengths are all public so we can test them in non-constant
12737 * time. */
12738 if (overhead > plaintext->len) {
12739 return SECFailure;
12740 }
12741
12742 paddingLength = plaintext->buf[plaintext->len - 1];
12743 good = PORT_CT_GE(plaintext->len, paddingLength + overhead);
12744
12745 /* The padding consists of a length byte at the end of the record and then
12746 * that many bytes of padding, all with the same value as the length byte.
12747 * Thus, with the length byte included, there are paddingLength+1 bytes of
12748 * padding.
12749 *
12750 * We can't check just |paddingLength+1| bytes because that leaks
12751 * decrypted information. Therefore we always have to check the maximum
12752 * amount of padding possible. (Again, the length of the record is
12753 * public information so we can use it.) */
12754 toCheck = 256; /* maximum amount of padding + 1. */
12755 if (toCheck > plaintext->len) {
12756 toCheck = plaintext->len;
12757 }
12758
12759 for (i = 0; i < toCheck; i++) {
12760 /* If i <= paddingLength then the MSB of t is zero and mask is
12761 * 0xff. Otherwise, mask is 0. */
12762 unsigned char mask = PORT_CT_LE(i, paddingLength);
12763 unsigned char b = plaintext->buf[plaintext->len - 1 - i];
12764 /* The final |paddingLength+1| bytes should all have the value
12765 * |paddingLength|. Therefore the XOR should be zero. */
12766 good &= ~(mask & (paddingLength ^ b));
12767 }
12768
12769 /* If any of the final |paddingLength+1| bytes had the wrong value,
12770 * one or more of the lower eight bits of |good| will be cleared. We
12771 * AND the bottom 8 bits together and duplicate the result to all the
12772 * bits. */
12773 good &= good >> 4;
12774 good &= good >> 2;
12775 good &= good >> 1;
12776 good <<= sizeof(good) * 8 - 1;
12777 good = PORT_CT_DUPLICATE_MSB_TO_ALL(good);
12778
12779 plaintext->len -= good & (paddingLength + 1);
12780 return (good & SECSuccess) | (~good & SECFailure);
12781 }
12782
12783 /* On entry:
12784 * originalLength >= macSize
12785 * macSize <= MAX_MAC_LENGTH
12786 * plaintext->len >= macSize
12787 */
12788 static void
ssl_CBCExtractMAC(sslBuffer * plaintext,unsigned int originalLength,PRUint8 * out,unsigned int macSize)12789 ssl_CBCExtractMAC(sslBuffer *plaintext,
12790 unsigned int originalLength,
12791 PRUint8 *out,
12792 unsigned int macSize)
12793 {
12794 unsigned char rotatedMac[MAX_MAC_LENGTH];
12795 /* macEnd is the index of |plaintext->buf| just after the end of the
12796 * MAC. */
12797 unsigned macEnd = plaintext->len;
12798 unsigned macStart = macEnd - macSize;
12799 /* scanStart contains the number of bytes that we can ignore because
12800 * the MAC's position can only vary by 255 bytes. */
12801 unsigned scanStart = 0;
12802 unsigned i, j;
12803 unsigned char rotateOffset;
12804
12805 if (originalLength > macSize + 255 + 1) {
12806 scanStart = originalLength - (macSize + 255 + 1);
12807 }
12808
12809 /* We want to compute
12810 * rotateOffset = (macStart - scanStart) % macSize
12811 * But the time to compute this varies based on the amount of padding. Thus
12812 * we explicitely handle all mac sizes with (hopefully) constant time modulo
12813 * using Barrett reduction:
12814 * q := (rotateOffset * m) >> k
12815 * rotateOffset -= q * n
12816 * if (n <= rotateOffset) rotateOffset -= n
12817 */
12818 rotateOffset = macStart - scanStart;
12819 /* rotateOffset < 255 + 1 + 48 = 304 */
12820 if (macSize == 16) {
12821 rotateOffset &= 15;
12822 } else if (macSize == 20) {
12823 /*
12824 * Correctness: rotateOffset * ( 1/20 - 25/2^9 ) < 1
12825 * with rotateOffset <= 853
12826 */
12827 unsigned q = (rotateOffset * 25) >> 9;
12828 rotateOffset -= q * 20;
12829 rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 20),
12830 20, 0);
12831 } else if (macSize == 32) {
12832 rotateOffset &= 31;
12833 } else if (macSize == 48) {
12834 /*
12835 * Correctness: rotateOffset * ( 1/48 - 10/2^9 ) < 1
12836 * with rotateOffset < 768
12837 */
12838 unsigned q = (rotateOffset * 10) >> 9;
12839 rotateOffset -= q * 48;
12840 rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 48),
12841 48, 0);
12842 } else {
12843 /*
12844 * SHA384 (macSize == 48) is the largest we support. We should never
12845 * get here.
12846 */
12847 PORT_Assert(0);
12848 rotateOffset = rotateOffset % macSize;
12849 }
12850
12851 memset(rotatedMac, 0, macSize);
12852 for (i = scanStart; i < originalLength;) {
12853 for (j = 0; j < macSize && i < originalLength; i++, j++) {
12854 unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
12855 unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
12856 unsigned char b = 0;
12857 b = plaintext->buf[i];
12858 rotatedMac[j] |= b & macStarted & ~macEnded;
12859 }
12860 }
12861
12862 /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
12863 * we could line-align |rotatedMac| and rotate in place. */
12864 memset(out, 0, macSize);
12865 rotateOffset = macSize - rotateOffset;
12866 rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
12867 0, rotateOffset);
12868 for (i = 0; i < macSize; i++) {
12869 for (j = 0; j < macSize; j++) {
12870 out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ(j, rotateOffset);
12871 }
12872 rotateOffset++;
12873 rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
12874 0, rotateOffset);
12875 }
12876 }
12877
12878 /* Unprotect an SSL3 record and leave the result in plaintext.
12879 *
12880 * If SECFailure is returned, we:
12881 * 1. Set |*alert| to the alert to be sent.
12882 * 2. Call PORT_SetError() with an appropriate code.
12883 *
12884 * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
12885 * Therefore, we MUST not call SSL3_SendAlert().
12886 *
12887 */
12888 static SECStatus
ssl3_UnprotectRecord(sslSocket * ss,ssl3CipherSpec * spec,SSL3Ciphertext * cText,sslBuffer * plaintext,SSL3AlertDescription * alert)12889 ssl3_UnprotectRecord(sslSocket *ss,
12890 ssl3CipherSpec *spec,
12891 SSL3Ciphertext *cText, sslBuffer *plaintext,
12892 SSL3AlertDescription *alert)
12893 {
12894 const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
12895 PRBool isTLS;
12896 unsigned int good;
12897 unsigned int ivLen = 0;
12898 SSLContentType rType;
12899 SSL3ProtocolVersion rVersion;
12900 unsigned int minLength;
12901 unsigned int originalLen = 0;
12902 PRUint8 headerBuf[13];
12903 sslBuffer header = SSL_BUFFER(headerBuf);
12904 PRUint8 hash[MAX_MAC_LENGTH];
12905 PRUint8 givenHashBuf[MAX_MAC_LENGTH];
12906 PRUint8 *givenHash;
12907 unsigned int hashBytes = MAX_MAC_LENGTH + 1;
12908 SECStatus rv;
12909
12910 PORT_Assert(spec->direction == ssl_secret_read);
12911
12912 good = ~0U;
12913 minLength = spec->macDef->mac_size;
12914 if (cipher_def->type == type_block) {
12915 /* CBC records have a padding length byte at the end. */
12916 minLength++;
12917 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
12918 /* With >= TLS 1.1, CBC records have an explicit IV. */
12919 minLength += cipher_def->iv_size;
12920 }
12921 } else if (cipher_def->type == type_aead) {
12922 minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
12923 }
12924
12925 /* We can perform this test in variable time because the record's total
12926 * length and the ciphersuite are both public knowledge. */
12927 if (cText->buf->len < minLength) {
12928 goto decrypt_loser;
12929 }
12930
12931 if (cipher_def->type == type_block &&
12932 spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
12933 /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
12934 * "The receiver decrypts the entire GenericBlockCipher structure and
12935 * then discards the first cipher block corresponding to the IV
12936 * component." Instead, we decrypt the first cipher block and then
12937 * discard it before decrypting the rest.
12938 */
12939 PRUint8 iv[MAX_IV_LENGTH];
12940 unsigned int decoded;
12941
12942 ivLen = cipher_def->iv_size;
12943 if (ivLen < 8 || ivLen > sizeof(iv)) {
12944 *alert = internal_error;
12945 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12946 return SECFailure;
12947 }
12948
12949 PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
12950
12951 /* The decryption result is garbage, but since we just throw away
12952 * the block it doesn't matter. The decryption of the next block
12953 * depends only on the ciphertext of the IV block.
12954 */
12955 rv = spec->cipher(spec->cipherContext, iv, &decoded,
12956 sizeof(iv), cText->buf->buf, ivLen);
12957
12958 good &= SECStatusToMask(rv);
12959 }
12960
12961 PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
12962 cText->buf->len - ivLen));
12963
12964 isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
12965
12966 if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) {
12967 *alert = record_overflow;
12968 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
12969 return SECFailure;
12970 }
12971
12972 rType = (SSLContentType)cText->hdr[0];
12973 rVersion = ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
12974 (SSL3ProtocolVersion)cText->hdr[2];
12975 if (cipher_def->type == type_aead) {
12976 /* XXX For many AEAD ciphers, the plaintext is shorter than the
12977 * ciphertext by a fixed byte count, but it is not true in general.
12978 * Each AEAD cipher should provide a function that returns the
12979 * plaintext length for a given ciphertext. */
12980 const unsigned int explicitNonceLen = cipher_def->explicit_nonce_size;
12981 const unsigned int tagLen = cipher_def->tag_size;
12982 unsigned int nonceLen = explicitNonceLen;
12983 unsigned int decryptedLen = cText->buf->len - nonceLen - tagLen;
12984 /* even though read doesn't return and IV, we still need a space to put
12985 * the combined iv/nonce n the gcm 1.2 case*/
12986 unsigned char ivOut[MAX_IV_LENGTH];
12987 unsigned char *iv = NULL;
12988 unsigned char *nonce = NULL;
12989
12990 ivLen = cipher_def->iv_size;
12991
12992 rv = ssl3_BuildRecordPseudoHeader(
12993 spec->epoch, cText->seqNum,
12994 rType, isTLS, rVersion, IS_DTLS(ss), decryptedLen, &header);
12995 PORT_Assert(rv == SECSuccess);
12996
12997 /* build the iv */
12998 if (explicitNonceLen == 0) {
12999 nonceLen = sizeof(cText->seqNum);
13000 iv = spec->keyMaterial.iv;
13001 nonce = SSL_BUFFER_BASE(&header);
13002 } else {
13003 PORT_Memcpy(ivOut, spec->keyMaterial.iv, ivLen);
13004 PORT_Memset(ivOut + ivLen, 0, explicitNonceLen);
13005 iv = ivOut;
13006 nonce = cText->buf->buf;
13007 nonceLen = explicitNonceLen;
13008 }
13009 rv = tls13_AEAD(spec->cipherContext, PR_TRUE,
13010 CKG_NO_GENERATE, 0, /* iv generator params
13011 * (not used in decrypt)*/
13012 iv, /* iv in */
13013 NULL, /* iv out */
13014 ivLen + explicitNonceLen, /* full iv length */
13015 nonce, nonceLen, /* nonce in */
13016 SSL_BUFFER_BASE(&header), /* aad */
13017 SSL_BUFFER_LEN(&header), /* aadlen */
13018 plaintext->buf, /* output */
13019 &plaintext->len, /* out len */
13020 plaintext->space, /* max out */
13021 tagLen,
13022 cText->buf->buf + explicitNonceLen, /* input */
13023 cText->buf->len - explicitNonceLen); /* input len */
13024 if (rv != SECSuccess) {
13025 good = 0;
13026 }
13027 } else {
13028 if (cipher_def->type == type_block &&
13029 ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
13030 goto decrypt_loser;
13031 }
13032
13033 /* decrypt from cText buf to plaintext. */
13034 rv = spec->cipher(
13035 spec->cipherContext, plaintext->buf, &plaintext->len,
13036 plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
13037 if (rv != SECSuccess) {
13038 goto decrypt_loser;
13039 }
13040
13041 PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
13042
13043 originalLen = plaintext->len;
13044
13045 /* If it's a block cipher, check and strip the padding. */
13046 if (cipher_def->type == type_block) {
13047 const unsigned int blockSize = cipher_def->block_size;
13048 const unsigned int macSize = spec->macDef->mac_size;
13049
13050 if (!isTLS) {
13051 good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
13052 plaintext, blockSize, macSize));
13053 } else {
13054 good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
13055 plaintext, macSize));
13056 }
13057 }
13058
13059 /* compute the MAC */
13060 rv = ssl3_BuildRecordPseudoHeader(
13061 spec->epoch, cText->seqNum,
13062 rType, isTLS, rVersion, IS_DTLS(ss),
13063 plaintext->len - spec->macDef->mac_size, &header);
13064 PORT_Assert(rv == SECSuccess);
13065 if (cipher_def->type == type_block) {
13066 rv = ssl3_ComputeRecordMACConstantTime(
13067 spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
13068 plaintext->buf, plaintext->len, originalLen,
13069 hash, &hashBytes);
13070
13071 ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
13072 spec->macDef->mac_size);
13073 givenHash = givenHashBuf;
13074
13075 /* plaintext->len will always have enough space to remove the MAC
13076 * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
13077 * plaintext->len if the result has enough space for the MAC and we
13078 * tested the unadjusted size against minLength, above. */
13079 plaintext->len -= spec->macDef->mac_size;
13080 } else {
13081 /* This is safe because we checked the minLength above. */
13082 plaintext->len -= spec->macDef->mac_size;
13083
13084 rv = ssl3_ComputeRecordMAC(
13085 spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
13086 plaintext->buf, plaintext->len, hash, &hashBytes);
13087
13088 /* We can read the MAC directly from the record because its location
13089 * is public when a stream cipher is used. */
13090 givenHash = plaintext->buf + plaintext->len;
13091 }
13092
13093 good &= SECStatusToMask(rv);
13094
13095 if (hashBytes != (unsigned)spec->macDef->mac_size ||
13096 NSS_SecureMemcmp(givenHash, hash, spec->macDef->mac_size) != 0) {
13097 /* We're allowed to leak whether or not the MAC check was correct */
13098 good = 0;
13099 }
13100 }
13101
13102 if (good == 0) {
13103 decrypt_loser:
13104 /* always log mac error, in case attacker can read server logs. */
13105 PORT_SetError(SSL_ERROR_BAD_MAC_READ);
13106 *alert = bad_record_mac;
13107 return SECFailure;
13108 }
13109 return SECSuccess;
13110 }
13111
13112 SECStatus
ssl3_HandleNonApplicationData(sslSocket * ss,SSLContentType rType,DTLSEpoch epoch,sslSequenceNumber seqNum,sslBuffer * databuf)13113 ssl3_HandleNonApplicationData(sslSocket *ss, SSLContentType rType,
13114 DTLSEpoch epoch, sslSequenceNumber seqNum,
13115 sslBuffer *databuf)
13116 {
13117 SECStatus rv;
13118
13119 /* check for Token Presence */
13120 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13121 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13122 return SECFailure;
13123 }
13124
13125 ssl_GetSSL3HandshakeLock(ss);
13126
13127 /* All the functions called in this switch MUST set error code if
13128 ** they return SECFailure.
13129 */
13130 switch (rType) {
13131 case ssl_ct_change_cipher_spec:
13132 rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
13133 break;
13134 case ssl_ct_alert:
13135 rv = ssl3_HandleAlert(ss, databuf);
13136 break;
13137 case ssl_ct_handshake:
13138 if (!IS_DTLS(ss)) {
13139 rv = ssl3_HandleHandshake(ss, databuf);
13140 } else {
13141 rv = dtls_HandleHandshake(ss, epoch, seqNum, databuf);
13142 }
13143 break;
13144 case ssl_ct_ack:
13145 if (IS_DTLS(ss) && tls13_MaybeTls13(ss)) {
13146 rv = dtls13_HandleAck(ss, databuf);
13147 break;
13148 }
13149 /* Fall through. */
13150 default:
13151 SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
13152 SSL_GETPID(), ss->fd, rType));
13153 PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
13154 ssl3_DecodeError(ss);
13155 rv = SECFailure;
13156 break;
13157 }
13158
13159 ssl_ReleaseSSL3HandshakeLock(ss);
13160 return rv;
13161 }
13162
13163 /* Find the cipher spec to use for a given record. For TLS, this
13164 * is the current cipherspec. For DTLS, we look up by epoch.
13165 * In DTLS < 1.3 this just means the current epoch or nothing,
13166 * but in DTLS >= 1.3, we keep multiple reading cipherspecs.
13167 * Returns NULL if no appropriate cipher spec is found.
13168 */
13169 static ssl3CipherSpec *
ssl3_GetCipherSpec(sslSocket * ss,SSL3Ciphertext * cText)13170 ssl3_GetCipherSpec(sslSocket *ss, SSL3Ciphertext *cText)
13171 {
13172 ssl3CipherSpec *crSpec = ss->ssl3.crSpec;
13173 ssl3CipherSpec *newSpec = NULL;
13174 DTLSEpoch epoch;
13175
13176 if (!IS_DTLS(ss)) {
13177 return crSpec;
13178 }
13179 epoch = dtls_ReadEpoch(crSpec, cText->hdr);
13180 if (crSpec->epoch == epoch) {
13181 return crSpec;
13182 }
13183 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
13184 /* Try to find the cipher spec. */
13185 newSpec = ssl_FindCipherSpecByEpoch(ss, ssl_secret_read,
13186 epoch);
13187 if (newSpec != NULL) {
13188 return newSpec;
13189 }
13190 }
13191 SSL_TRC(10, ("%d: DTLS[%d]: Couldn't find cipherspec from epoch %d",
13192 SSL_GETPID(), ss->fd, epoch));
13193 return NULL;
13194 }
13195
13196 /* MAX_EXPANSION is the amount by which a record might plausibly be expanded
13197 * when protected. It's the worst case estimate, so the sum of block cipher
13198 * padding (up to 256 octets), HMAC (48 octets for SHA-384), and IV (16
13199 * octets for AES). */
13200 #define MAX_EXPANSION (256 + 48 + 16)
13201
13202 /* if cText is non-null, then decipher and check the MAC of the
13203 * SSL record from cText->buf (typically gs->inbuf)
13204 * into databuf (typically gs->buf), and any previous contents of databuf
13205 * is lost. Then handle databuf according to its SSL record type,
13206 * unless it's an application record.
13207 *
13208 * If cText is NULL, then the ciphertext has previously been deciphered and
13209 * checked, and is already sitting in databuf. It is processed as an SSL
13210 * Handshake message.
13211 *
13212 * DOES NOT process the decrypted application data.
13213 * On return, databuf contains the decrypted record.
13214 *
13215 * Called from ssl3_GatherCompleteHandshake
13216 * ssl3_RestartHandshakeAfterCertReq
13217 *
13218 * Caller must hold the RecvBufLock.
13219 *
13220 * This function aquires and releases the SSL3Handshake Lock, holding the
13221 * lock around any calls to functions that handle records other than
13222 * Application Data records.
13223 */
13224 SECStatus
ssl3_HandleRecord(sslSocket * ss,SSL3Ciphertext * cText)13225 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText)
13226 {
13227 SECStatus rv;
13228 PRBool isTLS;
13229 DTLSEpoch epoch;
13230 ssl3CipherSpec *spec = NULL;
13231 PRUint16 recordSizeLimit;
13232 PRBool outOfOrderSpec = PR_FALSE;
13233 SSLContentType rType;
13234 sslBuffer *plaintext = &ss->gs.buf;
13235 SSL3AlertDescription alert = internal_error;
13236 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
13237
13238 /* check for Token Presence */
13239 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13240 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13241 return SECFailure;
13242 }
13243
13244 /* Clear out the buffer in case this exits early. Any data then won't be
13245 * processed twice. */
13246 plaintext->len = 0;
13247
13248 /* We're waiting for another ClientHello, which will appear unencrypted.
13249 * Use the content type to tell whether this should be discarded. */
13250 if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr &&
13251 cText->hdr[0] == ssl_ct_application_data) {
13252 PORT_Assert(ss->ssl3.hs.ws == wait_client_hello);
13253 return SECSuccess;
13254 }
13255
13256 ssl_GetSpecReadLock(ss); /******************************************/
13257 spec = ssl3_GetCipherSpec(ss, cText);
13258 if (!spec) {
13259 PORT_Assert(IS_DTLS(ss));
13260 ssl_ReleaseSpecReadLock(ss); /*****************************/
13261 return SECSuccess;
13262 }
13263 if (spec != ss->ssl3.crSpec) {
13264 PORT_Assert(IS_DTLS(ss));
13265 SSL_TRC(3, ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d",
13266 SSL_GETPID(), ss->fd, spec->epoch));
13267 outOfOrderSpec = PR_TRUE;
13268 }
13269 isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
13270 if (IS_DTLS(ss)) {
13271 if (dtls13_MaskSequenceNumber(ss, spec, cText->hdr,
13272 SSL_BUFFER_BASE(cText->buf), SSL_BUFFER_LEN(cText->buf)) != SECSuccess) {
13273 ssl_ReleaseSpecReadLock(ss); /*****************************/
13274 /* code already set. */
13275 return SECFailure;
13276 }
13277 if (!dtls_IsRelevant(ss, spec, cText, &cText->seqNum)) {
13278 ssl_ReleaseSpecReadLock(ss); /*****************************/
13279 return SECSuccess;
13280 }
13281 } else {
13282 cText->seqNum = spec->nextSeqNum;
13283 }
13284 if (cText->seqNum >= spec->cipherDef->max_records) {
13285 ssl_ReleaseSpecReadLock(ss); /*****************************/
13286 SSL_TRC(3, ("%d: SSL[%d]: read sequence number at limit 0x%0llx",
13287 SSL_GETPID(), ss->fd, cText->seqNum));
13288 PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
13289 return SECFailure;
13290 }
13291
13292 recordSizeLimit = spec->recordSizeLimit;
13293 if (cText->buf->len > recordSizeLimit + MAX_EXPANSION) {
13294 ssl_ReleaseSpecReadLock(ss); /*****************************/
13295 SSL3_SendAlert(ss, alert_fatal, record_overflow);
13296 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13297 return SECFailure;
13298 }
13299
13300 if (plaintext->space < recordSizeLimit + MAX_EXPANSION) {
13301 rv = sslBuffer_Grow(plaintext, recordSizeLimit + MAX_EXPANSION);
13302 if (rv != SECSuccess) {
13303 ssl_ReleaseSpecReadLock(ss); /*************************/
13304 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
13305 SSL_GETPID(), ss->fd, recordSizeLimit + MAX_EXPANSION));
13306 /* sslBuffer_Grow has set a memory error code. */
13307 /* Perhaps we should send an alert. (but we have no memory!) */
13308 return SECFailure;
13309 }
13310 }
13311
13312 /* Most record types aside from protected TLS 1.3 records carry the content
13313 * type in the first octet. TLS 1.3 will override this value later. */
13314 rType = cText->hdr[0];
13315 /* Encrypted application data records could arrive before the handshake
13316 * completes in DTLS 1.3. These can look like valid TLS 1.2 application_data
13317 * records in epoch 0, which is never valid. Pretend they didn't decrypt. */
13318
13319 if (spec->epoch == 0 && ((IS_DTLS(ss) &&
13320 dtls_IsDtls13Ciphertext(0, rType)) ||
13321 rType == ssl_ct_application_data)) {
13322 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
13323 alert = unexpected_message;
13324 rv = SECFailure;
13325 } else {
13326 #ifdef UNSAFE_FUZZER_MODE
13327 rv = Null_Cipher(NULL, plaintext->buf, &plaintext->len,
13328 plaintext->space, cText->buf->buf, cText->buf->len);
13329 #else
13330 /* IMPORTANT: Unprotect functions MUST NOT send alerts
13331 * because we still hold the spec read lock. Instead, if they
13332 * return SECFailure, they set *alert to the alert to be sent. */
13333 if (spec->version < SSL_LIBRARY_VERSION_TLS_1_3 ||
13334 spec->epoch == 0) {
13335 rv = ssl3_UnprotectRecord(ss, spec, cText, plaintext, &alert);
13336 } else {
13337 rv = tls13_UnprotectRecord(ss, spec, cText, plaintext, &rType,
13338 &alert);
13339 }
13340 #endif
13341 }
13342
13343 if (rv != SECSuccess) {
13344 ssl_ReleaseSpecReadLock(ss); /***************************/
13345
13346 SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
13347
13348 /* Ensure that we don't process this data again. */
13349 plaintext->len = 0;
13350
13351 /* Ignore a CCS if compatibility mode is negotiated. Note that this
13352 * will fail if the server fails to negotiate compatibility mode in a
13353 * 0-RTT session that is resumed from a session that did negotiate it.
13354 * We don't care about that corner case right now. */
13355 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
13356 cText->hdr[0] == ssl_ct_change_cipher_spec &&
13357 ss->ssl3.hs.ws != idle_handshake &&
13358 cText->buf->len == 1 &&
13359 cText->buf->buf[0] == change_cipher_spec_choice) {
13360 if (!ss->ssl3.hs.rejectCcs) {
13361 /* Allow only the first CCS. */
13362 ss->ssl3.hs.rejectCcs = PR_TRUE;
13363 return SECSuccess;
13364 } else {
13365 alert = unexpected_message;
13366 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
13367 }
13368 }
13369
13370 if ((IS_DTLS(ss) && !dtls13_AeadLimitReached(spec)) ||
13371 (!IS_DTLS(ss) && ss->sec.isServer &&
13372 ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_trial)) {
13373 /* Silently drop the packet unless we sent a fatal alert. */
13374 if (ss->ssl3.fatalAlertSent) {
13375 return SECFailure;
13376 }
13377 return SECSuccess;
13378 }
13379
13380 int errCode = PORT_GetError();
13381 SSL3_SendAlert(ss, alert_fatal, alert);
13382 /* Reset the error code in case SSL3_SendAlert called
13383 * PORT_SetError(). */
13384 PORT_SetError(errCode);
13385 return SECFailure;
13386 }
13387
13388 /* SECSuccess */
13389 if (IS_DTLS(ss)) {
13390 dtls_RecordSetRecvd(&spec->recvdRecords, cText->seqNum);
13391 spec->nextSeqNum = PR_MAX(spec->nextSeqNum, cText->seqNum + 1);
13392 } else {
13393 ++spec->nextSeqNum;
13394 }
13395 epoch = spec->epoch;
13396
13397 ssl_ReleaseSpecReadLock(ss); /*****************************************/
13398
13399 /*
13400 * The decrypted data is now in plaintext.
13401 */
13402
13403 /* IMPORTANT: We are in DTLS 1.3 mode and we have processed something
13404 * from the wrong epoch. Divert to a divert processing function to make
13405 * sure we don't accidentally use the data unsafely. */
13406 if (outOfOrderSpec) {
13407 PORT_Assert(IS_DTLS(ss) && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
13408 return dtls13_HandleOutOfEpochRecord(ss, spec, rType, plaintext);
13409 }
13410
13411 /* Check the length of the plaintext. */
13412 if (isTLS && plaintext->len > recordSizeLimit) {
13413 plaintext->len = 0;
13414 SSL3_SendAlert(ss, alert_fatal, record_overflow);
13415 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13416 return SECFailure;
13417 }
13418
13419 /* Application data records are processed by the caller of this
13420 ** function, not by this function.
13421 */
13422 if (rType == ssl_ct_application_data) {
13423 if (ss->firstHsDone)
13424 return SECSuccess;
13425 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
13426 ss->sec.isServer &&
13427 ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
13428 return tls13_HandleEarlyApplicationData(ss, plaintext);
13429 }
13430 plaintext->len = 0;
13431 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13432 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
13433 return SECFailure;
13434 }
13435
13436 return ssl3_HandleNonApplicationData(ss, rType, epoch, cText->seqNum,
13437 plaintext);
13438 }
13439
13440 /*
13441 * Initialization functions
13442 */
13443
13444 void
ssl_InitSecState(sslSecurityInfo * sec)13445 ssl_InitSecState(sslSecurityInfo *sec)
13446 {
13447 sec->authType = ssl_auth_null;
13448 sec->authKeyBits = 0;
13449 sec->signatureScheme = ssl_sig_none;
13450 sec->keaType = ssl_kea_null;
13451 sec->keaKeyBits = 0;
13452 sec->keaGroup = NULL;
13453 }
13454
13455 SECStatus
ssl3_InitState(sslSocket * ss)13456 ssl3_InitState(sslSocket *ss)
13457 {
13458 SECStatus rv;
13459
13460 ss->ssl3.policy = SSL_ALLOWED;
13461
13462 ssl_InitSecState(&ss->sec);
13463
13464 ssl_GetSpecWriteLock(ss);
13465 PR_INIT_CLIST(&ss->ssl3.hs.cipherSpecs);
13466 rv = ssl_SetupNullCipherSpec(ss, ssl_secret_read);
13467 rv |= ssl_SetupNullCipherSpec(ss, ssl_secret_write);
13468 ss->ssl3.pwSpec = ss->ssl3.prSpec = NULL;
13469 ssl_ReleaseSpecWriteLock(ss);
13470 if (rv != SECSuccess) {
13471 /* Rely on ssl_CreateNullCipherSpec() to set error code. */
13472 return SECFailure;
13473 }
13474
13475 ss->ssl3.hs.sendingSCSV = PR_FALSE;
13476 ss->ssl3.hs.preliminaryInfo = 0;
13477 ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : idle_handshake;
13478
13479 ssl3_ResetExtensionData(&ss->xtnData, ss);
13480 PR_INIT_CLIST(&ss->ssl3.hs.remoteExtensions);
13481 PR_INIT_CLIST(&ss->ssl3.hs.echOuterExtensions);
13482 if (IS_DTLS(ss)) {
13483 ss->ssl3.hs.sendMessageSeq = 0;
13484 ss->ssl3.hs.recvMessageSeq = 0;
13485 ss->ssl3.hs.rtTimer->timeout = DTLS_RETRANSMIT_INITIAL_MS;
13486 ss->ssl3.hs.rtRetries = 0;
13487 ss->ssl3.hs.recvdHighWater = -1;
13488 PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
13489 dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
13490 }
13491
13492 ss->ssl3.hs.currentSecret = NULL;
13493 ss->ssl3.hs.resumptionMasterSecret = NULL;
13494 ss->ssl3.hs.dheSecret = NULL;
13495 ss->ssl3.hs.clientEarlyTrafficSecret = NULL;
13496 ss->ssl3.hs.clientHsTrafficSecret = NULL;
13497 ss->ssl3.hs.serverHsTrafficSecret = NULL;
13498 ss->ssl3.hs.clientTrafficSecret = NULL;
13499 ss->ssl3.hs.serverTrafficSecret = NULL;
13500 ss->ssl3.hs.echHpkeCtx = NULL;
13501 ss->ssl3.hs.echAccepted = PR_FALSE;
13502
13503 PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
13504 ss->ssl3.hs.messages.buf = NULL;
13505 ss->ssl3.hs.messages.space = 0;
13506
13507 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
13508 PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0,
13509 sizeof(ss->ssl3.hs.newSessionTicket));
13510
13511 ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
13512
13513 return SECSuccess;
13514 }
13515
13516 /* record the export policy for this cipher suite */
13517 SECStatus
ssl3_SetPolicy(ssl3CipherSuite which,int policy)13518 ssl3_SetPolicy(ssl3CipherSuite which, int policy)
13519 {
13520 ssl3CipherSuiteCfg *suite;
13521
13522 suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
13523 if (suite == NULL) {
13524 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13525 }
13526 suite->policy = policy;
13527
13528 return SECSuccess;
13529 }
13530
13531 SECStatus
ssl3_GetPolicy(ssl3CipherSuite which,PRInt32 * oPolicy)13532 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
13533 {
13534 const ssl3CipherSuiteCfg *suite;
13535 PRInt32 policy;
13536 SECStatus rv;
13537
13538 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13539 if (suite) {
13540 policy = suite->policy;
13541 rv = SECSuccess;
13542 } else {
13543 policy = SSL_NOT_ALLOWED;
13544 rv = SECFailure; /* err code was set by Lookup. */
13545 }
13546 *oPolicy = policy;
13547 return rv;
13548 }
13549
13550 /* record the user preference for this suite */
13551 SECStatus
ssl3_CipherPrefSetDefault(ssl3CipherSuite which,PRBool enabled)13552 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
13553 {
13554 ssl3CipherSuiteCfg *suite;
13555
13556 suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
13557 if (suite == NULL) {
13558 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13559 }
13560 suite->enabled = enabled;
13561 return SECSuccess;
13562 }
13563
13564 /* return the user preference for this suite */
13565 SECStatus
ssl3_CipherPrefGetDefault(ssl3CipherSuite which,PRBool * enabled)13566 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
13567 {
13568 const ssl3CipherSuiteCfg *suite;
13569 PRBool pref;
13570 SECStatus rv;
13571
13572 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13573 if (suite) {
13574 pref = suite->enabled;
13575 rv = SECSuccess;
13576 } else {
13577 pref = SSL_NOT_ALLOWED;
13578 rv = SECFailure; /* err code was set by Lookup. */
13579 }
13580 *enabled = pref;
13581 return rv;
13582 }
13583
13584 SECStatus
ssl3_CipherPrefSet(sslSocket * ss,ssl3CipherSuite which,PRBool enabled)13585 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
13586 {
13587 ssl3CipherSuiteCfg *suite;
13588
13589 suite = ssl_LookupCipherSuiteCfgMutable(which, ss->cipherSuites);
13590 if (suite == NULL) {
13591 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13592 }
13593 suite->enabled = enabled;
13594 return SECSuccess;
13595 }
13596
13597 SECStatus
ssl3_CipherPrefGet(const sslSocket * ss,ssl3CipherSuite which,PRBool * enabled)13598 ssl3_CipherPrefGet(const sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
13599 {
13600 const ssl3CipherSuiteCfg *suite;
13601 PRBool pref;
13602 SECStatus rv;
13603
13604 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
13605 if (suite) {
13606 pref = suite->enabled;
13607 rv = SECSuccess;
13608 } else {
13609 pref = SSL_NOT_ALLOWED;
13610 rv = SECFailure; /* err code was set by Lookup. */
13611 }
13612 *enabled = pref;
13613 return rv;
13614 }
13615
13616 SECStatus
SSL_SignatureSchemePrefSet(PRFileDesc * fd,const SSLSignatureScheme * schemes,unsigned int count)13617 SSL_SignatureSchemePrefSet(PRFileDesc *fd, const SSLSignatureScheme *schemes,
13618 unsigned int count)
13619 {
13620 sslSocket *ss;
13621 unsigned int i;
13622 unsigned int supported = 0;
13623
13624 ss = ssl_FindSocket(fd);
13625 if (!ss) {
13626 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefSet",
13627 SSL_GETPID(), fd));
13628 PORT_SetError(SEC_ERROR_INVALID_ARGS);
13629 return SECFailure;
13630 }
13631
13632 if (!count) {
13633 PORT_SetError(SEC_ERROR_INVALID_ARGS);
13634 return SECFailure;
13635 }
13636
13637 for (i = 0; i < count; ++i) {
13638 if (ssl_IsSupportedSignatureScheme(schemes[i])) {
13639 ++supported;
13640 }
13641 }
13642 /* We don't check for duplicates, so it's possible to get too many. */
13643 if (supported > MAX_SIGNATURE_SCHEMES) {
13644 PORT_SetError(SEC_ERROR_INVALID_ARGS);
13645 return SECFailure;
13646 }
13647
13648 ss->ssl3.signatureSchemeCount = 0;
13649 for (i = 0; i < count; ++i) {
13650 if (!ssl_IsSupportedSignatureScheme(schemes[i])) {
13651 SSL_DBG(("%d: SSL[%d]: invalid signature scheme %d ignored",
13652 SSL_GETPID(), fd, schemes[i]));
13653 continue;
13654 }
13655
13656 ss->ssl3.signatureSchemes[ss->ssl3.signatureSchemeCount++] = schemes[i];
13657 }
13658
13659 if (ss->ssl3.signatureSchemeCount == 0) {
13660 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
13661 return SECFailure;
13662 }
13663 return SECSuccess;
13664 }
13665
13666 SECStatus
SSL_SignaturePrefSet(PRFileDesc * fd,const SSLSignatureAndHashAlg * algorithms,unsigned int count)13667 SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms,
13668 unsigned int count)
13669 {
13670 SSLSignatureScheme schemes[MAX_SIGNATURE_SCHEMES];
13671 unsigned int i;
13672
13673 count = PR_MIN(PR_ARRAY_SIZE(schemes), count);
13674 for (i = 0; i < count; ++i) {
13675 schemes[i] = (algorithms[i].hashAlg << 8) | algorithms[i].sigAlg;
13676 }
13677 return SSL_SignatureSchemePrefSet(fd, schemes, count);
13678 }
13679
13680 SECStatus
SSL_SignatureSchemePrefGet(PRFileDesc * fd,SSLSignatureScheme * schemes,unsigned int * count,unsigned int maxCount)13681 SSL_SignatureSchemePrefGet(PRFileDesc *fd, SSLSignatureScheme *schemes,
13682 unsigned int *count, unsigned int maxCount)
13683 {
13684 sslSocket *ss;
13685
13686 ss = ssl_FindSocket(fd);
13687 if (!ss) {
13688 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefGet",
13689 SSL_GETPID(), fd));
13690 PORT_SetError(SEC_ERROR_INVALID_ARGS);
13691 return SECFailure;
13692 }
13693
13694 if (!schemes || !count ||
13695 maxCount < ss->ssl3.signatureSchemeCount) {
13696 PORT_SetError(SEC_ERROR_INVALID_ARGS);
13697 return SECFailure;
13698 }
13699
13700 PORT_Memcpy(schemes, ss->ssl3.signatureSchemes,
13701 ss->ssl3.signatureSchemeCount * sizeof(SSLSignatureScheme));
13702 *count = ss->ssl3.signatureSchemeCount;
13703 return SECSuccess;
13704 }
13705
13706 SECStatus
SSL_SignaturePrefGet(PRFileDesc * fd,SSLSignatureAndHashAlg * algorithms,unsigned int * count,unsigned int maxCount)13707 SSL_SignaturePrefGet(PRFileDesc *fd, SSLSignatureAndHashAlg *algorithms,
13708 unsigned int *count, unsigned int maxCount)
13709 {
13710 sslSocket *ss;
13711 unsigned int i;
13712
13713 ss = ssl_FindSocket(fd);
13714 if (!ss) {
13715 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignaturePrefGet",
13716 SSL_GETPID(), fd));
13717 PORT_SetError(SEC_ERROR_INVALID_ARGS);
13718 return SECFailure;
13719 }
13720
13721 if (!algorithms || !count ||
13722 maxCount < ss->ssl3.signatureSchemeCount) {
13723 PORT_SetError(SEC_ERROR_INVALID_ARGS);
13724 return SECFailure;
13725 }
13726
13727 for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
13728 algorithms[i].hashAlg = (ss->ssl3.signatureSchemes[i] >> 8) & 0xff;
13729 algorithms[i].sigAlg = ss->ssl3.signatureSchemes[i] & 0xff;
13730 }
13731 *count = ss->ssl3.signatureSchemeCount;
13732 return SECSuccess;
13733 }
13734
13735 unsigned int
SSL_SignatureMaxCount(void)13736 SSL_SignatureMaxCount(void)
13737 {
13738 return MAX_SIGNATURE_SCHEMES;
13739 }
13740
13741 /* copy global default policy into socket. */
13742 void
ssl3_InitSocketPolicy(sslSocket * ss)13743 ssl3_InitSocketPolicy(sslSocket *ss)
13744 {
13745 PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof(cipherSuites));
13746 PORT_Memcpy(ss->ssl3.signatureSchemes, defaultSignatureSchemes,
13747 sizeof(defaultSignatureSchemes));
13748 ss->ssl3.signatureSchemeCount = PR_ARRAY_SIZE(defaultSignatureSchemes);
13749 }
13750
13751 /*
13752 ** If ssl3 socket has completed the first handshake, and is in idle state,
13753 ** then start a new handshake.
13754 ** If flushCache is true, the SID cache will be flushed first, forcing a
13755 ** "Full" handshake (not a session restart handshake), to be done.
13756 **
13757 ** called from SSL_RedoHandshake(), which already holds the handshake locks.
13758 */
13759 SECStatus
ssl3_RedoHandshake(sslSocket * ss,PRBool flushCache)13760 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
13761 {
13762 sslSessionID *sid = ss->sec.ci.sid;
13763 SECStatus rv;
13764
13765 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
13766
13767 if (!ss->firstHsDone || (ss->ssl3.hs.ws != idle_handshake)) {
13768 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
13769 return SECFailure;
13770 }
13771
13772 if (IS_DTLS(ss)) {
13773 dtls_RehandshakeCleanup(ss);
13774 }
13775
13776 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER ||
13777 ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
13778 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
13779 return SECFailure;
13780 }
13781 if (ss->version > ss->vrange.max || ss->version < ss->vrange.min) {
13782 PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
13783 return SECFailure;
13784 }
13785
13786 if (sid && flushCache) {
13787 ssl_UncacheSessionID(ss); /* remove it from whichever cache it's in. */
13788 ssl_FreeSID(sid); /* dec ref count and free if zero. */
13789 ss->sec.ci.sid = NULL;
13790 }
13791
13792 ssl_GetXmitBufLock(ss); /**************************************/
13793
13794 /* start off a new handshake. */
13795 if (ss->sec.isServer) {
13796 rv = ssl3_SendHelloRequest(ss);
13797 } else {
13798 rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
13799 }
13800
13801 ssl_ReleaseXmitBufLock(ss); /**************************************/
13802 return rv;
13803 }
13804
13805 /* Called from ssl_DestroySocketContents() in sslsock.c */
13806 void
ssl3_DestroySSL3Info(sslSocket * ss)13807 ssl3_DestroySSL3Info(sslSocket *ss)
13808 {
13809
13810 if (ss->ssl3.clientCertificate != NULL)
13811 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
13812
13813 if (ss->ssl3.clientPrivateKey != NULL)
13814 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
13815
13816 if (ss->ssl3.peerCertArena != NULL)
13817 ssl3_CleanupPeerCerts(ss);
13818
13819 if (ss->ssl3.clientCertChain != NULL) {
13820 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
13821 ss->ssl3.clientCertChain = NULL;
13822 }
13823 if (ss->ssl3.ca_list) {
13824 CERT_FreeDistNames(ss->ssl3.ca_list);
13825 }
13826
13827 /* clean up handshake */
13828 if (ss->ssl3.hs.md5) {
13829 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
13830 }
13831 if (ss->ssl3.hs.sha) {
13832 PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
13833 }
13834 if (ss->ssl3.hs.shaEchInner) {
13835 PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
13836 }
13837 if (ss->ssl3.hs.shaPostHandshake) {
13838 PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
13839 }
13840 if (ss->ssl3.hs.messages.buf) {
13841 sslBuffer_Clear(&ss->ssl3.hs.messages);
13842 }
13843 if (ss->ssl3.hs.echInnerMessages.buf) {
13844 sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
13845 }
13846
13847 /* free the SSL3Buffer (msg_body) */
13848 PORT_Free(ss->ssl3.hs.msg_body.buf);
13849
13850 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
13851 SECITEM_FreeItem(&ss->ssl3.hs.srvVirtName, PR_FALSE);
13852 SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
13853
13854 /* Destroy the DTLS data */
13855 if (IS_DTLS(ss)) {
13856 dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
13857 if (ss->ssl3.hs.recvdFragments.buf) {
13858 PORT_Free(ss->ssl3.hs.recvdFragments.buf);
13859 }
13860 }
13861
13862 /* Destroy remote extensions */
13863 ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
13864 ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.echOuterExtensions);
13865 ssl3_DestroyExtensionData(&ss->xtnData);
13866
13867 /* Destroy cipher specs */
13868 ssl_DestroyCipherSpecs(&ss->ssl3.hs.cipherSpecs);
13869
13870 /* Destroy TLS 1.3 keys */
13871 if (ss->ssl3.hs.currentSecret)
13872 PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
13873 if (ss->ssl3.hs.resumptionMasterSecret)
13874 PK11_FreeSymKey(ss->ssl3.hs.resumptionMasterSecret);
13875 if (ss->ssl3.hs.dheSecret)
13876 PK11_FreeSymKey(ss->ssl3.hs.dheSecret);
13877 if (ss->ssl3.hs.clientEarlyTrafficSecret)
13878 PK11_FreeSymKey(ss->ssl3.hs.clientEarlyTrafficSecret);
13879 if (ss->ssl3.hs.clientHsTrafficSecret)
13880 PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
13881 if (ss->ssl3.hs.serverHsTrafficSecret)
13882 PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
13883 if (ss->ssl3.hs.clientTrafficSecret)
13884 PK11_FreeSymKey(ss->ssl3.hs.clientTrafficSecret);
13885 if (ss->ssl3.hs.serverTrafficSecret)
13886 PK11_FreeSymKey(ss->ssl3.hs.serverTrafficSecret);
13887 if (ss->ssl3.hs.earlyExporterSecret)
13888 PK11_FreeSymKey(ss->ssl3.hs.earlyExporterSecret);
13889 if (ss->ssl3.hs.exporterSecret)
13890 PK11_FreeSymKey(ss->ssl3.hs.exporterSecret);
13891
13892 ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
13893 /* Destroy TLS 1.3 buffered early data. */
13894 tls13_DestroyEarlyData(&ss->ssl3.hs.bufferedEarlyData);
13895
13896 /* Destroy TLS 1.3 PSKs. */
13897 tls13_DestroyPskList(&ss->ssl3.hs.psks);
13898
13899 /* TLS 1.3 ECH state. */
13900 PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE);
13901 PORT_Free((void *)ss->ssl3.hs.echPublicName); /* CONST */
13902 sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
13903 }
13904
13905 /* check if the current cipher spec is FIPS. We only need to
13906 * check the contexts here, if the kea, prf or keys were not FIPS,
13907 * that status would have been rolled up in the create context
13908 * call */
13909 static PRBool
ssl_cipherSpecIsFips(ssl3CipherSpec * spec)13910 ssl_cipherSpecIsFips(ssl3CipherSpec *spec)
13911 {
13912 if (!spec || !spec->cipherDef) {
13913 return PR_FALSE;
13914 }
13915
13916 if (spec->cipherDef->type != type_aead) {
13917 if (spec->keyMaterial.macContext == NULL) {
13918 return PR_FALSE;
13919 }
13920 if (!PK11_ContextGetFIPSStatus(spec->keyMaterial.macContext)) {
13921 return PR_FALSE;
13922 }
13923 }
13924 if (!spec->cipherContext) {
13925 return PR_FALSE;
13926 }
13927 return PK11_ContextGetFIPSStatus(spec->cipherContext);
13928 }
13929
13930 /* return true if the current operation is running in FIPS mode */
13931 PRBool
ssl_isFIPS(sslSocket * ss)13932 ssl_isFIPS(sslSocket *ss)
13933 {
13934 if (!ssl_cipherSpecIsFips(ss->ssl3.crSpec)) {
13935 return PR_FALSE;
13936 }
13937 return ssl_cipherSpecIsFips(ss->ssl3.cwSpec);
13938 }
13939
13940 /*
13941 * parse the policy value for a single algorithm in a cipher_suite,
13942 * return TRUE if we disallow by the cipher suite by policy
13943 * (we don't have to parse any more algorithm policies on this cipher suite),
13944 * otherwise return FALSE.
13945 * 1. If we don't have the required policy, disable by default, disallow by
13946 * policy and return TRUE (no more processing needed).
13947 * 2. If we have the required policy, and we are disabled, return FALSE,
13948 * (if we are disabled, we only need to parse policy, not default).
13949 * 3. If we have the required policy, and we aren't adjusting the defaults
13950 * return FALSE. (only parsing the policy, not default).
13951 * 4. We have the required policy and we are adjusting the defaults.
13952 * If we are setting default = FALSE, set isDisabled to true so that
13953 * we don't try to re-enable the cipher suite based on a different
13954 * algorithm.
13955 */
13956 PRBool
ssl_HandlePolicy(int cipher_suite,SECOidTag policyOid,PRUint32 requiredPolicy,PRBool * isDisabled)13957 ssl_HandlePolicy(int cipher_suite, SECOidTag policyOid,
13958 PRUint32 requiredPolicy, PRBool *isDisabled)
13959 {
13960 PRUint32 policy;
13961 SECStatus rv;
13962
13963 /* first fetch the policy for this algorithm */
13964 rv = NSS_GetAlgorithmPolicy(policyOid, &policy);
13965 if (rv != SECSuccess) {
13966 return PR_FALSE; /* no policy value, continue to the next algorithm */
13967 }
13968 /* first, are we allowed by policy, if not turn off allow and disable */
13969 if (!(policy & requiredPolicy)) {
13970 ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE);
13971 ssl_CipherPolicySet(cipher_suite, SSL_NOT_ALLOWED);
13972 return PR_TRUE;
13973 }
13974 /* If we are already disabled, or the policy isn't setting a default
13975 * we are done processing this algorithm */
13976 if (*isDisabled || (policy & NSS_USE_DEFAULT_NOT_VALID)) {
13977 return PR_FALSE;
13978 }
13979 /* set the default value for the cipher suite. If we disable the cipher
13980 * suite, remember that so we don't process the next default. This has
13981 * the effect of disabling the whole cipher suite if any of the
13982 * algorithms it uses are disabled by default. We still have to
13983 * process the upper level because the cipher suite is still allowed
13984 * by policy, and we may still have to disallow it based on other
13985 * algorithms in the cipher suite. */
13986 if (policy & NSS_USE_DEFAULT_SSL_ENABLE) {
13987 ssl_CipherPrefSetDefault(cipher_suite, PR_TRUE);
13988 } else {
13989 *isDisabled = PR_TRUE;
13990 ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE);
13991 }
13992 return PR_FALSE;
13993 }
13994
13995 #define MAP_NULL(x) (((x) != 0) ? (x) : SEC_OID_NULL_CIPHER)
13996
13997 SECStatus
ssl3_ApplyNSSPolicy(void)13998 ssl3_ApplyNSSPolicy(void)
13999 {
14000 unsigned i;
14001 SECStatus rv;
14002 PRUint32 policy = 0;
14003
14004 rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy);
14005 if (rv != SECSuccess || !(policy & NSS_USE_POLICY_IN_SSL)) {
14006 return SECSuccess; /* do nothing */
14007 }
14008
14009 /* disable every ciphersuite */
14010 for (i = 1; i < PR_ARRAY_SIZE(cipher_suite_defs); ++i) {
14011 const ssl3CipherSuiteDef *suite = &cipher_suite_defs[i];
14012 SECOidTag policyOid;
14013 PRBool isDisabled = PR_FALSE;
14014
14015 /* if we haven't explicitly disabled it below enable by policy */
14016 ssl_CipherPolicySet(suite->cipher_suite, SSL_ALLOWED);
14017
14018 /* now check the various key exchange, ciphers and macs and
14019 * if we ever disallow by policy, we are done, go to the next cipher
14020 */
14021 policyOid = MAP_NULL(kea_defs[suite->key_exchange_alg].oid);
14022 if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14023 NSS_USE_ALG_IN_SSL_KX, &isDisabled)) {
14024 continue;
14025 }
14026
14027 policyOid = MAP_NULL(ssl_GetBulkCipherDef(suite)->oid);
14028 if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14029 NSS_USE_ALG_IN_SSL, &isDisabled)) {
14030 continue;
14031 }
14032
14033 if (ssl_GetBulkCipherDef(suite)->type != type_aead) {
14034 policyOid = MAP_NULL(ssl_GetMacDefByAlg(suite->mac_alg)->oid);
14035 if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14036 NSS_USE_ALG_IN_SSL, &isDisabled)) {
14037 continue;
14038 }
14039 }
14040 }
14041
14042 rv = ssl3_ConstrainRangeByPolicy();
14043
14044 return rv;
14045 }
14046
14047 /* End of ssl3con.c */
14048