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->vrange.min < 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 *)&params;
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, &param,
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, &params,
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, &params,
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, &params,
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, &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, &params);
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         /* Directly copy the extensions */
9813         rv = sslBuffer_AppendBufferVariable(messageBuf, extensionBuf, 2);
9814         if (rv != SECSuccess) {
9815             return SECFailure;
9816         }
9817     }
9818 
9819     if (ss->xtnData.ech && ss->xtnData.ech->receivedInnerXtn) {
9820         /* Signal ECH acceptance if we handled handled both CHOuter/CHInner (i.e.
9821          * in shared mode), or if we received a CHInner in split/backend mode. */
9822         if (ss->ssl3.hs.echAccepted || ss->opt.enableTls13BackendEch) {
9823             if (helloRetry) {
9824                 return tls13_WriteServerEchHrrSignal(ss, SSL_BUFFER_BASE(messageBuf),
9825                                                      SSL_BUFFER_LEN(messageBuf));
9826             } else {
9827                 return tls13_WriteServerEchSignal(ss, SSL_BUFFER_BASE(messageBuf),
9828                                                   SSL_BUFFER_LEN(messageBuf));
9829             }
9830         }
9831     }
9832     return SECSuccess;
9833 }
9834 
9835 /* The negotiated version number has been already placed in ss->version.
9836 **
9837 ** Called from:  ssl3_HandleClientHello                     (resuming session),
9838 **  ssl3_SendServerHelloSequence <- ssl3_HandleClientHello   (new session),
9839 **  ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
9840 */
9841 SECStatus
ssl3_SendServerHello(sslSocket * ss)9842 ssl3_SendServerHello(sslSocket *ss)
9843 {
9844     SECStatus rv;
9845     sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
9846     sslBuffer messageBuf = SSL_BUFFER_EMPTY;
9847 
9848     SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
9849                 ss->fd));
9850 
9851     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9852     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9853 
9854     PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
9855     if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
9856         PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
9857         return SECFailure;
9858     }
9859 
9860     rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_server_hello);
9861     if (rv != SECSuccess) {
9862         goto loser;
9863     }
9864 
9865     rv = ssl_ConstructServerHello(ss, PR_FALSE, &extensionBuf, &messageBuf);
9866     if (rv != SECSuccess) {
9867         goto loser;
9868     }
9869 
9870     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello,
9871                                     SSL_BUFFER_LEN(&messageBuf));
9872     if (rv != SECSuccess) {
9873         goto loser; /* err set by AppendHandshake. */
9874     }
9875 
9876     rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&messageBuf),
9877                               SSL_BUFFER_LEN(&messageBuf));
9878     if (rv != SECSuccess) {
9879         goto loser; /* err set by AppendHandshake. */
9880     }
9881 
9882     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
9883         rv = ssl3_SetupBothPendingCipherSpecs(ss);
9884         if (rv != SECSuccess) {
9885             goto loser; /* err set */
9886         }
9887     }
9888 
9889     sslBuffer_Clear(&extensionBuf);
9890     sslBuffer_Clear(&messageBuf);
9891     return SECSuccess;
9892 
9893 loser:
9894     sslBuffer_Clear(&extensionBuf);
9895     sslBuffer_Clear(&messageBuf);
9896     return SECFailure;
9897 }
9898 
9899 SECStatus
ssl_CreateDHEKeyPair(const sslNamedGroupDef * groupDef,const ssl3DHParams * params,sslEphemeralKeyPair ** keyPair)9900 ssl_CreateDHEKeyPair(const sslNamedGroupDef *groupDef,
9901                      const ssl3DHParams *params,
9902                      sslEphemeralKeyPair **keyPair)
9903 {
9904     SECKEYDHParams dhParam;
9905     SECKEYPublicKey *pubKey = NULL;   /* Ephemeral DH key */
9906     SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */
9907     sslEphemeralKeyPair *pair;
9908 
9909     dhParam.prime.data = params->prime.data;
9910     dhParam.prime.len = params->prime.len;
9911     dhParam.base.data = params->base.data;
9912     dhParam.base.len = params->base.len;
9913 
9914     PRINT_BUF(60, (NULL, "Server DH p", dhParam.prime.data,
9915                    dhParam.prime.len));
9916     PRINT_BUF(60, (NULL, "Server DH g", dhParam.base.data,
9917                    dhParam.base.len));
9918 
9919     /* Generate ephemeral DH keypair */
9920     privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
9921     if (!privKey || !pubKey) {
9922         ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
9923         return SECFailure;
9924     }
9925 
9926     pair = ssl_NewEphemeralKeyPair(groupDef, privKey, pubKey);
9927     if (!pair) {
9928         SECKEY_DestroyPrivateKey(privKey);
9929         SECKEY_DestroyPublicKey(pubKey);
9930 
9931         return SECFailure;
9932     }
9933 
9934     *keyPair = pair;
9935     return SECSuccess;
9936 }
9937 
9938 static SECStatus
ssl3_SendDHServerKeyExchange(sslSocket * ss)9939 ssl3_SendDHServerKeyExchange(sslSocket *ss)
9940 {
9941     const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
9942     SECStatus rv = SECFailure;
9943     int length;
9944     SECItem signed_hash = { siBuffer, NULL, 0 };
9945     SSL3Hashes hashes;
9946     SSLHashType hashAlg;
9947 
9948     const ssl3DHParams *params;
9949     sslEphemeralKeyPair *keyPair;
9950     SECKEYPublicKey *pubKey;
9951     SECKEYPrivateKey *certPrivateKey;
9952     const sslNamedGroupDef *groupDef;
9953     /* Do this on the heap, this could be over 2k long. */
9954     sslBuffer dhBuf = SSL_BUFFER_EMPTY;
9955 
9956     if (kea_def->kea != kea_dhe_dss && kea_def->kea != kea_dhe_rsa) {
9957         /* TODO: Support DH_anon. It might be sufficient to drop the signature.
9958                  See bug 1170510. */
9959         PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9960         return SECFailure;
9961     }
9962 
9963     rv = ssl_SelectDHEGroup(ss, &groupDef);
9964     if (rv == SECFailure) {
9965         PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
9966         return SECFailure;
9967     }
9968     ss->sec.keaGroup = groupDef;
9969 
9970     params = ssl_GetDHEParams(groupDef);
9971     rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
9972     if (rv == SECFailure) {
9973         ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
9974         return SECFailure;
9975     }
9976     PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs);
9977 
9978     if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
9979         hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
9980     } else {
9981         /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
9982         hashAlg = ssl_hash_none;
9983     }
9984 
9985     pubKey = keyPair->keys->pubKey;
9986     PRINT_BUF(50, (ss, "DH public value:",
9987                    pubKey->u.dh.publicValue.data,
9988                    pubKey->u.dh.publicValue.len));
9989     rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
9990                                pubKey->u.dh.prime,
9991                                pubKey->u.dh.base,
9992                                pubKey->u.dh.publicValue,
9993                                PR_TRUE /* padY */);
9994     if (rv != SECSuccess) {
9995         ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9996         goto loser;
9997     }
9998 
9999     certPrivateKey = ss->sec.serverCert->serverKeyPair->privKey;
10000     rv = ssl3_SignHashes(ss, &hashes, certPrivateKey, &signed_hash);
10001     if (rv != SECSuccess) {
10002         goto loser; /* ssl3_SignHashes has set err. */
10003     }
10004 
10005     length = 2 + pubKey->u.dh.prime.len +
10006              2 + pubKey->u.dh.base.len +
10007              2 + pubKey->u.dh.prime.len +
10008              2 + signed_hash.len;
10009 
10010     if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
10011         length += 2;
10012     }
10013 
10014     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_key_exchange, length);
10015     if (rv != SECSuccess) {
10016         goto loser; /* err set by AppendHandshake. */
10017     }
10018 
10019     rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.prime.data,
10020                                       pubKey->u.dh.prime.len, 2);
10021     if (rv != SECSuccess) {
10022         goto loser; /* err set by AppendHandshake. */
10023     }
10024 
10025     rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.base.data,
10026                                       pubKey->u.dh.base.len, 2);
10027     if (rv != SECSuccess) {
10028         goto loser; /* err set by AppendHandshake. */
10029     }
10030 
10031     rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE);
10032     if (rv != SECSuccess) {
10033         goto loser; /* err set by AppendPaddedDHKeyShare. */
10034     }
10035     rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
10036     if (rv != SECSuccess) {
10037         goto loser; /* err set by AppendHandshake. */
10038     }
10039 
10040     if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
10041         rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
10042         if (rv != SECSuccess) {
10043             goto loser; /* err set by AppendHandshake. */
10044         }
10045     }
10046 
10047     rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
10048                                       signed_hash.len, 2);
10049     if (rv != SECSuccess) {
10050         goto loser; /* err set by AppendHandshake. */
10051     }
10052 
10053     sslBuffer_Clear(&dhBuf);
10054     PORT_Free(signed_hash.data);
10055     return SECSuccess;
10056 
10057 loser:
10058     if (signed_hash.data)
10059         PORT_Free(signed_hash.data);
10060     sslBuffer_Clear(&dhBuf);
10061     return SECFailure;
10062 }
10063 
10064 static SECStatus
ssl3_SendServerKeyExchange(sslSocket * ss)10065 ssl3_SendServerKeyExchange(sslSocket *ss)
10066 {
10067     const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
10068 
10069     SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
10070                 SSL_GETPID(), ss->fd));
10071 
10072     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10073     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10074 
10075     switch (kea_def->exchKeyType) {
10076         case ssl_kea_dh: {
10077             return ssl3_SendDHServerKeyExchange(ss);
10078         }
10079 
10080         case ssl_kea_ecdh: {
10081             return ssl3_SendECDHServerKeyExchange(ss);
10082         }
10083 
10084         case ssl_kea_rsa:
10085         case ssl_kea_null:
10086         default:
10087             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10088             break;
10089     }
10090 
10091     return SECFailure;
10092 }
10093 
10094 SECStatus
ssl3_EncodeSigAlgs(const sslSocket * ss,PRUint16 minVersion,PRBool forCert,sslBuffer * buf)10095 ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool forCert,
10096                    sslBuffer *buf)
10097 {
10098     SSLSignatureScheme filtered[MAX_SIGNATURE_SCHEMES] = { 0 };
10099     unsigned int filteredCount = 0;
10100 
10101     SECStatus rv = ssl3_FilterSigAlgs(ss, minVersion, PR_FALSE, forCert,
10102                                       PR_ARRAY_SIZE(filtered),
10103                                       filtered, &filteredCount);
10104     if (rv != SECSuccess) {
10105         return SECFailure;
10106     }
10107     return ssl3_EncodeFilteredSigAlgs(ss, filtered, filteredCount, buf);
10108 }
10109 
10110 SECStatus
ssl3_EncodeFilteredSigAlgs(const sslSocket * ss,const SSLSignatureScheme * schemes,PRUint32 numSchemes,sslBuffer * buf)10111 ssl3_EncodeFilteredSigAlgs(const sslSocket *ss, const SSLSignatureScheme *schemes,
10112                            PRUint32 numSchemes, sslBuffer *buf)
10113 {
10114     if (!numSchemes) {
10115         PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
10116         return SECFailure;
10117     }
10118 
10119     unsigned int lengthOffset;
10120     SECStatus rv;
10121 
10122     rv = sslBuffer_Skip(buf, 2, &lengthOffset);
10123     if (rv != SECSuccess) {
10124         return SECFailure;
10125     }
10126 
10127     for (unsigned int i = 0; i < numSchemes; ++i) {
10128         rv = sslBuffer_AppendNumber(buf, schemes[i], 2);
10129         if (rv != SECSuccess) {
10130             return SECFailure;
10131         }
10132     }
10133     return sslBuffer_InsertLength(buf, lengthOffset, 2);
10134 }
10135 
10136 /*
10137  * In TLS 1.3 we are permitted to advertise support for PKCS#1
10138  * schemes. This doesn't affect the signatures in TLS itself, just
10139  * those on certificates. Not advertising PKCS#1 signatures creates a
10140  * serious compatibility risk as it excludes many certificate chains
10141  * that include PKCS#1. Hence, forCert is used to enable advertising
10142  * PKCS#1 support. Note that we include these in signature_algorithms
10143  * because we don't yet support signature_algorithms_cert. TLS 1.3
10144  * requires that PKCS#1 schemes are placed last in the list if they
10145  * are present. This sorting can be removed once we support
10146  * signature_algorithms_cert.
10147  */
10148 SECStatus
ssl3_FilterSigAlgs(const sslSocket * ss,PRUint16 minVersion,PRBool disableRsae,PRBool forCert,unsigned int maxSchemes,SSLSignatureScheme * filteredSchemes,unsigned int * numFilteredSchemes)10149 ssl3_FilterSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool disableRsae,
10150                    PRBool forCert,
10151                    unsigned int maxSchemes, SSLSignatureScheme *filteredSchemes,
10152                    unsigned int *numFilteredSchemes)
10153 {
10154     PORT_Assert(filteredSchemes);
10155     PORT_Assert(numFilteredSchemes);
10156     PORT_Assert(maxSchemes >= ss->ssl3.signatureSchemeCount);
10157     if (maxSchemes < ss->ssl3.signatureSchemeCount) {
10158         return SECFailure;
10159     }
10160 
10161     *numFilteredSchemes = 0;
10162     PRBool allowUnsortedPkcs1 = forCert && minVersion < SSL_LIBRARY_VERSION_TLS_1_3;
10163     for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
10164         if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
10165             continue;
10166         }
10167         if (ssl_SignatureSchemeAccepted(minVersion,
10168                                         ss->ssl3.signatureSchemes[i],
10169                                         allowUnsortedPkcs1)) {
10170             filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
10171         }
10172     }
10173     if (forCert && !allowUnsortedPkcs1) {
10174         for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
10175             if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
10176                 continue;
10177             }
10178             if (!ssl_SignatureSchemeAccepted(minVersion,
10179                                              ss->ssl3.signatureSchemes[i],
10180                                              PR_FALSE) &&
10181                 ssl_SignatureSchemeAccepted(minVersion,
10182                                             ss->ssl3.signatureSchemes[i],
10183                                             PR_TRUE)) {
10184                 filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
10185             }
10186         }
10187     }
10188     return SECSuccess;
10189 }
10190 
10191 static SECStatus
ssl3_SendCertificateRequest(sslSocket * ss)10192 ssl3_SendCertificateRequest(sslSocket *ss)
10193 {
10194     PRBool isTLS12;
10195     const PRUint8 *certTypes;
10196     SECStatus rv;
10197     PRUint32 length;
10198     const SECItem *names;
10199     unsigned int calen;
10200     unsigned int nnames;
10201     const SECItem *name;
10202     unsigned int i;
10203     int certTypesLength;
10204     PRUint8 sigAlgs[2 + MAX_SIGNATURE_SCHEMES * 2];
10205     sslBuffer sigAlgsBuf = SSL_BUFFER(sigAlgs);
10206 
10207     SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
10208                 SSL_GETPID(), ss->fd));
10209 
10210     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10211     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10212 
10213     isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
10214 
10215     rv = ssl_GetCertificateRequestCAs(ss, &calen, &names, &nnames);
10216     if (rv != SECSuccess) {
10217         return rv;
10218     }
10219     certTypes = certificate_types;
10220     certTypesLength = sizeof certificate_types;
10221 
10222     length = 1 + certTypesLength + 2 + calen;
10223     if (isTLS12) {
10224         rv = ssl3_EncodeSigAlgs(ss, ss->version, PR_TRUE /* forCert */, &sigAlgsBuf);
10225         if (rv != SECSuccess) {
10226             return rv;
10227         }
10228         length += SSL_BUFFER_LEN(&sigAlgsBuf);
10229     }
10230 
10231     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request, length);
10232     if (rv != SECSuccess) {
10233         return rv; /* err set by AppendHandshake. */
10234     }
10235     rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
10236     if (rv != SECSuccess) {
10237         return rv; /* err set by AppendHandshake. */
10238     }
10239     if (isTLS12) {
10240         rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&sigAlgsBuf),
10241                                   SSL_BUFFER_LEN(&sigAlgsBuf));
10242         if (rv != SECSuccess) {
10243             return rv; /* err set by AppendHandshake. */
10244         }
10245     }
10246     rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
10247     if (rv != SECSuccess) {
10248         return rv; /* err set by AppendHandshake. */
10249     }
10250     for (i = 0, name = names; i < nnames; i++, name++) {
10251         rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
10252         if (rv != SECSuccess) {
10253             return rv; /* err set by AppendHandshake. */
10254         }
10255     }
10256 
10257     return SECSuccess;
10258 }
10259 
10260 static SECStatus
ssl3_SendServerHelloDone(sslSocket * ss)10261 ssl3_SendServerHelloDone(sslSocket *ss)
10262 {
10263     SECStatus rv;
10264 
10265     SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
10266                 SSL_GETPID(), ss->fd));
10267 
10268     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10269     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10270 
10271     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello_done, 0);
10272     if (rv != SECSuccess) {
10273         return rv; /* err set by AppendHandshake. */
10274     }
10275     rv = ssl3_FlushHandshake(ss, 0);
10276     if (rv != SECSuccess) {
10277         return rv; /* error code set by ssl3_FlushHandshake */
10278     }
10279     return SECSuccess;
10280 }
10281 
10282 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10283  * a complete ssl3 Certificate Verify message
10284  * Caller must hold Handshake and RecvBuf locks.
10285  */
10286 static SECStatus
ssl3_HandleCertificateVerify(sslSocket * ss,PRUint8 * b,PRUint32 length)10287 ssl3_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
10288 {
10289     SECItem signed_hash = { siBuffer, NULL, 0 };
10290     SECStatus rv;
10291     int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
10292     SSL3AlertDescription desc = handshake_failure;
10293     PRBool isTLS;
10294     SSLSignatureScheme sigScheme;
10295     SSL3Hashes hashes;
10296     const PRUint8 *savedMsg = b;
10297     const PRUint32 savedLen = length;
10298 
10299     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
10300                 SSL_GETPID(), ss->fd));
10301     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10302     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10303 
10304     if (ss->ssl3.hs.ws != wait_cert_verify) {
10305         desc = unexpected_message;
10306         errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
10307         goto alert_loser;
10308     }
10309 
10310     /* TLS 1.3 is handled by tls13_HandleCertificateVerify */
10311     PORT_Assert(ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2);
10312 
10313     if (ss->ssl3.prSpec->version == SSL_LIBRARY_VERSION_TLS_1_2) {
10314         PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_record);
10315         rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
10316         if (rv != SECSuccess) {
10317             if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
10318                 errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
10319             }
10320             goto loser; /* alert already sent */
10321         }
10322         rv = ssl_CheckSignatureSchemeConsistency(
10323             ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo);
10324         if (rv != SECSuccess) {
10325             errCode = PORT_GetError();
10326             desc = illegal_parameter;
10327             goto alert_loser;
10328         }
10329 
10330         rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
10331                                        ss->ssl3.hs.messages.len,
10332                                        ssl_SignatureSchemeToHashType(sigScheme),
10333                                        &hashes);
10334     } else {
10335         PORT_Assert(ss->ssl3.hs.hashType != handshake_hash_record);
10336         sigScheme = ssl_sig_none;
10337         rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.prSpec, &hashes, 0);
10338     }
10339 
10340     if (rv != SECSuccess) {
10341         errCode = SSL_ERROR_DIGEST_FAILURE;
10342         desc = decrypt_error;
10343         goto alert_loser;
10344     }
10345 
10346     rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
10347     if (rv != SECSuccess) {
10348         goto loser; /* malformed. */
10349     }
10350 
10351     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
10352 
10353     /* XXX verify that the key & kea match */
10354     rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signed_hash);
10355     if (rv != SECSuccess) {
10356         errCode = PORT_GetError();
10357         desc = isTLS ? decrypt_error : handshake_failure;
10358         goto alert_loser;
10359     }
10360 
10361     signed_hash.data = NULL;
10362 
10363     if (length != 0) {
10364         desc = isTLS ? decode_error : illegal_parameter;
10365         goto alert_loser; /* malformed */
10366     }
10367 
10368     rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify,
10369                                   savedMsg, savedLen);
10370     if (rv != SECSuccess) {
10371         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10372         return rv;
10373     }
10374 
10375     ss->ssl3.hs.ws = wait_change_cipher;
10376     return SECSuccess;
10377 
10378 alert_loser:
10379     SSL3_SendAlert(ss, alert_fatal, desc);
10380 loser:
10381     PORT_SetError(errCode);
10382     return SECFailure;
10383 }
10384 
10385 /* find a slot that is able to generate a PMS and wrap it with RSA.
10386  * Then generate and return the PMS.
10387  * If the serverKeySlot parameter is non-null, this function will use
10388  * that slot to do the job, otherwise it will find a slot.
10389  *
10390  * Called from  ssl3_DeriveConnectionKeys()  (above)
10391  *      ssl3_SendRSAClientKeyExchange()     (above)
10392  *      ssl3_HandleRSAClientKeyExchange()  (below)
10393  * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
10394  */
10395 static PK11SymKey *
ssl3_GenerateRSAPMS(sslSocket * ss,ssl3CipherSpec * spec,PK11SlotInfo * serverKeySlot)10396 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
10397                     PK11SlotInfo *serverKeySlot)
10398 {
10399     PK11SymKey *pms = NULL;
10400     PK11SlotInfo *slot = serverKeySlot;
10401     void *pwArg = ss->pkcs11PinArg;
10402     SECItem param;
10403     CK_VERSION version;
10404     CK_MECHANISM_TYPE mechanism_array[3];
10405 
10406     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10407 
10408     if (slot == NULL) {
10409         SSLCipherAlgorithm calg;
10410         /* The specReadLock would suffice here, but we cannot assert on
10411         ** read locks.  Also, all the callers who call with a non-null
10412         ** slot already hold the SpecWriteLock.
10413         */
10414         PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
10415         PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
10416 
10417         calg = spec->cipherDef->calg;
10418 
10419         /* First get an appropriate slot.  */
10420         mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
10421         mechanism_array[1] = CKM_RSA_PKCS;
10422         mechanism_array[2] = ssl3_Alg2Mech(calg);
10423 
10424         slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
10425         if (slot == NULL) {
10426             /* can't find a slot with all three, find a slot with the minimum */
10427             slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
10428             if (slot == NULL) {
10429                 PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
10430                 return pms; /* which is NULL */
10431             }
10432         }
10433     }
10434 
10435     /* Generate the pre-master secret ...  */
10436     if (IS_DTLS(ss)) {
10437         SSL3ProtocolVersion temp;
10438 
10439         temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
10440         version.major = MSB(temp);
10441         version.minor = LSB(temp);
10442     } else {
10443         version.major = MSB(ss->clientHelloVersion);
10444         version.minor = LSB(ss->clientHelloVersion);
10445     }
10446 
10447     param.data = (unsigned char *)&version;
10448     param.len = sizeof version;
10449 
10450     pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
10451     if (!serverKeySlot)
10452         PK11_FreeSlot(slot);
10453     if (pms == NULL) {
10454         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10455     }
10456     return pms;
10457 }
10458 
10459 static void
ssl3_CSwapPK11SymKey(PK11SymKey ** x,PK11SymKey ** y,PRBool c)10460 ssl3_CSwapPK11SymKey(PK11SymKey **x, PK11SymKey **y, PRBool c)
10461 {
10462     uintptr_t mask = (uintptr_t)c;
10463     unsigned int i;
10464     for (i = 1; i < sizeof(uintptr_t) * 8; i <<= 1) {
10465         mask |= mask << i;
10466     }
10467     uintptr_t x_ptr = (uintptr_t)*x;
10468     uintptr_t y_ptr = (uintptr_t)*y;
10469     uintptr_t tmp = (x_ptr ^ y_ptr) & mask;
10470     x_ptr = x_ptr ^ tmp;
10471     y_ptr = y_ptr ^ tmp;
10472     *x = (PK11SymKey *)x_ptr;
10473     *y = (PK11SymKey *)y_ptr;
10474 }
10475 
10476 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
10477  * return any indication of failure of the Client Key Exchange message,
10478  * where that failure is caused by the content of the client's message.
10479  * This function must not return SECFailure for any reason that is directly
10480  * or indirectly caused by the content of the client's encrypted PMS.
10481  * We must not send an alert and also not drop the connection.
10482  * Instead, we generate a random PMS.  This will cause a failure
10483  * in the processing the finished message, which is exactly where
10484  * the failure must occur.
10485  *
10486  * Called from ssl3_HandleClientKeyExchange
10487  */
10488 static SECStatus
ssl3_HandleRSAClientKeyExchange(sslSocket * ss,PRUint8 * b,PRUint32 length,sslKeyPair * serverKeyPair)10489 ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
10490                                 PRUint8 *b,
10491                                 PRUint32 length,
10492                                 sslKeyPair *serverKeyPair)
10493 {
10494     SECStatus rv;
10495     SECItem enc_pms;
10496     PK11SymKey *pms = NULL;
10497     PK11SymKey *fauxPms = NULL;
10498     PK11SlotInfo *slot = NULL;
10499 
10500     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10501     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10502     PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
10503 
10504     enc_pms.data = b;
10505     enc_pms.len = length;
10506 
10507     if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
10508         PRUint32 kLen;
10509         rv = ssl3_ConsumeHandshakeNumber(ss, &kLen, 2, &enc_pms.data, &enc_pms.len);
10510         if (rv != SECSuccess) {
10511             PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10512             return SECFailure;
10513         }
10514         if ((unsigned)kLen < enc_pms.len) {
10515             enc_pms.len = kLen;
10516         }
10517     }
10518 
10519     /*
10520      * Get as close to algorithm 2 from RFC 5246; Section 7.4.7.1
10521      * as we can within the constraints of the PKCS#11 interface.
10522      *
10523      * 1. Unconditionally generate a bogus PMS (what RFC 5246
10524      *    calls R).
10525      * 2. Attempt the RSA decryption to recover the PMS (what
10526      *    RFC 5246 calls M).
10527      * 3. Set PMS = (M == NULL) ? R : M
10528      * 4. Use ssl3_ComputeMasterSecret(PMS) to attempt to derive
10529      *    the MS from PMS. This includes performing the version
10530      *    check and length check.
10531      * 5. If either the initial RSA decryption failed or
10532      *    ssl3_ComputeMasterSecret(PMS) failed, then discard
10533      *    M and set PMS = R. Else, discard R and set PMS = M.
10534      *
10535      * We do two derivations here because we can't rely on having
10536      * a function that only performs the PMS version and length
10537      * check. The only redundant cost is that this runs the PRF,
10538      * which isn't necessary here.
10539      */
10540 
10541     /* Generate the bogus PMS (R) */
10542     slot = PK11_GetSlotFromPrivateKey(serverKeyPair->privKey);
10543     if (!slot) {
10544         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10545         return SECFailure;
10546     }
10547 
10548     if (!PK11_DoesMechanism(slot, CKM_SSL3_MASTER_KEY_DERIVE)) {
10549         PK11_FreeSlot(slot);
10550         slot = PK11_GetBestSlot(CKM_SSL3_MASTER_KEY_DERIVE, NULL);
10551         if (!slot) {
10552             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10553             return SECFailure;
10554         }
10555     }
10556 
10557     ssl_GetSpecWriteLock(ss);
10558     fauxPms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
10559     ssl_ReleaseSpecWriteLock(ss);
10560     PK11_FreeSlot(slot);
10561 
10562     if (fauxPms == NULL) {
10563         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10564         return SECFailure;
10565     }
10566 
10567     /*
10568      * unwrap pms out of the incoming buffer
10569      * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
10570      *  the unwrap.  Rather, it is the mechanism with which the
10571      *      unwrapped pms will be used.
10572      */
10573     pms = PK11_PubUnwrapSymKey(serverKeyPair->privKey, &enc_pms,
10574                                CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
10575     /* Temporarily use the PMS if unwrapping the real PMS fails. */
10576     ssl3_CSwapPK11SymKey(&pms, &fauxPms, pms == NULL);
10577 
10578     /* Attempt to derive the MS from the PMS. This is the only way to
10579      * check the version field in the RSA PMS. If this fails, we
10580      * then use the faux PMS in place of the PMS. Note that this
10581      * operation should never fail if we are using the faux PMS
10582      * since it is correctly formatted. */
10583     rv = ssl3_ComputeMasterSecret(ss, pms, NULL);
10584 
10585     /* If we succeeded, then select the true PMS, else select the FPMS. */
10586     ssl3_CSwapPK11SymKey(&pms, &fauxPms, (rv != SECSuccess) & (fauxPms != NULL));
10587 
10588     /* This step will derive the MS from the PMS, among other things. */
10589     rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
10590 
10591     /* Clear both PMS. */
10592     PK11_FreeSymKey(pms);
10593     PK11_FreeSymKey(fauxPms);
10594 
10595     if (rv != SECSuccess) {
10596         (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10597         return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
10598     }
10599 
10600     return SECSuccess;
10601 }
10602 
10603 static SECStatus
ssl3_HandleDHClientKeyExchange(sslSocket * ss,PRUint8 * b,PRUint32 length,sslKeyPair * serverKeyPair)10604 ssl3_HandleDHClientKeyExchange(sslSocket *ss,
10605                                PRUint8 *b,
10606                                PRUint32 length,
10607                                sslKeyPair *serverKeyPair)
10608 {
10609     PK11SymKey *pms;
10610     SECStatus rv;
10611     SECKEYPublicKey clntPubKey;
10612     CK_MECHANISM_TYPE target;
10613     PRBool isTLS;
10614 
10615     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10616     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10617 
10618     clntPubKey.keyType = dhKey;
10619     clntPubKey.u.dh.prime.len = serverKeyPair->pubKey->u.dh.prime.len;
10620     clntPubKey.u.dh.prime.data = serverKeyPair->pubKey->u.dh.prime.data;
10621     clntPubKey.u.dh.base.len = serverKeyPair->pubKey->u.dh.base.len;
10622     clntPubKey.u.dh.base.data = serverKeyPair->pubKey->u.dh.base.data;
10623 
10624     rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.dh.publicValue,
10625                                        2, &b, &length);
10626     if (rv != SECSuccess) {
10627         return SECFailure;
10628     }
10629 
10630     if (!ssl_IsValidDHEShare(&serverKeyPair->pubKey->u.dh.prime,
10631                              &clntPubKey.u.dh.publicValue)) {
10632         PORT_SetError(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE);
10633         return SECFailure;
10634     }
10635 
10636     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
10637 
10638     if (isTLS)
10639         target = CKM_TLS_MASTER_KEY_DERIVE_DH;
10640     else
10641         target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
10642 
10643     /* Determine the PMS */
10644     pms = PK11_PubDerive(serverKeyPair->privKey, &clntPubKey, PR_FALSE, NULL, NULL,
10645                          CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
10646     if (pms == NULL) {
10647         ssl_FreeEphemeralKeyPairs(ss);
10648         ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10649         return SECFailure;
10650     }
10651 
10652     rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
10653     PK11_FreeSymKey(pms);
10654     ssl_FreeEphemeralKeyPairs(ss);
10655     return rv;
10656 }
10657 
10658 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10659  * a complete ssl3 ClientKeyExchange message from the remote client
10660  * Caller must hold Handshake and RecvBuf locks.
10661  */
10662 static SECStatus
ssl3_HandleClientKeyExchange(sslSocket * ss,PRUint8 * b,PRUint32 length)10663 ssl3_HandleClientKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
10664 {
10665     sslKeyPair *serverKeyPair = NULL;
10666     SECStatus rv;
10667     const ssl3KEADef *kea_def;
10668 
10669     SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
10670                 SSL_GETPID(), ss->fd));
10671 
10672     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10673     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10674 
10675     if (ss->ssl3.hs.ws != wait_client_key) {
10676         SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10677         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
10678         return SECFailure;
10679     }
10680 
10681     kea_def = ss->ssl3.hs.kea_def;
10682 
10683     if (kea_def->ephemeral) {
10684         sslEphemeralKeyPair *keyPair;
10685         /* There should be exactly one pair. */
10686         PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
10687         PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==
10688                     PR_NEXT_LINK(&ss->ephemeralKeyPairs));
10689         keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs);
10690         serverKeyPair = keyPair->keys;
10691         ss->sec.keaKeyBits =
10692             SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
10693     } else {
10694         serverKeyPair = ss->sec.serverCert->serverKeyPair;
10695         ss->sec.keaKeyBits = ss->sec.serverCert->serverKeyBits;
10696     }
10697 
10698     if (!serverKeyPair) {
10699         SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10700         PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
10701         return SECFailure;
10702     }
10703     PORT_Assert(serverKeyPair->pubKey);
10704     PORT_Assert(serverKeyPair->privKey);
10705 
10706     ss->sec.keaType = kea_def->exchKeyType;
10707 
10708     switch (kea_def->exchKeyType) {
10709         case ssl_kea_rsa:
10710             rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKeyPair);
10711             break;
10712 
10713         case ssl_kea_dh:
10714             rv = ssl3_HandleDHClientKeyExchange(ss, b, length, serverKeyPair);
10715             break;
10716 
10717         case ssl_kea_ecdh:
10718             rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, serverKeyPair);
10719             break;
10720 
10721         default:
10722             (void)ssl3_HandshakeFailure(ss);
10723             PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
10724             return SECFailure;
10725     }
10726     ssl_FreeEphemeralKeyPairs(ss);
10727     if (rv == SECSuccess) {
10728         ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
10729     } else {
10730         /* PORT_SetError has been called by all the Handle*ClientKeyExchange
10731          * functions above.  However, not all error paths result in an alert, so
10732          * this ensures that the server knows about the error.  Note that if an
10733          * alert was already sent, SSL3_SendAlert() is a noop. */
10734         PRErrorCode errCode = PORT_GetError();
10735         (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10736         PORT_SetError(errCode);
10737     }
10738     return rv;
10739 }
10740 
10741 /* This is TLS's equivalent of sending a no_certificate alert. */
10742 SECStatus
ssl3_SendEmptyCertificate(sslSocket * ss)10743 ssl3_SendEmptyCertificate(sslSocket *ss)
10744 {
10745     SECStatus rv;
10746     unsigned int len = 0;
10747     PRBool isTLS13 = PR_FALSE;
10748     const SECItem *context;
10749 
10750     if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
10751         PORT_Assert(ss->ssl3.hs.clientCertRequested);
10752         context = &ss->xtnData.certReqContext;
10753         len = context->len + 1;
10754         isTLS13 = PR_TRUE;
10755     }
10756 
10757     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate, len + 3);
10758     if (rv != SECSuccess) {
10759         return rv;
10760     }
10761 
10762     if (isTLS13) {
10763         rv = ssl3_AppendHandshakeVariable(ss, context->data, context->len, 1);
10764         if (rv != SECSuccess) {
10765             return rv;
10766         }
10767     }
10768 
10769     return ssl3_AppendHandshakeNumber(ss, 0, 3);
10770 }
10771 
10772 /*
10773  * NewSessionTicket
10774  * Called from ssl3_HandleFinished
10775  */
10776 static SECStatus
ssl3_SendNewSessionTicket(sslSocket * ss)10777 ssl3_SendNewSessionTicket(sslSocket *ss)
10778 {
10779     SECItem ticket = { 0, NULL, 0 };
10780     SECStatus rv;
10781     NewSessionTicket nticket = { 0 };
10782 
10783     rv = ssl3_EncodeSessionTicket(ss, &nticket, NULL, 0,
10784                                   ss->ssl3.pwSpec->masterSecret, &ticket);
10785     if (rv != SECSuccess)
10786         goto loser;
10787 
10788     /* Serialize the handshake message. Length =
10789      * lifetime (4) + ticket length (2) + ticket. */
10790     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
10791                                     4 + 2 + ticket.len);
10792     if (rv != SECSuccess)
10793         goto loser;
10794 
10795     /* This is a fixed value. */
10796     rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
10797     if (rv != SECSuccess)
10798         goto loser;
10799 
10800     /* Encode the ticket. */
10801     rv = ssl3_AppendHandshakeVariable(ss, ticket.data, ticket.len, 2);
10802     if (rv != SECSuccess)
10803         goto loser;
10804 
10805     rv = SECSuccess;
10806 
10807 loser:
10808     if (ticket.data) {
10809         SECITEM_FreeItem(&ticket, PR_FALSE);
10810     }
10811     return rv;
10812 }
10813 
10814 static SECStatus
ssl3_HandleNewSessionTicket(sslSocket * ss,PRUint8 * b,PRUint32 length)10815 ssl3_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
10816 {
10817     SECStatus rv;
10818     SECItem ticketData;
10819     PRUint32 temp;
10820 
10821     SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
10822                 SSL_GETPID(), ss->fd));
10823 
10824     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10825     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10826 
10827     PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
10828     PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket);
10829 
10830     if (ss->ssl3.hs.ws != wait_new_session_ticket) {
10831         SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10832         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
10833         return SECFailure;
10834     }
10835 
10836     /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid
10837      * until it has verified the server's Finished message." See the comment in
10838      * ssl3_FinishHandshake for more details.
10839      */
10840     ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(ss);
10841     if (length < 4) {
10842         (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
10843         PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
10844         return SECFailure;
10845     }
10846 
10847     rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 4, &b, &length);
10848     if (rv != SECSuccess) {
10849         PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
10850         return SECFailure;
10851     }
10852     ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = temp;
10853 
10854     rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length);
10855     if (rv != SECSuccess || length != 0) {
10856         (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
10857         PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
10858         return SECFailure; /* malformed */
10859     }
10860     /* If the server sent a zero-length ticket, ignore it and keep the
10861      * existing ticket. */
10862     if (ticketData.len != 0) {
10863         rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket,
10864                               &ticketData);
10865         if (rv != SECSuccess) {
10866             return rv;
10867         }
10868         ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE;
10869     }
10870 
10871     ss->ssl3.hs.ws = wait_change_cipher;
10872     return SECSuccess;
10873 }
10874 
10875 #ifdef NISCC_TEST
10876 static PRInt32 connNum = 0;
10877 
10878 static SECStatus
get_fake_cert(SECItem * pCertItem,int * pIndex)10879 get_fake_cert(SECItem *pCertItem, int *pIndex)
10880 {
10881     PRFileDesc *cf;
10882     char *testdir;
10883     char *startat;
10884     char *stopat;
10885     const char *extension;
10886     int fileNum;
10887     PRInt32 numBytes = 0;
10888     PRStatus prStatus;
10889     PRFileInfo info;
10890     char cfn[100];
10891 
10892     pCertItem->data = 0;
10893     if ((testdir = PR_GetEnvSecure("NISCC_TEST")) == NULL) {
10894         return SECSuccess;
10895     }
10896     *pIndex = (NULL != strstr(testdir, "root"));
10897     extension = (strstr(testdir, "simple") ? "" : ".der");
10898     fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1;
10899     if ((startat = PR_GetEnvSecure("START_AT")) != NULL) {
10900         fileNum += atoi(startat);
10901     }
10902     if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL &&
10903         fileNum >= atoi(stopat)) {
10904         *pIndex = -1;
10905         return SECSuccess;
10906     }
10907     sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension);
10908     cf = PR_Open(cfn, PR_RDONLY, 0);
10909     if (!cf) {
10910         goto loser;
10911     }
10912     prStatus = PR_GetOpenFileInfo(cf, &info);
10913     if (prStatus != PR_SUCCESS) {
10914         PR_Close(cf);
10915         goto loser;
10916     }
10917     pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
10918     if (pCertItem) {
10919         numBytes = PR_Read(cf, pCertItem->data, info.size);
10920     }
10921     PR_Close(cf);
10922     if (numBytes != info.size) {
10923         SECITEM_FreeItem(pCertItem, PR_FALSE);
10924         PORT_SetError(SEC_ERROR_IO);
10925         goto loser;
10926     }
10927     fprintf(stderr, "using %s\n", cfn);
10928     return SECSuccess;
10929 
10930 loser:
10931     fprintf(stderr, "failed to use %s\n", cfn);
10932     *pIndex = -1;
10933     return SECFailure;
10934 }
10935 #endif
10936 
10937 /*
10938  * Used by both client and server.
10939  * Called from HandleServerHelloDone and from SendServerHelloSequence.
10940  */
10941 static SECStatus
ssl3_SendCertificate(sslSocket * ss)10942 ssl3_SendCertificate(sslSocket *ss)
10943 {
10944     SECStatus rv;
10945     CERTCertificateList *certChain;
10946     int certChainLen = 0;
10947     int i;
10948 #ifdef NISCC_TEST
10949     SECItem fakeCert;
10950     int ndex = -1;
10951 #endif
10952     PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
10953     SECItem context = { siBuffer, NULL, 0 };
10954     unsigned int contextLen = 0;
10955 
10956     SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
10957                 SSL_GETPID(), ss->fd));
10958 
10959     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10960     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10961 
10962     if (ss->sec.localCert)
10963         CERT_DestroyCertificate(ss->sec.localCert);
10964     if (ss->sec.isServer) {
10965         /* A server certificate is selected in ssl3_HandleClientHello. */
10966         PORT_Assert(ss->sec.serverCert);
10967 
10968         certChain = ss->sec.serverCert->serverCertChain;
10969         ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
10970     } else {
10971         certChain = ss->ssl3.clientCertChain;
10972         ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
10973     }
10974 
10975 #ifdef NISCC_TEST
10976     rv = get_fake_cert(&fakeCert, &ndex);
10977 #endif
10978 
10979     if (isTLS13) {
10980         contextLen = 1; /* Size of the context length */
10981         if (!ss->sec.isServer) {
10982             PORT_Assert(ss->ssl3.hs.clientCertRequested);
10983             context = ss->xtnData.certReqContext;
10984             contextLen += context.len;
10985         }
10986     }
10987     if (certChain) {
10988         for (i = 0; i < certChain->len; i++) {
10989 #ifdef NISCC_TEST
10990             if (fakeCert.len > 0 && i == ndex) {
10991                 certChainLen += fakeCert.len + 3;
10992             } else {
10993                 certChainLen += certChain->certs[i].len + 3;
10994             }
10995 #else
10996             certChainLen += certChain->certs[i].len + 3;
10997 #endif
10998         }
10999     }
11000 
11001     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate,
11002                                     contextLen + certChainLen + 3);
11003     if (rv != SECSuccess) {
11004         return rv; /* err set by AppendHandshake. */
11005     }
11006 
11007     if (isTLS13) {
11008         rv = ssl3_AppendHandshakeVariable(ss, context.data,
11009                                           context.len, 1);
11010         if (rv != SECSuccess) {
11011             return rv; /* err set by AppendHandshake. */
11012         }
11013     }
11014 
11015     rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3);
11016     if (rv != SECSuccess) {
11017         return rv; /* err set by AppendHandshake. */
11018     }
11019     if (certChain) {
11020         for (i = 0; i < certChain->len; i++) {
11021 #ifdef NISCC_TEST
11022             if (fakeCert.len > 0 && i == ndex) {
11023                 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
11024                                                   fakeCert.len, 3);
11025                 SECITEM_FreeItem(&fakeCert, PR_FALSE);
11026             } else {
11027                 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
11028                                                   certChain->certs[i].len, 3);
11029             }
11030 #else
11031             rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
11032                                               certChain->certs[i].len, 3);
11033 #endif
11034             if (rv != SECSuccess) {
11035                 return rv; /* err set by AppendHandshake. */
11036             }
11037         }
11038     }
11039 
11040     return SECSuccess;
11041 }
11042 
11043 /*
11044  * Used by server only.
11045  * single-stapling, send only a single cert status
11046  */
11047 SECStatus
ssl3_SendCertificateStatus(sslSocket * ss)11048 ssl3_SendCertificateStatus(sslSocket *ss)
11049 {
11050     SECStatus rv;
11051     int len = 0;
11052     SECItemArray *statusToSend = NULL;
11053     const sslServerCert *serverCert;
11054 
11055     SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
11056                 SSL_GETPID(), ss->fd));
11057 
11058     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11059     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11060     PORT_Assert(ss->sec.isServer);
11061 
11062     if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
11063         return SECSuccess;
11064 
11065     /* Use certStatus based on the cert being used. */
11066     serverCert = ss->sec.serverCert;
11067     if (serverCert->certStatusArray && serverCert->certStatusArray->len) {
11068         statusToSend = serverCert->certStatusArray;
11069     }
11070     if (!statusToSend)
11071         return SECSuccess;
11072 
11073     /* Use the array's first item only (single stapling) */
11074     len = 1 + statusToSend->items[0].len + 3;
11075 
11076     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_status, len);
11077     if (rv != SECSuccess) {
11078         return rv; /* err set by AppendHandshake. */
11079     }
11080     rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
11081     if (rv != SECSuccess)
11082         return rv; /* err set by AppendHandshake. */
11083 
11084     rv = ssl3_AppendHandshakeVariable(ss,
11085                                       statusToSend->items[0].data,
11086                                       statusToSend->items[0].len,
11087                                       3);
11088     if (rv != SECSuccess)
11089         return rv; /* err set by AppendHandshake. */
11090 
11091     return SECSuccess;
11092 }
11093 
11094 /* This is used to delete the CA certificates in the peer certificate chain
11095  * from the cert database after they've been validated.
11096  */
11097 void
ssl3_CleanupPeerCerts(sslSocket * ss)11098 ssl3_CleanupPeerCerts(sslSocket *ss)
11099 {
11100     PLArenaPool *arena = ss->ssl3.peerCertArena;
11101     ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
11102 
11103     for (; certs; certs = certs->next) {
11104         CERT_DestroyCertificate(certs->cert);
11105     }
11106     if (arena)
11107         PORT_FreeArena(arena, PR_FALSE);
11108     ss->ssl3.peerCertArena = NULL;
11109     ss->ssl3.peerCertChain = NULL;
11110 
11111     if (ss->sec.peerCert != NULL) {
11112         if (ss->sec.peerKey) {
11113             SECKEY_DestroyPublicKey(ss->sec.peerKey);
11114             ss->sec.peerKey = NULL;
11115         }
11116         CERT_DestroyCertificate(ss->sec.peerCert);
11117         ss->sec.peerCert = NULL;
11118     }
11119 }
11120 
11121 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11122  * a complete ssl3 CertificateStatus message.
11123  * Caller must hold Handshake and RecvBuf locks.
11124  */
11125 static SECStatus
ssl3_HandleCertificateStatus(sslSocket * ss,PRUint8 * b,PRUint32 length)11126 ssl3_HandleCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
11127 {
11128     SECStatus rv;
11129 
11130     if (ss->ssl3.hs.ws != wait_certificate_status) {
11131         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11132         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
11133         return SECFailure;
11134     }
11135 
11136     rv = ssl_ReadCertificateStatus(ss, b, length);
11137     if (rv != SECSuccess) {
11138         return SECFailure; /* code already set */
11139     }
11140 
11141     return ssl3_AuthCertificate(ss);
11142 }
11143 
11144 SECStatus
ssl_ReadCertificateStatus(sslSocket * ss,PRUint8 * b,PRUint32 length)11145 ssl_ReadCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
11146 {
11147     PRUint32 status, len;
11148     SECStatus rv;
11149 
11150     PORT_Assert(!ss->sec.isServer);
11151 
11152     /* Consume the CertificateStatusType enum */
11153     rv = ssl3_ConsumeHandshakeNumber(ss, &status, 1, &b, &length);
11154     if (rv != SECSuccess || status != 1 /* ocsp */) {
11155         return ssl3_DecodeError(ss);
11156     }
11157 
11158     rv = ssl3_ConsumeHandshakeNumber(ss, &len, 3, &b, &length);
11159     if (rv != SECSuccess || len != length) {
11160         return ssl3_DecodeError(ss);
11161     }
11162 
11163 #define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */
11164     if (length > MAX_CERTSTATUS_LEN) {
11165         ssl3_DecodeError(ss); /* sets error code */
11166         return SECFailure;
11167     }
11168 #undef MAX_CERTSTATUS_LEN
11169 
11170     /* Array size 1, because we currently implement single-stapling only */
11171     SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
11172     if (!ss->sec.ci.sid->peerCertStatus.items)
11173         return SECFailure; /* code already set */
11174 
11175     ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
11176 
11177     if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
11178         SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
11179         return SECFailure; /* code already set */
11180     }
11181 
11182     PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
11183     ss->sec.ci.sid->peerCertStatus.items[0].len = length;
11184     ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
11185     return SECSuccess;
11186 }
11187 
11188 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11189  * a complete ssl3 Certificate message.
11190  * Caller must hold Handshake and RecvBuf locks.
11191  */
11192 static SECStatus
ssl3_HandleCertificate(sslSocket * ss,PRUint8 * b,PRUint32 length)11193 ssl3_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
11194 {
11195     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
11196                 SSL_GETPID(), ss->fd));
11197     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11198     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11199 
11200     if ((ss->sec.isServer && ss->ssl3.hs.ws != wait_client_cert) ||
11201         (!ss->sec.isServer && ss->ssl3.hs.ws != wait_server_cert)) {
11202         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11203         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE);
11204         return SECFailure;
11205     }
11206 
11207     if (ss->sec.isServer) {
11208         dtls_ReceivedFirstMessageInFlight(ss);
11209     }
11210 
11211     return ssl3_CompleteHandleCertificate(ss, b, length);
11212 }
11213 
11214 /* Called from ssl3_HandleCertificate
11215  */
11216 SECStatus
ssl3_CompleteHandleCertificate(sslSocket * ss,PRUint8 * b,PRUint32 length)11217 ssl3_CompleteHandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
11218 {
11219     ssl3CertNode *c;
11220     ssl3CertNode *lastCert = NULL;
11221     PRUint32 remaining = 0;
11222     PRUint32 size;
11223     SECStatus rv;
11224     PRBool isServer = ss->sec.isServer;
11225     PRBool isTLS;
11226     SSL3AlertDescription desc;
11227     int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
11228     SECItem certItem;
11229 
11230     ssl3_CleanupPeerCerts(ss);
11231     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
11232 
11233     /* It is reported that some TLS client sends a Certificate message
11234     ** with a zero-length message body.  We'll treat that case like a
11235     ** normal no_certificates message to maximize interoperability.
11236     */
11237     if (length) {
11238         rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 3, &b, &length);
11239         if (rv != SECSuccess)
11240             goto loser; /* fatal alert already sent by ConsumeHandshake. */
11241         if (remaining > length)
11242             goto decode_loser;
11243     }
11244 
11245     if (!remaining) {
11246         if (!(isTLS && isServer)) {
11247             desc = bad_certificate;
11248             goto alert_loser;
11249         }
11250         /* This is TLS's version of a no_certificate alert. */
11251         /* I'm a server. I've requested a client cert. He hasn't got one. */
11252         rv = ssl3_HandleNoCertificate(ss);
11253         if (rv != SECSuccess) {
11254             errCode = PORT_GetError();
11255             goto loser;
11256         }
11257 
11258         if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11259             ss->ssl3.hs.ws = wait_client_key;
11260         } else {
11261             TLS13_SET_HS_STATE(ss, wait_finished);
11262         }
11263         return SECSuccess;
11264     }
11265 
11266     ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
11267     if (ss->ssl3.peerCertArena == NULL) {
11268         goto loser; /* don't send alerts on memory errors */
11269     }
11270 
11271     /* First get the peer cert. */
11272     if (remaining < 3)
11273         goto decode_loser;
11274 
11275     remaining -= 3;
11276     rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
11277     if (rv != SECSuccess)
11278         goto loser; /* fatal alert already sent by ConsumeHandshake. */
11279     if (size == 0 || remaining < size)
11280         goto decode_loser;
11281 
11282     certItem.data = b;
11283     certItem.len = size;
11284     b += size;
11285     length -= size;
11286     remaining -= size;
11287 
11288     ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
11289                                                PR_FALSE, PR_TRUE);
11290     if (ss->sec.peerCert == NULL) {
11291         /* We should report an alert if the cert was bad, but not if the
11292          * problem was just some local problem, like memory error.
11293          */
11294         goto ambiguous_err;
11295     }
11296 
11297     /* Now get all of the CA certs. */
11298     while (remaining > 0) {
11299         if (remaining < 3)
11300             goto decode_loser;
11301 
11302         remaining -= 3;
11303         rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
11304         if (rv != SECSuccess)
11305             goto loser; /* fatal alert already sent by ConsumeHandshake. */
11306         if (size == 0 || remaining < size)
11307             goto decode_loser;
11308 
11309         certItem.data = b;
11310         certItem.len = size;
11311         b += size;
11312         length -= size;
11313         remaining -= size;
11314 
11315         c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
11316         if (c == NULL) {
11317             goto loser; /* don't send alerts on memory errors */
11318         }
11319 
11320         c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
11321                                           PR_FALSE, PR_TRUE);
11322         if (c->cert == NULL) {
11323             goto ambiguous_err;
11324         }
11325 
11326         c->next = NULL;
11327         if (lastCert) {
11328             lastCert->next = c;
11329         } else {
11330             ss->ssl3.peerCertChain = c;
11331         }
11332         lastCert = c;
11333     }
11334 
11335     SECKEY_UpdateCertPQG(ss->sec.peerCert);
11336 
11337     if (!isServer &&
11338         ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
11339         ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
11340         ss->ssl3.hs.ws = wait_certificate_status;
11341         rv = SECSuccess;
11342     } else {
11343         rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
11344     }
11345 
11346     return rv;
11347 
11348 ambiguous_err:
11349     errCode = PORT_GetError();
11350     switch (errCode) {
11351         case PR_OUT_OF_MEMORY_ERROR:
11352         case SEC_ERROR_BAD_DATABASE:
11353         case SEC_ERROR_NO_MEMORY:
11354             if (isTLS) {
11355                 desc = internal_error;
11356                 goto alert_loser;
11357             }
11358             goto loser;
11359     }
11360     ssl3_SendAlertForCertError(ss, errCode);
11361     goto loser;
11362 
11363 decode_loser:
11364     desc = isTLS ? decode_error : bad_certificate;
11365 
11366 alert_loser:
11367     (void)SSL3_SendAlert(ss, alert_fatal, desc);
11368 
11369 loser:
11370     (void)ssl_MapLowLevelError(errCode);
11371     return SECFailure;
11372 }
11373 
11374 SECStatus
ssl_SetAuthKeyBits(sslSocket * ss,const SECKEYPublicKey * pubKey)11375 ssl_SetAuthKeyBits(sslSocket *ss, const SECKEYPublicKey *pubKey)
11376 {
11377     SECStatus rv;
11378     PRUint32 minKey;
11379     PRInt32 optval;
11380 
11381     ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(pubKey);
11382     switch (SECKEY_GetPublicKeyType(pubKey)) {
11383         case rsaKey:
11384         case rsaPssKey:
11385         case rsaOaepKey:
11386             rv = NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &optval);
11387             if (rv == SECSuccess && optval > 0) {
11388                 minKey = (PRUint32)optval;
11389             } else {
11390                 minKey = SSL_RSA_MIN_MODULUS_BITS;
11391             }
11392             break;
11393 
11394         case dsaKey:
11395             rv = NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &optval);
11396             if (rv == SECSuccess && optval > 0) {
11397                 minKey = (PRUint32)optval;
11398             } else {
11399                 minKey = SSL_DSA_MIN_P_BITS;
11400             }
11401             break;
11402 
11403         case dhKey:
11404             rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &optval);
11405             if (rv == SECSuccess && optval > 0) {
11406                 minKey = (PRUint32)optval;
11407             } else {
11408                 minKey = SSL_DH_MIN_P_BITS;
11409             }
11410             break;
11411 
11412         case ecKey:
11413             /* Don't check EC strength here on the understanding that we only
11414              * support curves we like. */
11415             minKey = ss->sec.authKeyBits;
11416             break;
11417 
11418         default:
11419             FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
11420             return SECFailure;
11421     }
11422 
11423     /* Too small: not good enough. Send a fatal alert. */
11424     if (ss->sec.authKeyBits < minKey) {
11425         FATAL_ERROR(ss, SSL_ERROR_WEAK_SERVER_CERT_KEY,
11426                     ss->version >= SSL_LIBRARY_VERSION_TLS_1_0
11427                         ? insufficient_security
11428                         : illegal_parameter);
11429         return SECFailure;
11430     }
11431 
11432     /* PreliminaryChannelInfo.authKeyBits, scheme, and peerDelegCred are now valid. */
11433     ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_peer_auth;
11434 
11435     return SECSuccess;
11436 }
11437 
11438 SECStatus
ssl3_HandleServerSpki(sslSocket * ss)11439 ssl3_HandleServerSpki(sslSocket *ss)
11440 {
11441     PORT_Assert(!ss->sec.isServer);
11442     SECKEYPublicKey *pubKey;
11443 
11444     if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
11445         tls13_IsVerifyingWithDelegatedCredential(ss)) {
11446         sslDelegatedCredential *dc = ss->xtnData.peerDelegCred;
11447         pubKey = SECKEY_ExtractPublicKey(dc->spki);
11448         if (!pubKey) {
11449             PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
11450             return SECFailure;
11451         }
11452 
11453         /* Because we have only a single authType (ssl_auth_tls13_any)
11454          * for TLS 1.3 at this point, set the scheme so that the
11455          * callback can interpret |authKeyBits| correctly.
11456          */
11457         ss->sec.signatureScheme = dc->expectedCertVerifyAlg;
11458     } else {
11459         pubKey = CERT_ExtractPublicKey(ss->sec.peerCert);
11460         if (!pubKey) {
11461             PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
11462             return SECFailure;
11463         }
11464     }
11465 
11466     SECStatus rv = ssl_SetAuthKeyBits(ss, pubKey);
11467     SECKEY_DestroyPublicKey(pubKey);
11468     if (rv != SECSuccess) {
11469         return rv; /* Alert sent and code set. */
11470     }
11471 
11472     return SECSuccess;
11473 }
11474 
11475 SECStatus
ssl3_AuthCertificate(sslSocket * ss)11476 ssl3_AuthCertificate(sslSocket *ss)
11477 {
11478     SECStatus rv;
11479     PRBool isServer = ss->sec.isServer;
11480     int errCode;
11481 
11482     ss->ssl3.hs.authCertificatePending = PR_FALSE;
11483 
11484     PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
11485                 ssl_preinfo_all);
11486 
11487     if (!ss->sec.isServer) {
11488         /* Set the |spki| used to verify the handshake. When verifying with a
11489          * delegated credential (DC), this corresponds to the DC public key;
11490          * otherwise it correspond to the public key of the peer's end-entity
11491          * certificate. */
11492         rv = ssl3_HandleServerSpki(ss);
11493         if (rv != SECSuccess) {
11494             /* Alert sent and code set (if not SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE).
11495              * In either case, we're done here. */
11496             errCode = PORT_GetError();
11497             goto loser;
11498         }
11499 
11500         if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11501             ss->sec.authType = ss->ssl3.hs.kea_def->authKeyType;
11502             ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
11503         }
11504     }
11505 
11506     /*
11507      * Ask caller-supplied callback function to validate cert chain.
11508      */
11509     rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
11510                                            PR_TRUE, isServer);
11511     if (rv != SECSuccess) {
11512         errCode = PORT_GetError();
11513         if (errCode == 0) {
11514             errCode = SSL_ERROR_BAD_CERTIFICATE;
11515         }
11516         if (rv != SECWouldBlock) {
11517             if (ss->handleBadCert) {
11518                 rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
11519             }
11520         }
11521 
11522         if (rv == SECWouldBlock) {
11523             if (ss->sec.isServer) {
11524                 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
11525                 goto loser;
11526             }
11527 
11528             ss->ssl3.hs.authCertificatePending = PR_TRUE;
11529             rv = SECSuccess;
11530         }
11531 
11532         if (rv != SECSuccess) {
11533             ssl3_SendAlertForCertError(ss, errCode);
11534             goto loser;
11535         }
11536     }
11537 
11538     if (ss->sec.ci.sid->peerCert) {
11539         CERT_DestroyCertificate(ss->sec.ci.sid->peerCert);
11540     }
11541     ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
11542 
11543     if (!ss->sec.isServer) {
11544         if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
11545             TLS13_SET_HS_STATE(ss, wait_cert_verify);
11546         } else {
11547             /* Ephemeral suites require ServerKeyExchange. */
11548             if (ss->ssl3.hs.kea_def->ephemeral) {
11549                 /* require server_key_exchange */
11550                 ss->ssl3.hs.ws = wait_server_key;
11551             } else {
11552                 /* disallow server_key_exchange */
11553                 ss->ssl3.hs.ws = wait_cert_request;
11554                 /* This is static RSA key exchange so set the key exchange
11555                  * details to compensate for that. */
11556                 ss->sec.keaKeyBits = ss->sec.authKeyBits;
11557                 ss->sec.signatureScheme = ssl_sig_none;
11558                 ss->sec.keaGroup = NULL;
11559             }
11560         }
11561     } else {
11562         /* Server */
11563         if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11564             ss->ssl3.hs.ws = wait_client_key;
11565         } else {
11566             TLS13_SET_HS_STATE(ss, wait_cert_verify);
11567         }
11568     }
11569 
11570     PORT_Assert(rv == SECSuccess);
11571     if (rv != SECSuccess) {
11572         errCode = SEC_ERROR_LIBRARY_FAILURE;
11573         goto loser;
11574     }
11575 
11576     return SECSuccess;
11577 
11578 loser:
11579     (void)ssl_MapLowLevelError(errCode);
11580     return SECFailure;
11581 }
11582 
11583 static SECStatus ssl3_FinishHandshake(sslSocket *ss);
11584 
11585 static SECStatus
ssl3_AlwaysFail(sslSocket * ss)11586 ssl3_AlwaysFail(sslSocket *ss)
11587 {
11588     /* The caller should have cleared the callback. */
11589     ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
11590     PORT_SetError(PR_INVALID_STATE_ERROR);
11591     return SECFailure;
11592 }
11593 
11594 /* Caller must hold 1stHandshakeLock.
11595 */
11596 SECStatus
ssl3_AuthCertificateComplete(sslSocket * ss,PRErrorCode error)11597 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
11598 {
11599     SECStatus rv;
11600 
11601     PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
11602 
11603     if (ss->sec.isServer) {
11604         PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
11605         return SECFailure;
11606     }
11607 
11608     ssl_GetRecvBufLock(ss);
11609     ssl_GetSSL3HandshakeLock(ss);
11610 
11611     if (!ss->ssl3.hs.authCertificatePending) {
11612         PORT_SetError(PR_INVALID_STATE_ERROR);
11613         rv = SECFailure;
11614         goto done;
11615     }
11616 
11617     ss->ssl3.hs.authCertificatePending = PR_FALSE;
11618 
11619     if (error != 0) {
11620         ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
11621         ssl3_SendAlertForCertError(ss, error);
11622         rv = SECSuccess;
11623     } else if (ss->ssl3.hs.restartTarget != NULL) {
11624         sslRestartTarget target = ss->ssl3.hs.restartTarget;
11625         ss->ssl3.hs.restartTarget = NULL;
11626 
11627         if (target == ssl3_FinishHandshake) {
11628             SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication lost the race"
11629                         " with peer's finished message",
11630                         SSL_GETPID(), ss->fd));
11631         }
11632 
11633         rv = target(ss);
11634     } else {
11635         SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with"
11636                     " peer's finished message",
11637                     SSL_GETPID(), ss->fd));
11638 
11639         PORT_Assert(!ss->ssl3.hs.isResuming);
11640         PORT_Assert(ss->ssl3.hs.ws != idle_handshake);
11641 
11642         if (ss->opt.enableFalseStart &&
11643             !ss->firstHsDone &&
11644             !ss->ssl3.hs.isResuming &&
11645             ssl3_WaitingForServerSecondRound(ss)) {
11646             /* ssl3_SendClientSecondRound deferred the false start check because
11647              * certificate authentication was pending, so we do it now if we still
11648              * haven't received all of the server's second round yet.
11649              */
11650             rv = ssl3_CheckFalseStart(ss);
11651         } else {
11652             rv = SECSuccess;
11653         }
11654     }
11655 
11656 done:
11657     ssl_ReleaseSSL3HandshakeLock(ss);
11658     ssl_ReleaseRecvBufLock(ss);
11659 
11660     return rv;
11661 }
11662 
11663 static SECStatus
ssl3_ComputeTLSFinished(sslSocket * ss,ssl3CipherSpec * spec,PRBool isServer,const SSL3Hashes * hashes,TLSFinished * tlsFinished)11664 ssl3_ComputeTLSFinished(sslSocket *ss, ssl3CipherSpec *spec,
11665                         PRBool isServer,
11666                         const SSL3Hashes *hashes,
11667                         TLSFinished *tlsFinished)
11668 {
11669     SECStatus rv;
11670     CK_TLS_MAC_PARAMS tls_mac_params;
11671     SECItem param = { siBuffer, NULL, 0 };
11672     PK11Context *prf_context;
11673     unsigned int retLen;
11674 
11675     PORT_Assert(spec->masterSecret);
11676     if (!spec->masterSecret) {
11677         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11678         return SECFailure;
11679     }
11680 
11681     if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) {
11682         tls_mac_params.prfHashMechanism = CKM_TLS_PRF;
11683     } else {
11684         tls_mac_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
11685     }
11686     tls_mac_params.ulMacLength = 12;
11687     tls_mac_params.ulServerOrClient = isServer ? 1 : 2;
11688     param.data = (unsigned char *)&tls_mac_params;
11689     param.len = sizeof(tls_mac_params);
11690     prf_context = PK11_CreateContextBySymKey(CKM_TLS_MAC, CKA_SIGN,
11691                                              spec->masterSecret, &param);
11692     if (!prf_context)
11693         return SECFailure;
11694 
11695     rv = PK11_DigestBegin(prf_context);
11696     rv |= PK11_DigestOp(prf_context, hashes->u.raw, hashes->len);
11697     rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data, &retLen,
11698                            sizeof tlsFinished->verify_data);
11699     PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data);
11700 
11701     PK11_DestroyContext(prf_context, PR_TRUE);
11702 
11703     return rv;
11704 }
11705 
11706 /* The calling function must acquire and release the appropriate
11707  * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
11708  * ss->ssl3.crSpec).
11709  */
11710 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)11711 ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec,
11712                             const char *label, unsigned int labelLen,
11713                             const unsigned char *val, unsigned int valLen,
11714                             unsigned char *out, unsigned int outLen)
11715 {
11716     SECItem param = { siBuffer, NULL, 0 };
11717     CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
11718     PK11Context *prf_context;
11719     unsigned int retLen;
11720     SECStatus rv;
11721 
11722     if (!spec->masterSecret) {
11723         PORT_Assert(spec->masterSecret);
11724         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11725         return SECFailure;
11726     }
11727 
11728     if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
11729         /* Bug 1312976 non-SHA256 exporters are broken. */
11730         if (ssl3_GetPrfHashMechanism(ss) != CKM_SHA256) {
11731             PORT_Assert(0);
11732             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11733             return SECFailure;
11734         }
11735         mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
11736     }
11737     prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
11738                                              spec->masterSecret, &param);
11739     if (!prf_context)
11740         return SECFailure;
11741 
11742     rv = PK11_DigestBegin(prf_context);
11743     rv |= PK11_DigestOp(prf_context, (unsigned char *)label, labelLen);
11744     rv |= PK11_DigestOp(prf_context, val, valLen);
11745     rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
11746     PORT_Assert(rv != SECSuccess || retLen == outLen);
11747 
11748     PK11_DestroyContext(prf_context, PR_TRUE);
11749     return rv;
11750 }
11751 
11752 /* called from ssl3_SendClientSecondRound
11753  *             ssl3_HandleFinished
11754  */
11755 static SECStatus
ssl3_SendNextProto(sslSocket * ss)11756 ssl3_SendNextProto(sslSocket *ss)
11757 {
11758     SECStatus rv;
11759     int padding_len;
11760     static const unsigned char padding[32] = { 0 };
11761 
11762     if (ss->xtnData.nextProto.len == 0 ||
11763         ss->xtnData.nextProtoState == SSL_NEXT_PROTO_SELECTED) {
11764         return SECSuccess;
11765     }
11766 
11767     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11768     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11769 
11770     padding_len = 32 - ((ss->xtnData.nextProto.len + 2) % 32);
11771 
11772     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_next_proto, ss->xtnData.nextProto.len + 2 + padding_len);
11773     if (rv != SECSuccess) {
11774         return rv; /* error code set by AppendHandshakeHeader */
11775     }
11776     rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.nextProto.data,
11777                                       ss->xtnData.nextProto.len, 1);
11778     if (rv != SECSuccess) {
11779         return rv; /* error code set by AppendHandshake */
11780     }
11781     rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
11782     if (rv != SECSuccess) {
11783         return rv; /* error code set by AppendHandshake */
11784     }
11785     return rv;
11786 }
11787 
11788 /* called from ssl3_SendFinished and tls13_DeriveSecret.
11789  *
11790  * This function is simply a debugging aid and therefore does not return a
11791  * SECStatus. */
11792 void
ssl3_RecordKeyLog(sslSocket * ss,const char * label,PK11SymKey * secret)11793 ssl3_RecordKeyLog(sslSocket *ss, const char *label, PK11SymKey *secret)
11794 {
11795 #ifdef NSS_ALLOW_SSLKEYLOGFILE
11796     SECStatus rv;
11797     SECItem *keyData;
11798     /* Longest label is "CLIENT_HANDSHAKE_TRAFFIC_SECRET", master secret is 48
11799      * bytes which happens to be the largest in TLS 1.3 as well (SHA384).
11800      * Maximum line length: "CLIENT_HANDSHAKE_TRAFFIC_SECRET" (31) + " " (1) +
11801      * client_random (32*2) + " " (1) +
11802      * traffic_secret (48*2) + "\n" (1) = 194. */
11803     char buf[200];
11804     unsigned int offset, len;
11805 
11806     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11807 
11808     if (!ssl_keylog_iob)
11809         return;
11810 
11811     rv = PK11_ExtractKeyValue(secret);
11812     if (rv != SECSuccess)
11813         return;
11814 
11815     /* keyData does not need to be freed. */
11816     keyData = PK11_GetKeyData(secret);
11817     if (!keyData || !keyData->data)
11818         return;
11819 
11820     len = strlen(label) + 1 +          /* label + space */
11821           SSL3_RANDOM_LENGTH * 2 + 1 + /* client random (hex) + space */
11822           keyData->len * 2 + 1;        /* secret (hex) + newline */
11823     PORT_Assert(len <= sizeof(buf));
11824     if (len > sizeof(buf))
11825         return;
11826 
11827     /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
11828 
11829     /* There could be multiple, concurrent writers to the
11830      * keylog, so we have to do everything in a single call to
11831      * fwrite. */
11832 
11833     strcpy(buf, label);
11834     offset = strlen(label);
11835     buf[offset++] += ' ';
11836     hexEncode(buf + offset, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
11837     offset += SSL3_RANDOM_LENGTH * 2;
11838     buf[offset++] = ' ';
11839     hexEncode(buf + offset, keyData->data, keyData->len);
11840     offset += keyData->len * 2;
11841     buf[offset++] = '\n';
11842 
11843     PORT_Assert(offset == len);
11844 
11845     PZ_Lock(ssl_keylog_lock);
11846     if (fwrite(buf, len, 1, ssl_keylog_iob) == 1)
11847         fflush(ssl_keylog_iob);
11848     PZ_Unlock(ssl_keylog_lock);
11849 #endif
11850 }
11851 
11852 /* called from ssl3_SendClientSecondRound
11853  *             ssl3_HandleClientHello
11854  *             ssl3_HandleFinished
11855  */
11856 static SECStatus
ssl3_SendFinished(sslSocket * ss,PRInt32 flags)11857 ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
11858 {
11859     ssl3CipherSpec *cwSpec;
11860     PRBool isTLS;
11861     PRBool isServer = ss->sec.isServer;
11862     SECStatus rv;
11863     SSL3Sender sender = isServer ? sender_server : sender_client;
11864     SSL3Hashes hashes;
11865     TLSFinished tlsFinished;
11866 
11867     SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
11868 
11869     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11870     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11871 
11872     ssl_GetSpecReadLock(ss);
11873     cwSpec = ss->ssl3.cwSpec;
11874     isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
11875     rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
11876     if (isTLS && rv == SECSuccess) {
11877         rv = ssl3_ComputeTLSFinished(ss, cwSpec, isServer, &hashes, &tlsFinished);
11878     }
11879     ssl_ReleaseSpecReadLock(ss);
11880     if (rv != SECSuccess) {
11881         goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */
11882     }
11883 
11884     if (isTLS) {
11885         if (isServer)
11886             ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
11887         else
11888             ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
11889         ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
11890         rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof tlsFinished);
11891         if (rv != SECSuccess)
11892             goto fail; /* err set by AppendHandshake. */
11893         rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
11894         if (rv != SECSuccess)
11895             goto fail; /* err set by AppendHandshake. */
11896     } else {
11897         if (isServer)
11898             ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
11899         else
11900             ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
11901         PORT_Assert(hashes.len == sizeof hashes.u.s);
11902         ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
11903         rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof hashes.u.s);
11904         if (rv != SECSuccess)
11905             goto fail; /* err set by AppendHandshake. */
11906         rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
11907         if (rv != SECSuccess)
11908             goto fail; /* err set by AppendHandshake. */
11909     }
11910     rv = ssl3_FlushHandshake(ss, flags);
11911     if (rv != SECSuccess) {
11912         goto fail; /* error code set by ssl3_FlushHandshake */
11913     }
11914 
11915     ssl3_RecordKeyLog(ss, "CLIENT_RANDOM", ss->ssl3.cwSpec->masterSecret);
11916 
11917     return SECSuccess;
11918 
11919 fail:
11920     return rv;
11921 }
11922 
11923 /* wrap the master secret, and put it into the SID.
11924  * Caller holds the Spec read lock.
11925  */
11926 SECStatus
ssl3_CacheWrappedSecret(sslSocket * ss,sslSessionID * sid,PK11SymKey * secret)11927 ssl3_CacheWrappedSecret(sslSocket *ss, sslSessionID *sid,
11928                         PK11SymKey *secret)
11929 {
11930     PK11SymKey *wrappingKey = NULL;
11931     PK11SlotInfo *symKeySlot;
11932     void *pwArg = ss->pkcs11PinArg;
11933     SECStatus rv = SECFailure;
11934     PRBool isServer = ss->sec.isServer;
11935     CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
11936 
11937     symKeySlot = PK11_GetSlotFromKey(secret);
11938     if (!isServer) {
11939         int wrapKeyIndex;
11940         int incarnation;
11941 
11942         /* these next few functions are mere accessors and don't fail. */
11943         sid->u.ssl3.masterWrapIndex = wrapKeyIndex =
11944             PK11_GetCurrentWrapIndex(symKeySlot);
11945         PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
11946 
11947         sid->u.ssl3.masterWrapSeries = incarnation =
11948             PK11_GetSlotSeries(symKeySlot);
11949         sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot);
11950         sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
11951         sid->u.ssl3.masterValid = PR_TRUE;
11952         /* Get the default wrapping key, for wrapping the master secret before
11953          * placing it in the SID cache entry. */
11954         wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
11955                                       CKM_INVALID_MECHANISM, incarnation,
11956                                       pwArg);
11957         if (wrappingKey) {
11958             mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
11959         } else {
11960             int keyLength;
11961             /* if the wrappingKey doesn't exist, attempt to create it.
11962              * Note: we intentionally ignore errors here.  If we cannot
11963              * generate a wrapping key, it is not fatal to this SSL connection,
11964              * but we will not be able to restart this session.
11965              */
11966             mechanism = PK11_GetBestWrapMechanism(symKeySlot);
11967             keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
11968             /* Zero length means fixed key length algorithm, or error.
11969              * It's ambiguous.
11970              */
11971             wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
11972                                       keyLength, pwArg);
11973             if (wrappingKey) {
11974                 /* The thread safety characteristics of PK11_[SG]etWrapKey is
11975                 * abominable.  This protects against races in calling
11976                 * PK11_SetWrapKey by dropping and re-acquiring the canonical
11977                 * value once it is set.  The mutex in PK11_[SG]etWrapKey will
11978                 * ensure that races produce the same value in the end. */
11979                 PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
11980                 PK11_FreeSymKey(wrappingKey);
11981                 wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
11982                                               CKM_INVALID_MECHANISM, incarnation, pwArg);
11983                 if (!wrappingKey) {
11984                     PK11_FreeSlot(symKeySlot);
11985                     return SECFailure;
11986                 }
11987             }
11988         }
11989     } else {
11990         /* server socket using session cache. */
11991         mechanism = PK11_GetBestWrapMechanism(symKeySlot);
11992         if (mechanism != CKM_INVALID_MECHANISM) {
11993             wrappingKey =
11994                 ssl3_GetWrappingKey(ss, symKeySlot, mechanism, pwArg);
11995             if (wrappingKey) {
11996                 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
11997             }
11998         }
11999     }
12000 
12001     sid->u.ssl3.masterWrapMech = mechanism;
12002     PK11_FreeSlot(symKeySlot);
12003 
12004     if (wrappingKey) {
12005         SECItem wmsItem;
12006 
12007         wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
12008         wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret;
12009         rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
12010                              secret, &wmsItem);
12011         /* rv is examined below. */
12012         sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
12013         PK11_FreeSymKey(wrappingKey);
12014     }
12015     return rv;
12016 }
12017 
12018 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
12019  * a complete ssl3 Finished message from the peer.
12020  * Caller must hold Handshake and RecvBuf locks.
12021  */
12022 static SECStatus
ssl3_HandleFinished(sslSocket * ss,PRUint8 * b,PRUint32 length)12023 ssl3_HandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
12024 {
12025     SECStatus rv = SECSuccess;
12026     PRBool isServer = ss->sec.isServer;
12027     PRBool isTLS;
12028     SSL3Hashes hashes;
12029 
12030     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12031     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12032 
12033     SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
12034                 SSL_GETPID(), ss->fd));
12035 
12036     if (ss->ssl3.hs.ws != wait_finished) {
12037         SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12038         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
12039         return SECFailure;
12040     }
12041 
12042     if (!ss->sec.isServer || !ss->opt.requestCertificate) {
12043         dtls_ReceivedFirstMessageInFlight(ss);
12044     }
12045 
12046     rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.crSpec, &hashes,
12047                                      isServer ? sender_client : sender_server);
12048     if (rv != SECSuccess) {
12049         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12050         return SECFailure;
12051     }
12052 
12053     rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
12054     if (rv != SECSuccess) {
12055         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12056         return rv;
12057     }
12058 
12059     isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
12060     if (isTLS) {
12061         TLSFinished tlsFinished;
12062 
12063         if (length != sizeof(tlsFinished)) {
12064 #ifndef UNSAFE_FUZZER_MODE
12065             (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
12066             PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12067             return SECFailure;
12068 #endif
12069         }
12070         rv = ssl3_ComputeTLSFinished(ss, ss->ssl3.crSpec, !isServer,
12071                                      &hashes, &tlsFinished);
12072         if (!isServer)
12073             ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
12074         else
12075             ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
12076         ss->ssl3.hs.finishedBytes = sizeof(tlsFinished);
12077         if (rv != SECSuccess ||
12078             0 != NSS_SecureMemcmp(&tlsFinished, b,
12079                                   PR_MIN(length, ss->ssl3.hs.finishedBytes))) {
12080 #ifndef UNSAFE_FUZZER_MODE
12081             (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
12082             PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12083             return SECFailure;
12084 #endif
12085         }
12086     } else {
12087         if (length != sizeof(SSL3Finished)) {
12088             (void)ssl3_IllegalParameter(ss);
12089             PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12090             return SECFailure;
12091         }
12092 
12093         if (!isServer)
12094             ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
12095         else
12096             ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
12097         PORT_Assert(hashes.len == sizeof hashes.u.s);
12098         ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
12099         if (0 != NSS_SecureMemcmp(&hashes.u.s, b, length)) {
12100             (void)ssl3_HandshakeFailure(ss);
12101             PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12102             return SECFailure;
12103         }
12104     }
12105 
12106     ssl_GetXmitBufLock(ss); /*************************************/
12107 
12108     if ((isServer && !ss->ssl3.hs.isResuming) ||
12109         (!isServer && ss->ssl3.hs.isResuming)) {
12110         PRInt32 flags = 0;
12111 
12112         /* Send a NewSessionTicket message if the client sent us
12113          * either an empty session ticket, or one that did not verify.
12114          * (Note that if either of these conditions was met, then the
12115          * server has sent a SessionTicket extension in the
12116          * ServerHello message.)
12117          */
12118         if (isServer && !ss->ssl3.hs.isResuming &&
12119             ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
12120             ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
12121             /* RFC 5077 Section 3.3: "In the case of a full handshake, the
12122              * server MUST verify the client's Finished message before sending
12123              * the ticket." Presumably, this also means that the client's
12124              * certificate, if any, must be verified beforehand too.
12125              */
12126             rv = ssl3_SendNewSessionTicket(ss);
12127             if (rv != SECSuccess) {
12128                 goto xmit_loser;
12129             }
12130         }
12131 
12132         rv = ssl3_SendChangeCipherSpecs(ss);
12133         if (rv != SECSuccess) {
12134             goto xmit_loser; /* err is set. */
12135         }
12136         /* If this thread is in SSL_SecureSend (trying to write some data)
12137         ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
12138         ** last two handshake messages (change cipher spec and finished)
12139         ** will be sent in the same send/write call as the application data.
12140         */
12141         if (ss->writerThread == PR_GetCurrentThread()) {
12142             flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
12143         }
12144 
12145         if (!isServer && !ss->firstHsDone) {
12146             rv = ssl3_SendNextProto(ss);
12147             if (rv != SECSuccess) {
12148                 goto xmit_loser; /* err code was set. */
12149             }
12150         }
12151 
12152         if (IS_DTLS(ss)) {
12153             flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
12154         }
12155 
12156         rv = ssl3_SendFinished(ss, flags);
12157         if (rv != SECSuccess) {
12158             goto xmit_loser; /* err is set. */
12159         }
12160     }
12161 
12162 xmit_loser:
12163     ssl_ReleaseXmitBufLock(ss); /*************************************/
12164     if (rv != SECSuccess) {
12165         return rv;
12166     }
12167 
12168     if (ss->ssl3.hs.authCertificatePending) {
12169         if (ss->ssl3.hs.restartTarget) {
12170             PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
12171             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12172             return SECFailure;
12173         }
12174 
12175         ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
12176         PORT_SetError(PR_WOULD_BLOCK_ERROR);
12177         return SECFailure;
12178     }
12179 
12180     rv = ssl3_FinishHandshake(ss);
12181     return rv;
12182 }
12183 
12184 SECStatus
ssl3_FillInCachedSID(sslSocket * ss,sslSessionID * sid,PK11SymKey * secret)12185 ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid, PK11SymKey *secret)
12186 {
12187     PORT_Assert(secret);
12188 
12189     /* fill in the sid */
12190     sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
12191     sid->u.ssl3.policy = ss->ssl3.policy;
12192     sid->version = ss->version;
12193     sid->authType = ss->sec.authType;
12194     sid->authKeyBits = ss->sec.authKeyBits;
12195     sid->keaType = ss->sec.keaType;
12196     sid->keaKeyBits = ss->sec.keaKeyBits;
12197     if (ss->sec.keaGroup) {
12198         sid->keaGroup = ss->sec.keaGroup->name;
12199     } else {
12200         sid->keaGroup = ssl_grp_none;
12201     }
12202     sid->sigScheme = ss->sec.signatureScheme;
12203     sid->lastAccessTime = sid->creationTime = ssl_Time(ss);
12204     sid->expirationTime = sid->creationTime + (ssl_ticket_lifetime * PR_USEC_PER_SEC);
12205     sid->localCert = CERT_DupCertificate(ss->sec.localCert);
12206     if (ss->sec.isServer) {
12207         sid->namedCurve = ss->sec.serverCert->namedCurve;
12208     }
12209 
12210     if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
12211         ss->xtnData.nextProto.data) {
12212         SECITEM_FreeItem(&sid->u.ssl3.alpnSelection, PR_FALSE);
12213         if (SECITEM_CopyItem(
12214                 NULL, &sid->u.ssl3.alpnSelection, &ss->xtnData.nextProto) != SECSuccess) {
12215             return SECFailure; /* error already set. */
12216         }
12217     }
12218 
12219     /* Copy the master secret (wrapped or unwrapped) into the sid */
12220     return ssl3_CacheWrappedSecret(ss, ss->sec.ci.sid, secret);
12221 }
12222 
12223 /* The return type is SECStatus instead of void because this function needs
12224  * to have type sslRestartTarget.
12225  */
12226 SECStatus
ssl3_FinishHandshake(sslSocket * ss)12227 ssl3_FinishHandshake(sslSocket *ss)
12228 {
12229     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12230     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12231     PORT_Assert(ss->ssl3.hs.restartTarget == NULL);
12232     sslSessionID *sid = ss->sec.ci.sid;
12233     SECStatus sidRv = SECFailure;
12234 
12235     /* The first handshake is now completed. */
12236     ss->handshake = NULL;
12237 
12238     if (sid->cached == never_cached && !ss->opt.noCache) {
12239         /* If the wrap fails, don't cache the sid. The connection proceeds
12240          * normally, so the rv is only used to determine whether we cache. */
12241         sidRv = ssl3_FillInCachedSID(ss, sid, ss->ssl3.crSpec->masterSecret);
12242     }
12243 
12244     /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid
12245     * until it has verified the server's Finished message." When the server
12246     * sends a NewSessionTicket in a resumption handshake, we must wait until
12247     * the handshake is finished (we have verified the server's Finished
12248     * AND the server's certificate) before we update the ticket in the sid.
12249     *
12250     * This must be done before we call ssl_CacheSessionID(ss)
12251     * because CacheSID requires the session ticket to already be set, and also
12252     * because of the lazy lock creation scheme used by CacheSID and
12253     * ssl3_SetSIDSessionTicket. */
12254     if (ss->ssl3.hs.receivedNewSessionTicket) {
12255         PORT_Assert(!ss->sec.isServer);
12256         if (sidRv == SECSuccess) {
12257             /* The sid takes over the ticket data */
12258             ssl3_SetSIDSessionTicket(ss->sec.ci.sid,
12259                                      &ss->ssl3.hs.newSessionTicket);
12260         } else {
12261             PORT_Assert(ss->ssl3.hs.newSessionTicket.ticket.data);
12262             SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket,
12263                              PR_FALSE);
12264         }
12265         PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
12266         ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
12267     }
12268     if (sidRv == SECSuccess) {
12269         PORT_Assert(ss->sec.ci.sid->cached == never_cached);
12270         ssl_CacheSessionID(ss);
12271     }
12272 
12273     ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */
12274     ss->ssl3.hs.ws = idle_handshake;
12275 
12276     ssl_FinishHandshake(ss);
12277 
12278     return SECSuccess;
12279 }
12280 
12281 SECStatus
ssl_HashHandshakeMessageInt(sslSocket * ss,SSLHandshakeType ct,PRUint32 dtlsSeq,const PRUint8 * b,PRUint32 length,sslUpdateHandshakeHashes updateHashes)12282 ssl_HashHandshakeMessageInt(sslSocket *ss, SSLHandshakeType ct,
12283                             PRUint32 dtlsSeq,
12284                             const PRUint8 *b, PRUint32 length,
12285                             sslUpdateHandshakeHashes updateHashes)
12286 {
12287     PRUint8 hdr[4];
12288     PRUint8 dtlsData[8];
12289     SECStatus rv;
12290 
12291     PRINT_BUF(50, (ss, "Hash handshake message:", b, length));
12292 
12293     hdr[0] = (PRUint8)ct;
12294     hdr[1] = (PRUint8)(length >> 16);
12295     hdr[2] = (PRUint8)(length >> 8);
12296     hdr[3] = (PRUint8)(length);
12297 
12298     rv = updateHashes(ss, (unsigned char *)hdr, 4);
12299     if (rv != SECSuccess)
12300         return rv; /* err code already set. */
12301 
12302     /* Extra data to simulate a complete DTLS handshake fragment */
12303     if (IS_DTLS(ss)) {
12304         /* Sequence number */
12305         dtlsData[0] = MSB(dtlsSeq);
12306         dtlsData[1] = LSB(dtlsSeq);
12307 
12308         /* Fragment offset */
12309         dtlsData[2] = 0;
12310         dtlsData[3] = 0;
12311         dtlsData[4] = 0;
12312 
12313         /* Fragment length */
12314         dtlsData[5] = (PRUint8)(length >> 16);
12315         dtlsData[6] = (PRUint8)(length >> 8);
12316         dtlsData[7] = (PRUint8)(length);
12317 
12318         rv = updateHashes(ss, (unsigned char *)dtlsData, sizeof(dtlsData));
12319         if (rv != SECSuccess)
12320             return rv; /* err code already set. */
12321     }
12322 
12323     /* The message body */
12324     rv = updateHashes(ss, b, length);
12325     if (rv != SECSuccess)
12326         return rv; /* err code already set. */
12327 
12328     return SECSuccess;
12329 }
12330 
12331 SECStatus
ssl_HashHandshakeMessage(sslSocket * ss,SSLHandshakeType ct,const PRUint8 * b,PRUint32 length)12332 ssl_HashHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
12333                          const PRUint8 *b, PRUint32 length)
12334 {
12335     return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12336                                        b, length, ssl3_UpdateHandshakeHashes);
12337 }
12338 
12339 SECStatus
ssl_HashHandshakeMessageDefault(sslSocket * ss,SSLHandshakeType ct,const PRUint8 * b,PRUint32 length)12340 ssl_HashHandshakeMessageDefault(sslSocket *ss, SSLHandshakeType ct,
12341                                 const PRUint8 *b, PRUint32 length)
12342 {
12343     return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12344                                        b, length, ssl3_UpdateDefaultHandshakeHashes);
12345 }
12346 SECStatus
ssl_HashHandshakeMessageEchInner(sslSocket * ss,SSLHandshakeType ct,const PRUint8 * b,PRUint32 length)12347 ssl_HashHandshakeMessageEchInner(sslSocket *ss, SSLHandshakeType ct,
12348                                  const PRUint8 *b, PRUint32 length)
12349 {
12350     return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12351                                        b, length, ssl3_UpdateInnerHandshakeHashes);
12352 }
12353 
12354 SECStatus
ssl_HashPostHandshakeMessage(sslSocket * ss,SSLHandshakeType ct,const PRUint8 * b,PRUint32 length)12355 ssl_HashPostHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
12356                              const PRUint8 *b, PRUint32 length)
12357 {
12358     return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12359                                        b, length, ssl3_UpdatePostHandshakeHashes);
12360 }
12361 
12362 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
12363  * handshake message.
12364  * Caller must hold Handshake and RecvBuf locks.
12365  */
12366 SECStatus
ssl3_HandleHandshakeMessage(sslSocket * ss,PRUint8 * b,PRUint32 length,PRBool endOfRecord)12367 ssl3_HandleHandshakeMessage(sslSocket *ss, PRUint8 *b, PRUint32 length,
12368                             PRBool endOfRecord)
12369 {
12370     SECStatus rv = SECSuccess;
12371     PRUint16 epoch;
12372 
12373     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12374     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12375 
12376     SSL_TRC(30, ("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
12377                  ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
12378 
12379     /* Start new handshake hashes when we start a new handshake. */
12380     if (ss->ssl3.hs.msg_type == ssl_hs_client_hello) {
12381         ssl3_RestartHandshakeHashes(ss);
12382     }
12383     switch (ss->ssl3.hs.msg_type) {
12384         case ssl_hs_hello_request:
12385         case ssl_hs_hello_verify_request:
12386             /* We don't include hello_request and hello_verify_request messages
12387              * in the handshake hashes */
12388             break;
12389 
12390         /* Defer hashing of these messages until the message handlers. */
12391         case ssl_hs_client_hello:
12392         case ssl_hs_server_hello:
12393         case ssl_hs_certificate_verify:
12394         case ssl_hs_finished:
12395             break;
12396 
12397         default:
12398             if (!tls13_IsPostHandshake(ss)) {
12399                 rv = ssl_HashHandshakeMessage(ss, ss->ssl3.hs.msg_type, b, length);
12400                 if (rv != SECSuccess) {
12401                     return SECFailure;
12402                 }
12403             }
12404     }
12405 
12406     PORT_SetError(0); /* each message starts with no error. */
12407 
12408     if (ss->ssl3.hs.ws == wait_certificate_status &&
12409         ss->ssl3.hs.msg_type != ssl_hs_certificate_status) {
12410         /* If we negotiated the certificate_status extension then we deferred
12411          * certificate validation until we get the CertificateStatus messsage.
12412          * But the CertificateStatus message is optional. If the server did
12413          * not send it then we need to validate the certificate now. If the
12414          * server does send the CertificateStatus message then we will
12415          * authenticate the certificate in ssl3_HandleCertificateStatus.
12416          */
12417         rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
12418         if (rv != SECSuccess) {
12419             /* This can't block. */
12420             PORT_Assert(PORT_GetError() != PR_WOULD_BLOCK_ERROR);
12421             return SECFailure;
12422         }
12423     }
12424 
12425     epoch = ss->ssl3.crSpec->epoch;
12426     switch (ss->ssl3.hs.msg_type) {
12427         case ssl_hs_client_hello:
12428             if (!ss->sec.isServer) {
12429                 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12430                 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
12431                 return SECFailure;
12432             }
12433             rv = ssl3_HandleClientHello(ss, b, length);
12434             break;
12435         case ssl_hs_server_hello:
12436             if (ss->sec.isServer) {
12437                 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12438                 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
12439                 return SECFailure;
12440             }
12441             rv = ssl3_HandleServerHello(ss, b, length);
12442             break;
12443         default:
12444             if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
12445                 rv = ssl3_HandlePostHelloHandshakeMessage(ss, b, length);
12446             } else {
12447                 rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length);
12448             }
12449             break;
12450     }
12451     if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
12452         (epoch != ss->ssl3.crSpec->epoch) && !endOfRecord) {
12453         /* If we changed read cipher states, there must not be any
12454          * data in the input queue. */
12455         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12456         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
12457         return SECFailure;
12458     }
12459 
12460     if (IS_DTLS(ss) && (rv != SECFailure)) {
12461         /* Increment the expected sequence number */
12462         ss->ssl3.hs.recvMessageSeq++;
12463     }
12464 
12465     /* Taint the message so that it's easier to detect UAFs. */
12466     PORT_Memset(b, 'N', length);
12467 
12468     return rv;
12469 }
12470 
12471 static SECStatus
ssl3_HandlePostHelloHandshakeMessage(sslSocket * ss,PRUint8 * b,PRUint32 length)12472 ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b,
12473                                      PRUint32 length)
12474 {
12475     SECStatus rv;
12476     PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
12477 
12478     switch (ss->ssl3.hs.msg_type) {
12479         case ssl_hs_hello_request:
12480             if (length != 0) {
12481                 (void)ssl3_DecodeError(ss);
12482                 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
12483                 return SECFailure;
12484             }
12485             if (ss->sec.isServer) {
12486                 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12487                 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
12488                 return SECFailure;
12489             }
12490             rv = ssl3_HandleHelloRequest(ss);
12491             break;
12492 
12493         case ssl_hs_hello_verify_request:
12494             if (!IS_DTLS(ss) || ss->sec.isServer) {
12495                 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12496                 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
12497                 return SECFailure;
12498             }
12499             rv = dtls_HandleHelloVerifyRequest(ss, b, length);
12500             break;
12501         case ssl_hs_certificate:
12502             rv = ssl3_HandleCertificate(ss, b, length);
12503             break;
12504         case ssl_hs_certificate_status:
12505             rv = ssl3_HandleCertificateStatus(ss, b, length);
12506             break;
12507         case ssl_hs_server_key_exchange:
12508             if (ss->sec.isServer) {
12509                 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12510                 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
12511                 return SECFailure;
12512             }
12513             rv = ssl3_HandleServerKeyExchange(ss, b, length);
12514             break;
12515         case ssl_hs_certificate_request:
12516             if (ss->sec.isServer) {
12517                 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12518                 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
12519                 return SECFailure;
12520             }
12521             rv = ssl3_HandleCertificateRequest(ss, b, length);
12522             break;
12523         case ssl_hs_server_hello_done:
12524             if (length != 0) {
12525                 (void)ssl3_DecodeError(ss);
12526                 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
12527                 return SECFailure;
12528             }
12529             if (ss->sec.isServer) {
12530                 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12531                 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
12532                 return SECFailure;
12533             }
12534             rv = ssl3_HandleServerHelloDone(ss);
12535             break;
12536         case ssl_hs_certificate_verify:
12537             if (!ss->sec.isServer) {
12538                 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12539                 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
12540                 return SECFailure;
12541             }
12542             rv = ssl3_HandleCertificateVerify(ss, b, length);
12543             break;
12544         case ssl_hs_client_key_exchange:
12545             if (!ss->sec.isServer) {
12546                 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12547                 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
12548                 return SECFailure;
12549             }
12550             rv = ssl3_HandleClientKeyExchange(ss, b, length);
12551             break;
12552         case ssl_hs_new_session_ticket:
12553             if (ss->sec.isServer) {
12554                 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12555                 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
12556                 return SECFailure;
12557             }
12558             rv = ssl3_HandleNewSessionTicket(ss, b, length);
12559             break;
12560         case ssl_hs_finished:
12561             rv = ssl3_HandleFinished(ss, b, length);
12562             break;
12563         default:
12564             (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12565             PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
12566             rv = SECFailure;
12567     }
12568 
12569     return rv;
12570 }
12571 
12572 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
12573  * origBuf is the decrypted ssl record content.
12574  * Caller must hold the handshake and RecvBuf locks.
12575  */
12576 static SECStatus
ssl3_HandleHandshake(sslSocket * ss,sslBuffer * origBuf)12577 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
12578 {
12579     sslBuffer buf = *origBuf; /* Work from a copy. */
12580     SECStatus rv;
12581 
12582     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12583     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12584 
12585     while (buf.len > 0) {
12586         if (ss->ssl3.hs.header_bytes < 4) {
12587             PRUint8 t;
12588             t = *(buf.buf++);
12589             buf.len--;
12590             if (ss->ssl3.hs.header_bytes++ == 0)
12591                 ss->ssl3.hs.msg_type = (SSLHandshakeType)t;
12592             else
12593                 ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
12594             if (ss->ssl3.hs.header_bytes < 4)
12595                 continue;
12596 
12597 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
12598             if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
12599                 (void)ssl3_DecodeError(ss);
12600                 PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
12601                 goto loser;
12602             }
12603 #undef MAX_HANDSHAKE_MSG_LEN
12604 
12605             /* If msg_len is zero, be sure we fall through,
12606             ** even if buf.len is zero.
12607             */
12608             if (ss->ssl3.hs.msg_len > 0)
12609                 continue;
12610         }
12611 
12612         /*
12613          * Header has been gathered and there is at least one byte of new
12614          * data available for this message. If it can be done right out
12615          * of the original buffer, then use it from there.
12616          */
12617         if (ss->ssl3.hs.msg_body.len == 0 && buf.len >= ss->ssl3.hs.msg_len) {
12618             /* handle it from input buffer */
12619             rv = ssl3_HandleHandshakeMessage(ss, buf.buf, ss->ssl3.hs.msg_len,
12620                                              buf.len == ss->ssl3.hs.msg_len);
12621             buf.buf += ss->ssl3.hs.msg_len;
12622             buf.len -= ss->ssl3.hs.msg_len;
12623             ss->ssl3.hs.msg_len = 0;
12624             ss->ssl3.hs.header_bytes = 0;
12625             if (rv != SECSuccess) {
12626                 goto loser;
12627             }
12628         } else {
12629             /* must be copied to msg_body and dealt with from there */
12630             unsigned int bytes;
12631 
12632             PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
12633             bytes = PR_MIN(buf.len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
12634 
12635             /* Grow the buffer if needed */
12636             rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
12637             if (rv != SECSuccess) {
12638                 /* sslBuffer_Grow has set a memory error code. */
12639                 goto loser;
12640             }
12641 
12642             PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
12643                         buf.buf, bytes);
12644             ss->ssl3.hs.msg_body.len += bytes;
12645             buf.buf += bytes;
12646             buf.len -= bytes;
12647 
12648             PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
12649 
12650             /* if we have a whole message, do it */
12651             if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
12652                 rv = ssl3_HandleHandshakeMessage(
12653                     ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len,
12654                     buf.len == 0);
12655                 ss->ssl3.hs.msg_body.len = 0;
12656                 ss->ssl3.hs.msg_len = 0;
12657                 ss->ssl3.hs.header_bytes = 0;
12658                 if (rv != SECSuccess) {
12659                     goto loser;
12660                 }
12661             } else {
12662                 PORT_Assert(buf.len == 0);
12663                 break;
12664             }
12665         }
12666     } /* end loop */
12667 
12668     origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
12669     return SECSuccess;
12670 
12671 loser : {
12672     /* Make sure to remove any data that was consumed. */
12673     unsigned int consumed = origBuf->len - buf.len;
12674     PORT_Assert(consumed == buf.buf - origBuf->buf);
12675     if (consumed > 0) {
12676         memmove(origBuf->buf, origBuf->buf + consumed, buf.len);
12677         origBuf->len = buf.len;
12678     }
12679 }
12680     return SECFailure;
12681 }
12682 
12683 /* SECStatusToMask returns, in constant time, a mask value of all ones if
12684  * rv == SECSuccess.  Otherwise it returns zero. */
12685 static unsigned int
SECStatusToMask(SECStatus rv)12686 SECStatusToMask(SECStatus rv)
12687 {
12688     return PORT_CT_EQ(rv, SECSuccess);
12689 }
12690 
12691 /* ssl_ConstantTimeGE returns 0xffffffff if a>=b and 0x00 otherwise. */
12692 static unsigned char
ssl_ConstantTimeGE(unsigned int a,unsigned int b)12693 ssl_ConstantTimeGE(unsigned int a, unsigned int b)
12694 {
12695     return PORT_CT_GE(a, b);
12696 }
12697 
12698 /* ssl_ConstantTimeEQ returns 0xffffffff if a==b and 0x00 otherwise. */
12699 static unsigned char
ssl_ConstantTimeEQ(unsigned char a,unsigned char b)12700 ssl_ConstantTimeEQ(unsigned char a, unsigned char b)
12701 {
12702     return PORT_CT_EQ(a, b);
12703 }
12704 
12705 /* ssl_constantTimeSelect return a if mask is 0xFF and b if mask is 0x00 */
12706 static unsigned char
ssl_constantTimeSelect(unsigned char mask,unsigned char a,unsigned char b)12707 ssl_constantTimeSelect(unsigned char mask, unsigned char a, unsigned char b)
12708 {
12709     return (mask & a) | (~mask & b);
12710 }
12711 
12712 static SECStatus
ssl_RemoveSSLv3CBCPadding(sslBuffer * plaintext,unsigned int blockSize,unsigned int macSize)12713 ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
12714                           unsigned int blockSize,
12715                           unsigned int macSize)
12716 {
12717     unsigned int paddingLength, good;
12718     const unsigned int overhead = 1 /* padding length byte */ + macSize;
12719 
12720     /* These lengths are all public so we can test them in non-constant
12721      * time. */
12722     if (overhead > plaintext->len) {
12723         return SECFailure;
12724     }
12725 
12726     paddingLength = plaintext->buf[plaintext->len - 1];
12727     /* SSLv3 padding bytes are random and cannot be checked. */
12728     good = PORT_CT_GE(plaintext->len, paddingLength + overhead);
12729     /* SSLv3 requires that the padding is minimal. */
12730     good &= PORT_CT_GE(blockSize, paddingLength + 1);
12731     plaintext->len -= good & (paddingLength + 1);
12732     return (good & SECSuccess) | (~good & SECFailure);
12733 }
12734 
12735 SECStatus
ssl_RemoveTLSCBCPadding(sslBuffer * plaintext,unsigned int macSize)12736 ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
12737 {
12738     unsigned int paddingLength, good, toCheck, i;
12739     const unsigned int overhead = 1 /* padding length byte */ + macSize;
12740 
12741     /* These lengths are all public so we can test them in non-constant
12742      * time. */
12743     if (overhead > plaintext->len) {
12744         return SECFailure;
12745     }
12746 
12747     paddingLength = plaintext->buf[plaintext->len - 1];
12748     good = PORT_CT_GE(plaintext->len, paddingLength + overhead);
12749 
12750     /* The padding consists of a length byte at the end of the record and then
12751      * that many bytes of padding, all with the same value as the length byte.
12752      * Thus, with the length byte included, there are paddingLength+1 bytes of
12753      * padding.
12754      *
12755      * We can't check just |paddingLength+1| bytes because that leaks
12756      * decrypted information. Therefore we always have to check the maximum
12757      * amount of padding possible. (Again, the length of the record is
12758      * public information so we can use it.) */
12759     toCheck = 256; /* maximum amount of padding + 1. */
12760     if (toCheck > plaintext->len) {
12761         toCheck = plaintext->len;
12762     }
12763 
12764     for (i = 0; i < toCheck; i++) {
12765         /* If i <= paddingLength then the MSB of t is zero and mask is
12766          * 0xff.  Otherwise, mask is 0. */
12767         unsigned char mask = PORT_CT_LE(i, paddingLength);
12768         unsigned char b = plaintext->buf[plaintext->len - 1 - i];
12769         /* The final |paddingLength+1| bytes should all have the value
12770          * |paddingLength|. Therefore the XOR should be zero. */
12771         good &= ~(mask & (paddingLength ^ b));
12772     }
12773 
12774     /* If any of the final |paddingLength+1| bytes had the wrong value,
12775      * one or more of the lower eight bits of |good| will be cleared. We
12776      * AND the bottom 8 bits together and duplicate the result to all the
12777      * bits. */
12778     good &= good >> 4;
12779     good &= good >> 2;
12780     good &= good >> 1;
12781     good <<= sizeof(good) * 8 - 1;
12782     good = PORT_CT_DUPLICATE_MSB_TO_ALL(good);
12783 
12784     plaintext->len -= good & (paddingLength + 1);
12785     return (good & SECSuccess) | (~good & SECFailure);
12786 }
12787 
12788 /* On entry:
12789  *   originalLength >= macSize
12790  *   macSize <= MAX_MAC_LENGTH
12791  *   plaintext->len >= macSize
12792  */
12793 static void
ssl_CBCExtractMAC(sslBuffer * plaintext,unsigned int originalLength,PRUint8 * out,unsigned int macSize)12794 ssl_CBCExtractMAC(sslBuffer *plaintext,
12795                   unsigned int originalLength,
12796                   PRUint8 *out,
12797                   unsigned int macSize)
12798 {
12799     unsigned char rotatedMac[MAX_MAC_LENGTH];
12800     /* macEnd is the index of |plaintext->buf| just after the end of the
12801      * MAC. */
12802     unsigned macEnd = plaintext->len;
12803     unsigned macStart = macEnd - macSize;
12804     /* scanStart contains the number of bytes that we can ignore because
12805      * the MAC's position can only vary by 255 bytes. */
12806     unsigned scanStart = 0;
12807     unsigned i, j;
12808     unsigned char rotateOffset;
12809 
12810     if (originalLength > macSize + 255 + 1) {
12811         scanStart = originalLength - (macSize + 255 + 1);
12812     }
12813 
12814     /* We want to compute
12815      * rotateOffset = (macStart - scanStart) % macSize
12816      * But the time to compute this varies based on the amount of padding. Thus
12817      * we explicitely handle all mac sizes with (hopefully) constant time modulo
12818      * using Barrett reduction:
12819      *  q := (rotateOffset * m) >> k
12820      *  rotateOffset -= q * n
12821      *  if (n <= rotateOffset) rotateOffset -= n
12822      */
12823     rotateOffset = macStart - scanStart;
12824     /* rotateOffset < 255 + 1 + 48 = 304 */
12825     if (macSize == 16) {
12826         rotateOffset &= 15;
12827     } else if (macSize == 20) {
12828         /*
12829          * Correctness: rotateOffset * ( 1/20 - 25/2^9 ) < 1
12830          *              with rotateOffset <= 853
12831          */
12832         unsigned q = (rotateOffset * 25) >> 9;
12833         rotateOffset -= q * 20;
12834         rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 20),
12835                                                20, 0);
12836     } else if (macSize == 32) {
12837         rotateOffset &= 31;
12838     } else if (macSize == 48) {
12839         /*
12840          * Correctness: rotateOffset * ( 1/48 - 10/2^9 ) < 1
12841          *              with rotateOffset < 768
12842          */
12843         unsigned q = (rotateOffset * 10) >> 9;
12844         rotateOffset -= q * 48;
12845         rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 48),
12846                                                48, 0);
12847     } else {
12848         /*
12849          * SHA384 (macSize == 48) is the largest we support. We should never
12850          * get here.
12851          */
12852         PORT_Assert(0);
12853         rotateOffset = rotateOffset % macSize;
12854     }
12855 
12856     memset(rotatedMac, 0, macSize);
12857     for (i = scanStart; i < originalLength;) {
12858         for (j = 0; j < macSize && i < originalLength; i++, j++) {
12859             unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
12860             unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
12861             unsigned char b = 0;
12862             b = plaintext->buf[i];
12863             rotatedMac[j] |= b & macStarted & ~macEnded;
12864         }
12865     }
12866 
12867     /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
12868      * we could line-align |rotatedMac| and rotate in place. */
12869     memset(out, 0, macSize);
12870     rotateOffset = macSize - rotateOffset;
12871     rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
12872                                           0, rotateOffset);
12873     for (i = 0; i < macSize; i++) {
12874         for (j = 0; j < macSize; j++) {
12875             out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ(j, rotateOffset);
12876         }
12877         rotateOffset++;
12878         rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
12879                                               0, rotateOffset);
12880     }
12881 }
12882 
12883 /* Unprotect an SSL3 record and leave the result in plaintext.
12884  *
12885  * If SECFailure is returned, we:
12886  * 1. Set |*alert| to the alert to be sent.
12887  * 2. Call PORT_SetError() with an appropriate code.
12888  *
12889  * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
12890  * Therefore, we MUST not call SSL3_SendAlert().
12891  *
12892  */
12893 static SECStatus
ssl3_UnprotectRecord(sslSocket * ss,ssl3CipherSpec * spec,SSL3Ciphertext * cText,sslBuffer * plaintext,SSL3AlertDescription * alert)12894 ssl3_UnprotectRecord(sslSocket *ss,
12895                      ssl3CipherSpec *spec,
12896                      SSL3Ciphertext *cText, sslBuffer *plaintext,
12897                      SSL3AlertDescription *alert)
12898 {
12899     const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
12900     PRBool isTLS;
12901     unsigned int good;
12902     unsigned int ivLen = 0;
12903     SSLContentType rType;
12904     SSL3ProtocolVersion rVersion;
12905     unsigned int minLength;
12906     unsigned int originalLen = 0;
12907     PRUint8 headerBuf[13];
12908     sslBuffer header = SSL_BUFFER(headerBuf);
12909     PRUint8 hash[MAX_MAC_LENGTH];
12910     PRUint8 givenHashBuf[MAX_MAC_LENGTH];
12911     PRUint8 *givenHash;
12912     unsigned int hashBytes = MAX_MAC_LENGTH + 1;
12913     SECStatus rv;
12914 
12915     PORT_Assert(spec->direction == ssl_secret_read);
12916 
12917     good = ~0U;
12918     minLength = spec->macDef->mac_size;
12919     if (cipher_def->type == type_block) {
12920         /* CBC records have a padding length byte at the end. */
12921         minLength++;
12922         if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
12923             /* With >= TLS 1.1, CBC records have an explicit IV. */
12924             minLength += cipher_def->iv_size;
12925         }
12926     } else if (cipher_def->type == type_aead) {
12927         minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
12928     }
12929 
12930     /* We can perform this test in variable time because the record's total
12931      * length and the ciphersuite are both public knowledge. */
12932     if (cText->buf->len < minLength) {
12933         goto decrypt_loser;
12934     }
12935 
12936     if (cipher_def->type == type_block &&
12937         spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
12938         /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
12939          * "The receiver decrypts the entire GenericBlockCipher structure and
12940          * then discards the first cipher block corresponding to the IV
12941          * component." Instead, we decrypt the first cipher block and then
12942          * discard it before decrypting the rest.
12943          */
12944         PRUint8 iv[MAX_IV_LENGTH];
12945         unsigned int decoded;
12946 
12947         ivLen = cipher_def->iv_size;
12948         if (ivLen < 8 || ivLen > sizeof(iv)) {
12949             *alert = internal_error;
12950             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12951             return SECFailure;
12952         }
12953 
12954         PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
12955 
12956         /* The decryption result is garbage, but since we just throw away
12957          * the block it doesn't matter.  The decryption of the next block
12958          * depends only on the ciphertext of the IV block.
12959          */
12960         rv = spec->cipher(spec->cipherContext, iv, &decoded,
12961                           sizeof(iv), cText->buf->buf, ivLen);
12962 
12963         good &= SECStatusToMask(rv);
12964     }
12965 
12966     PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
12967                    cText->buf->len - ivLen));
12968 
12969     isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
12970 
12971     if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) {
12972         *alert = record_overflow;
12973         PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
12974         return SECFailure;
12975     }
12976 
12977     rType = (SSLContentType)cText->hdr[0];
12978     rVersion = ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
12979                (SSL3ProtocolVersion)cText->hdr[2];
12980     if (cipher_def->type == type_aead) {
12981         /* XXX For many AEAD ciphers, the plaintext is shorter than the
12982          * ciphertext by a fixed byte count, but it is not true in general.
12983          * Each AEAD cipher should provide a function that returns the
12984          * plaintext length for a given ciphertext. */
12985         const unsigned int explicitNonceLen = cipher_def->explicit_nonce_size;
12986         const unsigned int tagLen = cipher_def->tag_size;
12987         unsigned int nonceLen = explicitNonceLen;
12988         unsigned int decryptedLen = cText->buf->len - nonceLen - tagLen;
12989         /* even though read doesn't return and IV, we still need a space to put
12990          * the combined iv/nonce n the gcm 1.2 case*/
12991         unsigned char ivOut[MAX_IV_LENGTH];
12992         unsigned char *iv = NULL;
12993         unsigned char *nonce = NULL;
12994 
12995         ivLen = cipher_def->iv_size;
12996 
12997         rv = ssl3_BuildRecordPseudoHeader(
12998             spec->epoch, cText->seqNum,
12999             rType, isTLS, rVersion, IS_DTLS(ss), decryptedLen, &header);
13000         PORT_Assert(rv == SECSuccess);
13001 
13002         /* build the iv */
13003         if (explicitNonceLen == 0) {
13004             nonceLen = sizeof(cText->seqNum);
13005             iv = spec->keyMaterial.iv;
13006             nonce = SSL_BUFFER_BASE(&header);
13007         } else {
13008             PORT_Memcpy(ivOut, spec->keyMaterial.iv, ivLen);
13009             PORT_Memset(ivOut + ivLen, 0, explicitNonceLen);
13010             iv = ivOut;
13011             nonce = cText->buf->buf;
13012             nonceLen = explicitNonceLen;
13013         }
13014         rv = tls13_AEAD(spec->cipherContext, PR_TRUE,
13015                         CKG_NO_GENERATE, 0,       /* iv generator params
13016                                                         * (not used in decrypt)*/
13017                         iv,                       /* iv in */
13018                         NULL,                     /* iv out */
13019                         ivLen + explicitNonceLen, /* full iv length */
13020                         nonce, nonceLen,          /* nonce in */
13021                         SSL_BUFFER_BASE(&header), /* aad */
13022                         SSL_BUFFER_LEN(&header),  /* aadlen */
13023                         plaintext->buf,           /* output  */
13024                         &plaintext->len,          /* out len */
13025                         plaintext->space,         /* max out */
13026                         tagLen,
13027                         cText->buf->buf + explicitNonceLen,  /* input */
13028                         cText->buf->len - explicitNonceLen); /* input len */
13029         if (rv != SECSuccess) {
13030             good = 0;
13031         }
13032     } else {
13033         if (cipher_def->type == type_block &&
13034             ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
13035             goto decrypt_loser;
13036         }
13037 
13038         /* decrypt from cText buf to plaintext. */
13039         rv = spec->cipher(
13040             spec->cipherContext, plaintext->buf, &plaintext->len,
13041             plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
13042         if (rv != SECSuccess) {
13043             goto decrypt_loser;
13044         }
13045 
13046         PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
13047 
13048         originalLen = plaintext->len;
13049 
13050         /* If it's a block cipher, check and strip the padding. */
13051         if (cipher_def->type == type_block) {
13052             const unsigned int blockSize = cipher_def->block_size;
13053             const unsigned int macSize = spec->macDef->mac_size;
13054 
13055             if (!isTLS) {
13056                 good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
13057                     plaintext, blockSize, macSize));
13058             } else {
13059                 good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
13060                     plaintext, macSize));
13061             }
13062         }
13063 
13064         /* compute the MAC */
13065         rv = ssl3_BuildRecordPseudoHeader(
13066             spec->epoch, cText->seqNum,
13067             rType, isTLS, rVersion, IS_DTLS(ss),
13068             plaintext->len - spec->macDef->mac_size, &header);
13069         PORT_Assert(rv == SECSuccess);
13070         if (cipher_def->type == type_block) {
13071             rv = ssl3_ComputeRecordMACConstantTime(
13072                 spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
13073                 plaintext->buf, plaintext->len, originalLen,
13074                 hash, &hashBytes);
13075 
13076             ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
13077                               spec->macDef->mac_size);
13078             givenHash = givenHashBuf;
13079 
13080             /* plaintext->len will always have enough space to remove the MAC
13081              * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
13082              * plaintext->len if the result has enough space for the MAC and we
13083              * tested the unadjusted size against minLength, above. */
13084             plaintext->len -= spec->macDef->mac_size;
13085         } else {
13086             /* This is safe because we checked the minLength above. */
13087             plaintext->len -= spec->macDef->mac_size;
13088 
13089             rv = ssl3_ComputeRecordMAC(
13090                 spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
13091                 plaintext->buf, plaintext->len, hash, &hashBytes);
13092 
13093             /* We can read the MAC directly from the record because its location
13094              * is public when a stream cipher is used. */
13095             givenHash = plaintext->buf + plaintext->len;
13096         }
13097 
13098         good &= SECStatusToMask(rv);
13099 
13100         if (hashBytes != (unsigned)spec->macDef->mac_size ||
13101             NSS_SecureMemcmp(givenHash, hash, spec->macDef->mac_size) != 0) {
13102             /* We're allowed to leak whether or not the MAC check was correct */
13103             good = 0;
13104         }
13105     }
13106 
13107     if (good == 0) {
13108     decrypt_loser:
13109         /* always log mac error, in case attacker can read server logs. */
13110         PORT_SetError(SSL_ERROR_BAD_MAC_READ);
13111         *alert = bad_record_mac;
13112         return SECFailure;
13113     }
13114     return SECSuccess;
13115 }
13116 
13117 SECStatus
ssl3_HandleNonApplicationData(sslSocket * ss,SSLContentType rType,DTLSEpoch epoch,sslSequenceNumber seqNum,sslBuffer * databuf)13118 ssl3_HandleNonApplicationData(sslSocket *ss, SSLContentType rType,
13119                               DTLSEpoch epoch, sslSequenceNumber seqNum,
13120                               sslBuffer *databuf)
13121 {
13122     SECStatus rv;
13123 
13124     /* check for Token Presence */
13125     if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13126         PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13127         return SECFailure;
13128     }
13129 
13130     ssl_GetSSL3HandshakeLock(ss);
13131 
13132     /* All the functions called in this switch MUST set error code if
13133     ** they return SECFailure.
13134     */
13135     switch (rType) {
13136         case ssl_ct_change_cipher_spec:
13137             rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
13138             break;
13139         case ssl_ct_alert:
13140             rv = ssl3_HandleAlert(ss, databuf);
13141             break;
13142         case ssl_ct_handshake:
13143             if (!IS_DTLS(ss)) {
13144                 rv = ssl3_HandleHandshake(ss, databuf);
13145             } else {
13146                 rv = dtls_HandleHandshake(ss, epoch, seqNum, databuf);
13147             }
13148             break;
13149         case ssl_ct_ack:
13150             if (IS_DTLS(ss) && tls13_MaybeTls13(ss)) {
13151                 rv = dtls13_HandleAck(ss, databuf);
13152                 break;
13153             }
13154         /* Fall through. */
13155         default:
13156             SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
13157                      SSL_GETPID(), ss->fd, rType));
13158             PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
13159             ssl3_DecodeError(ss);
13160             rv = SECFailure;
13161             break;
13162     }
13163 
13164     ssl_ReleaseSSL3HandshakeLock(ss);
13165     return rv;
13166 }
13167 
13168 /* Find the cipher spec to use for a given record. For TLS, this
13169  * is the current cipherspec. For DTLS, we look up by epoch.
13170  * In DTLS < 1.3 this just means the current epoch or nothing,
13171  * but in DTLS >= 1.3, we keep multiple reading cipherspecs.
13172  * Returns NULL if no appropriate cipher spec is found.
13173  */
13174 static ssl3CipherSpec *
ssl3_GetCipherSpec(sslSocket * ss,SSL3Ciphertext * cText)13175 ssl3_GetCipherSpec(sslSocket *ss, SSL3Ciphertext *cText)
13176 {
13177     ssl3CipherSpec *crSpec = ss->ssl3.crSpec;
13178     ssl3CipherSpec *newSpec = NULL;
13179     DTLSEpoch epoch;
13180 
13181     if (!IS_DTLS(ss)) {
13182         return crSpec;
13183     }
13184     epoch = dtls_ReadEpoch(crSpec, cText->hdr);
13185     if (crSpec->epoch == epoch) {
13186         return crSpec;
13187     }
13188     if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
13189         /* Try to find the cipher spec. */
13190         newSpec = ssl_FindCipherSpecByEpoch(ss, ssl_secret_read,
13191                                             epoch);
13192         if (newSpec != NULL) {
13193             return newSpec;
13194         }
13195     }
13196     SSL_TRC(10, ("%d: DTLS[%d]: Couldn't find cipherspec from epoch %d",
13197                  SSL_GETPID(), ss->fd, epoch));
13198     return NULL;
13199 }
13200 
13201 /* MAX_EXPANSION is the amount by which a record might plausibly be expanded
13202  * when protected.  It's the worst case estimate, so the sum of block cipher
13203  * padding (up to 256 octets), HMAC (48 octets for SHA-384), and IV (16
13204  * octets for AES). */
13205 #define MAX_EXPANSION (256 + 48 + 16)
13206 
13207 /* if cText is non-null, then decipher and check the MAC of the
13208  * SSL record from cText->buf (typically gs->inbuf)
13209  * into databuf (typically gs->buf), and any previous contents of databuf
13210  * is lost.  Then handle databuf according to its SSL record type,
13211  * unless it's an application record.
13212  *
13213  * If cText is NULL, then the ciphertext has previously been deciphered and
13214  * checked, and is already sitting in databuf.  It is processed as an SSL
13215  * Handshake message.
13216  *
13217  * DOES NOT process the decrypted application data.
13218  * On return, databuf contains the decrypted record.
13219  *
13220  * Called from ssl3_GatherCompleteHandshake
13221  *             ssl3_RestartHandshakeAfterCertReq
13222  *
13223  * Caller must hold the RecvBufLock.
13224  *
13225  * This function aquires and releases the SSL3Handshake Lock, holding the
13226  * lock around any calls to functions that handle records other than
13227  * Application Data records.
13228  */
13229 SECStatus
ssl3_HandleRecord(sslSocket * ss,SSL3Ciphertext * cText)13230 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText)
13231 {
13232     SECStatus rv;
13233     PRBool isTLS;
13234     DTLSEpoch epoch;
13235     ssl3CipherSpec *spec = NULL;
13236     PRUint16 recordSizeLimit;
13237     PRBool outOfOrderSpec = PR_FALSE;
13238     SSLContentType rType;
13239     sslBuffer *plaintext = &ss->gs.buf;
13240     SSL3AlertDescription alert = internal_error;
13241     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
13242 
13243     /* check for Token Presence */
13244     if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13245         PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13246         return SECFailure;
13247     }
13248 
13249     /* Clear out the buffer in case this exits early.  Any data then won't be
13250      * processed twice. */
13251     plaintext->len = 0;
13252 
13253     /* We're waiting for another ClientHello, which will appear unencrypted.
13254      * Use the content type to tell whether this should be discarded. */
13255     if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr &&
13256         cText->hdr[0] == ssl_ct_application_data) {
13257         PORT_Assert(ss->ssl3.hs.ws == wait_client_hello);
13258         return SECSuccess;
13259     }
13260 
13261     ssl_GetSpecReadLock(ss); /******************************************/
13262     spec = ssl3_GetCipherSpec(ss, cText);
13263     if (!spec) {
13264         PORT_Assert(IS_DTLS(ss));
13265         ssl_ReleaseSpecReadLock(ss); /*****************************/
13266         return SECSuccess;
13267     }
13268     if (spec != ss->ssl3.crSpec) {
13269         PORT_Assert(IS_DTLS(ss));
13270         SSL_TRC(3, ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d",
13271                     SSL_GETPID(), ss->fd, spec->epoch));
13272         outOfOrderSpec = PR_TRUE;
13273     }
13274     isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
13275     if (IS_DTLS(ss)) {
13276         if (dtls13_MaskSequenceNumber(ss, spec, cText->hdr,
13277                                       SSL_BUFFER_BASE(cText->buf), SSL_BUFFER_LEN(cText->buf)) != SECSuccess) {
13278             ssl_ReleaseSpecReadLock(ss); /*****************************/
13279             /* code already set. */
13280             return SECFailure;
13281         }
13282         if (!dtls_IsRelevant(ss, spec, cText, &cText->seqNum)) {
13283             ssl_ReleaseSpecReadLock(ss); /*****************************/
13284             return SECSuccess;
13285         }
13286     } else {
13287         cText->seqNum = spec->nextSeqNum;
13288     }
13289     if (cText->seqNum >= spec->cipherDef->max_records) {
13290         ssl_ReleaseSpecReadLock(ss); /*****************************/
13291         SSL_TRC(3, ("%d: SSL[%d]: read sequence number at limit 0x%0llx",
13292                     SSL_GETPID(), ss->fd, cText->seqNum));
13293         PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
13294         return SECFailure;
13295     }
13296 
13297     recordSizeLimit = spec->recordSizeLimit;
13298     if (cText->buf->len > recordSizeLimit + MAX_EXPANSION) {
13299         ssl_ReleaseSpecReadLock(ss); /*****************************/
13300         SSL3_SendAlert(ss, alert_fatal, record_overflow);
13301         PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13302         return SECFailure;
13303     }
13304 
13305     if (plaintext->space < recordSizeLimit + MAX_EXPANSION) {
13306         rv = sslBuffer_Grow(plaintext, recordSizeLimit + MAX_EXPANSION);
13307         if (rv != SECSuccess) {
13308             ssl_ReleaseSpecReadLock(ss); /*************************/
13309             SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
13310                      SSL_GETPID(), ss->fd, recordSizeLimit + MAX_EXPANSION));
13311             /* sslBuffer_Grow has set a memory error code. */
13312             /* Perhaps we should send an alert. (but we have no memory!) */
13313             return SECFailure;
13314         }
13315     }
13316 
13317     /* Most record types aside from protected TLS 1.3 records carry the content
13318      * type in the first octet. TLS 1.3 will override this value later. */
13319     rType = cText->hdr[0];
13320     /* Encrypted application data records could arrive before the handshake
13321      * completes in DTLS 1.3. These can look like valid TLS 1.2 application_data
13322      * records in epoch 0, which is never valid. Pretend they didn't decrypt. */
13323 
13324     if (spec->epoch == 0 && ((IS_DTLS(ss) &&
13325                               dtls_IsDtls13Ciphertext(0, rType)) ||
13326                              rType == ssl_ct_application_data)) {
13327         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
13328         alert = unexpected_message;
13329         rv = SECFailure;
13330     } else {
13331 #ifdef UNSAFE_FUZZER_MODE
13332         rv = Null_Cipher(NULL, plaintext->buf, &plaintext->len,
13333                          plaintext->space, cText->buf->buf, cText->buf->len);
13334 #else
13335         /* IMPORTANT: Unprotect functions MUST NOT send alerts
13336          * because we still hold the spec read lock. Instead, if they
13337          * return SECFailure, they set *alert to the alert to be sent. */
13338         if (spec->version < SSL_LIBRARY_VERSION_TLS_1_3 ||
13339             spec->epoch == 0) {
13340             rv = ssl3_UnprotectRecord(ss, spec, cText, plaintext, &alert);
13341         } else {
13342             rv = tls13_UnprotectRecord(ss, spec, cText, plaintext, &rType,
13343                                        &alert);
13344         }
13345 #endif
13346     }
13347 
13348     if (rv != SECSuccess) {
13349         ssl_ReleaseSpecReadLock(ss); /***************************/
13350 
13351         SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
13352 
13353         /* Ensure that we don't process this data again. */
13354         plaintext->len = 0;
13355 
13356         /* Ignore a CCS if compatibility mode is negotiated.  Note that this
13357          * will fail if the server fails to negotiate compatibility mode in a
13358          * 0-RTT session that is resumed from a session that did negotiate it.
13359          * We don't care about that corner case right now. */
13360         if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
13361             cText->hdr[0] == ssl_ct_change_cipher_spec &&
13362             ss->ssl3.hs.ws != idle_handshake &&
13363             cText->buf->len == 1 &&
13364             cText->buf->buf[0] == change_cipher_spec_choice) {
13365             if (!ss->ssl3.hs.rejectCcs) {
13366                 /* Allow only the first CCS. */
13367                 ss->ssl3.hs.rejectCcs = PR_TRUE;
13368                 return SECSuccess;
13369             } else {
13370                 alert = unexpected_message;
13371                 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
13372             }
13373         }
13374 
13375         if ((IS_DTLS(ss) && !dtls13_AeadLimitReached(spec)) ||
13376             (!IS_DTLS(ss) && ss->sec.isServer &&
13377              ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_trial)) {
13378             /* Silently drop the packet unless we sent a fatal alert. */
13379             if (ss->ssl3.fatalAlertSent) {
13380                 return SECFailure;
13381             }
13382             return SECSuccess;
13383         }
13384 
13385         int errCode = PORT_GetError();
13386         SSL3_SendAlert(ss, alert_fatal, alert);
13387         /* Reset the error code in case SSL3_SendAlert called
13388          * PORT_SetError(). */
13389         PORT_SetError(errCode);
13390         return SECFailure;
13391     }
13392 
13393     /* SECSuccess */
13394     if (IS_DTLS(ss)) {
13395         dtls_RecordSetRecvd(&spec->recvdRecords, cText->seqNum);
13396         spec->nextSeqNum = PR_MAX(spec->nextSeqNum, cText->seqNum + 1);
13397     } else {
13398         ++spec->nextSeqNum;
13399     }
13400     epoch = spec->epoch;
13401 
13402     ssl_ReleaseSpecReadLock(ss); /*****************************************/
13403 
13404     /*
13405      * The decrypted data is now in plaintext.
13406      */
13407 
13408     /* IMPORTANT: We are in DTLS 1.3 mode and we have processed something
13409      * from the wrong epoch. Divert to a divert processing function to make
13410      * sure we don't accidentally use the data unsafely. */
13411     if (outOfOrderSpec) {
13412         PORT_Assert(IS_DTLS(ss) && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
13413         return dtls13_HandleOutOfEpochRecord(ss, spec, rType, plaintext);
13414     }
13415 
13416     /* Check the length of the plaintext. */
13417     if (isTLS && plaintext->len > recordSizeLimit) {
13418         plaintext->len = 0;
13419         SSL3_SendAlert(ss, alert_fatal, record_overflow);
13420         PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13421         return SECFailure;
13422     }
13423 
13424     /* Application data records are processed by the caller of this
13425     ** function, not by this function.
13426     */
13427     if (rType == ssl_ct_application_data) {
13428         if (ss->firstHsDone)
13429             return SECSuccess;
13430         if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
13431             ss->sec.isServer &&
13432             ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
13433             return tls13_HandleEarlyApplicationData(ss, plaintext);
13434         }
13435         plaintext->len = 0;
13436         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13437         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
13438         return SECFailure;
13439     }
13440 
13441     return ssl3_HandleNonApplicationData(ss, rType, epoch, cText->seqNum,
13442                                          plaintext);
13443 }
13444 
13445 /*
13446  * Initialization functions
13447  */
13448 
13449 void
ssl_InitSecState(sslSecurityInfo * sec)13450 ssl_InitSecState(sslSecurityInfo *sec)
13451 {
13452     sec->authType = ssl_auth_null;
13453     sec->authKeyBits = 0;
13454     sec->signatureScheme = ssl_sig_none;
13455     sec->keaType = ssl_kea_null;
13456     sec->keaKeyBits = 0;
13457     sec->keaGroup = NULL;
13458 }
13459 
13460 SECStatus
ssl3_InitState(sslSocket * ss)13461 ssl3_InitState(sslSocket *ss)
13462 {
13463     SECStatus rv;
13464 
13465     ss->ssl3.policy = SSL_ALLOWED;
13466 
13467     ssl_InitSecState(&ss->sec);
13468 
13469     ssl_GetSpecWriteLock(ss);
13470     PR_INIT_CLIST(&ss->ssl3.hs.cipherSpecs);
13471     rv = ssl_SetupNullCipherSpec(ss, ssl_secret_read);
13472     rv |= ssl_SetupNullCipherSpec(ss, ssl_secret_write);
13473     ss->ssl3.pwSpec = ss->ssl3.prSpec = NULL;
13474     ssl_ReleaseSpecWriteLock(ss);
13475     if (rv != SECSuccess) {
13476         /* Rely on ssl_CreateNullCipherSpec() to set error code. */
13477         return SECFailure;
13478     }
13479 
13480     ss->ssl3.hs.sendingSCSV = PR_FALSE;
13481     ss->ssl3.hs.preliminaryInfo = 0;
13482     ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : idle_handshake;
13483 
13484     ssl3_ResetExtensionData(&ss->xtnData, ss);
13485     PR_INIT_CLIST(&ss->ssl3.hs.remoteExtensions);
13486     PR_INIT_CLIST(&ss->ssl3.hs.echOuterExtensions);
13487     if (IS_DTLS(ss)) {
13488         ss->ssl3.hs.sendMessageSeq = 0;
13489         ss->ssl3.hs.recvMessageSeq = 0;
13490         ss->ssl3.hs.rtTimer->timeout = DTLS_RETRANSMIT_INITIAL_MS;
13491         ss->ssl3.hs.rtRetries = 0;
13492         ss->ssl3.hs.recvdHighWater = -1;
13493         PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
13494         dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
13495     }
13496 
13497     ss->ssl3.hs.currentSecret = NULL;
13498     ss->ssl3.hs.resumptionMasterSecret = NULL;
13499     ss->ssl3.hs.dheSecret = NULL;
13500     ss->ssl3.hs.clientEarlyTrafficSecret = NULL;
13501     ss->ssl3.hs.clientHsTrafficSecret = NULL;
13502     ss->ssl3.hs.serverHsTrafficSecret = NULL;
13503     ss->ssl3.hs.clientTrafficSecret = NULL;
13504     ss->ssl3.hs.serverTrafficSecret = NULL;
13505     ss->ssl3.hs.echHpkeCtx = NULL;
13506     ss->ssl3.hs.echAccepted = PR_FALSE;
13507     ss->ssl3.hs.echDecided = PR_FALSE;
13508 
13509     PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
13510     ss->ssl3.hs.messages.buf = NULL;
13511     ss->ssl3.hs.messages.space = 0;
13512 
13513     ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
13514     PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0,
13515                 sizeof(ss->ssl3.hs.newSessionTicket));
13516 
13517     ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
13518 
13519     return SECSuccess;
13520 }
13521 
13522 /* record the export policy for this cipher suite */
13523 SECStatus
ssl3_SetPolicy(ssl3CipherSuite which,int policy)13524 ssl3_SetPolicy(ssl3CipherSuite which, int policy)
13525 {
13526     ssl3CipherSuiteCfg *suite;
13527 
13528     suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
13529     if (suite == NULL) {
13530         return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13531     }
13532     suite->policy = policy;
13533 
13534     return SECSuccess;
13535 }
13536 
13537 SECStatus
ssl3_GetPolicy(ssl3CipherSuite which,PRInt32 * oPolicy)13538 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
13539 {
13540     const ssl3CipherSuiteCfg *suite;
13541     PRInt32 policy;
13542     SECStatus rv;
13543 
13544     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13545     if (suite) {
13546         policy = suite->policy;
13547         rv = SECSuccess;
13548     } else {
13549         policy = SSL_NOT_ALLOWED;
13550         rv = SECFailure; /* err code was set by Lookup. */
13551     }
13552     *oPolicy = policy;
13553     return rv;
13554 }
13555 
13556 /* record the user preference for this suite */
13557 SECStatus
ssl3_CipherPrefSetDefault(ssl3CipherSuite which,PRBool enabled)13558 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
13559 {
13560     ssl3CipherSuiteCfg *suite;
13561 
13562     suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
13563     if (suite == NULL) {
13564         return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13565     }
13566     suite->enabled = enabled;
13567     return SECSuccess;
13568 }
13569 
13570 /* return the user preference for this suite */
13571 SECStatus
ssl3_CipherPrefGetDefault(ssl3CipherSuite which,PRBool * enabled)13572 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
13573 {
13574     const ssl3CipherSuiteCfg *suite;
13575     PRBool pref;
13576     SECStatus rv;
13577 
13578     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13579     if (suite) {
13580         pref = suite->enabled;
13581         rv = SECSuccess;
13582     } else {
13583         pref = SSL_NOT_ALLOWED;
13584         rv = SECFailure; /* err code was set by Lookup. */
13585     }
13586     *enabled = pref;
13587     return rv;
13588 }
13589 
13590 SECStatus
ssl3_CipherPrefSet(sslSocket * ss,ssl3CipherSuite which,PRBool enabled)13591 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
13592 {
13593     ssl3CipherSuiteCfg *suite;
13594 
13595     suite = ssl_LookupCipherSuiteCfgMutable(which, ss->cipherSuites);
13596     if (suite == NULL) {
13597         return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13598     }
13599     suite->enabled = enabled;
13600     return SECSuccess;
13601 }
13602 
13603 SECStatus
ssl3_CipherPrefGet(const sslSocket * ss,ssl3CipherSuite which,PRBool * enabled)13604 ssl3_CipherPrefGet(const sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
13605 {
13606     const ssl3CipherSuiteCfg *suite;
13607     PRBool pref;
13608     SECStatus rv;
13609 
13610     suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
13611     if (suite) {
13612         pref = suite->enabled;
13613         rv = SECSuccess;
13614     } else {
13615         pref = SSL_NOT_ALLOWED;
13616         rv = SECFailure; /* err code was set by Lookup. */
13617     }
13618     *enabled = pref;
13619     return rv;
13620 }
13621 
13622 SECStatus
SSL_SignatureSchemePrefSet(PRFileDesc * fd,const SSLSignatureScheme * schemes,unsigned int count)13623 SSL_SignatureSchemePrefSet(PRFileDesc *fd, const SSLSignatureScheme *schemes,
13624                            unsigned int count)
13625 {
13626     sslSocket *ss;
13627     unsigned int i;
13628     unsigned int supported = 0;
13629 
13630     ss = ssl_FindSocket(fd);
13631     if (!ss) {
13632         SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefSet",
13633                  SSL_GETPID(), fd));
13634         PORT_SetError(SEC_ERROR_INVALID_ARGS);
13635         return SECFailure;
13636     }
13637 
13638     if (!count) {
13639         PORT_SetError(SEC_ERROR_INVALID_ARGS);
13640         return SECFailure;
13641     }
13642 
13643     for (i = 0; i < count; ++i) {
13644         if (ssl_IsSupportedSignatureScheme(schemes[i])) {
13645             ++supported;
13646         }
13647     }
13648     /* We don't check for duplicates, so it's possible to get too many. */
13649     if (supported > MAX_SIGNATURE_SCHEMES) {
13650         PORT_SetError(SEC_ERROR_INVALID_ARGS);
13651         return SECFailure;
13652     }
13653 
13654     ss->ssl3.signatureSchemeCount = 0;
13655     for (i = 0; i < count; ++i) {
13656         if (!ssl_IsSupportedSignatureScheme(schemes[i])) {
13657             SSL_DBG(("%d: SSL[%d]: invalid signature scheme %d ignored",
13658                      SSL_GETPID(), fd, schemes[i]));
13659             continue;
13660         }
13661 
13662         ss->ssl3.signatureSchemes[ss->ssl3.signatureSchemeCount++] = schemes[i];
13663     }
13664 
13665     if (ss->ssl3.signatureSchemeCount == 0) {
13666         PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
13667         return SECFailure;
13668     }
13669     return SECSuccess;
13670 }
13671 
13672 SECStatus
SSL_SignaturePrefSet(PRFileDesc * fd,const SSLSignatureAndHashAlg * algorithms,unsigned int count)13673 SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms,
13674                      unsigned int count)
13675 {
13676     SSLSignatureScheme schemes[MAX_SIGNATURE_SCHEMES];
13677     unsigned int i;
13678 
13679     count = PR_MIN(PR_ARRAY_SIZE(schemes), count);
13680     for (i = 0; i < count; ++i) {
13681         schemes[i] = (algorithms[i].hashAlg << 8) | algorithms[i].sigAlg;
13682     }
13683     return SSL_SignatureSchemePrefSet(fd, schemes, count);
13684 }
13685 
13686 SECStatus
SSL_SignatureSchemePrefGet(PRFileDesc * fd,SSLSignatureScheme * schemes,unsigned int * count,unsigned int maxCount)13687 SSL_SignatureSchemePrefGet(PRFileDesc *fd, SSLSignatureScheme *schemes,
13688                            unsigned int *count, unsigned int maxCount)
13689 {
13690     sslSocket *ss;
13691 
13692     ss = ssl_FindSocket(fd);
13693     if (!ss) {
13694         SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefGet",
13695                  SSL_GETPID(), fd));
13696         PORT_SetError(SEC_ERROR_INVALID_ARGS);
13697         return SECFailure;
13698     }
13699 
13700     if (!schemes || !count ||
13701         maxCount < ss->ssl3.signatureSchemeCount) {
13702         PORT_SetError(SEC_ERROR_INVALID_ARGS);
13703         return SECFailure;
13704     }
13705 
13706     PORT_Memcpy(schemes, ss->ssl3.signatureSchemes,
13707                 ss->ssl3.signatureSchemeCount * sizeof(SSLSignatureScheme));
13708     *count = ss->ssl3.signatureSchemeCount;
13709     return SECSuccess;
13710 }
13711 
13712 SECStatus
SSL_SignaturePrefGet(PRFileDesc * fd,SSLSignatureAndHashAlg * algorithms,unsigned int * count,unsigned int maxCount)13713 SSL_SignaturePrefGet(PRFileDesc *fd, SSLSignatureAndHashAlg *algorithms,
13714                      unsigned int *count, unsigned int maxCount)
13715 {
13716     sslSocket *ss;
13717     unsigned int i;
13718 
13719     ss = ssl_FindSocket(fd);
13720     if (!ss) {
13721         SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignaturePrefGet",
13722                  SSL_GETPID(), fd));
13723         PORT_SetError(SEC_ERROR_INVALID_ARGS);
13724         return SECFailure;
13725     }
13726 
13727     if (!algorithms || !count ||
13728         maxCount < ss->ssl3.signatureSchemeCount) {
13729         PORT_SetError(SEC_ERROR_INVALID_ARGS);
13730         return SECFailure;
13731     }
13732 
13733     for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
13734         algorithms[i].hashAlg = (ss->ssl3.signatureSchemes[i] >> 8) & 0xff;
13735         algorithms[i].sigAlg = ss->ssl3.signatureSchemes[i] & 0xff;
13736     }
13737     *count = ss->ssl3.signatureSchemeCount;
13738     return SECSuccess;
13739 }
13740 
13741 unsigned int
SSL_SignatureMaxCount(void)13742 SSL_SignatureMaxCount(void)
13743 {
13744     return MAX_SIGNATURE_SCHEMES;
13745 }
13746 
13747 /* copy global default policy into socket. */
13748 void
ssl3_InitSocketPolicy(sslSocket * ss)13749 ssl3_InitSocketPolicy(sslSocket *ss)
13750 {
13751     PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof(cipherSuites));
13752     PORT_Memcpy(ss->ssl3.signatureSchemes, defaultSignatureSchemes,
13753                 sizeof(defaultSignatureSchemes));
13754     ss->ssl3.signatureSchemeCount = PR_ARRAY_SIZE(defaultSignatureSchemes);
13755 }
13756 
13757 /*
13758 ** If ssl3 socket has completed the first handshake, and is in idle state,
13759 ** then start a new handshake.
13760 ** If flushCache is true, the SID cache will be flushed first, forcing a
13761 ** "Full" handshake (not a session restart handshake), to be done.
13762 **
13763 ** called from SSL_RedoHandshake(), which already holds the handshake locks.
13764 */
13765 SECStatus
ssl3_RedoHandshake(sslSocket * ss,PRBool flushCache)13766 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
13767 {
13768     sslSessionID *sid = ss->sec.ci.sid;
13769     SECStatus rv;
13770 
13771     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
13772 
13773     if (!ss->firstHsDone || (ss->ssl3.hs.ws != idle_handshake)) {
13774         PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
13775         return SECFailure;
13776     }
13777 
13778     if (IS_DTLS(ss)) {
13779         dtls_RehandshakeCleanup(ss);
13780     }
13781 
13782     if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER ||
13783         ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
13784         PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
13785         return SECFailure;
13786     }
13787     if (ss->version > ss->vrange.max || ss->version < ss->vrange.min) {
13788         PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
13789         return SECFailure;
13790     }
13791 
13792     if (sid && flushCache) {
13793         ssl_UncacheSessionID(ss); /* remove it from whichever cache it's in. */
13794         ssl_FreeSID(sid);         /* dec ref count and free if zero. */
13795         ss->sec.ci.sid = NULL;
13796     }
13797 
13798     ssl_GetXmitBufLock(ss); /**************************************/
13799 
13800     /* start off a new handshake. */
13801     if (ss->sec.isServer) {
13802         rv = ssl3_SendHelloRequest(ss);
13803     } else {
13804         rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
13805     }
13806 
13807     ssl_ReleaseXmitBufLock(ss); /**************************************/
13808     return rv;
13809 }
13810 
13811 /* Called from ssl_DestroySocketContents() in sslsock.c */
13812 void
ssl3_DestroySSL3Info(sslSocket * ss)13813 ssl3_DestroySSL3Info(sslSocket *ss)
13814 {
13815 
13816     if (ss->ssl3.clientCertificate != NULL)
13817         CERT_DestroyCertificate(ss->ssl3.clientCertificate);
13818 
13819     if (ss->ssl3.clientPrivateKey != NULL)
13820         SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
13821 
13822     if (ss->ssl3.peerCertArena != NULL)
13823         ssl3_CleanupPeerCerts(ss);
13824 
13825     if (ss->ssl3.clientCertChain != NULL) {
13826         CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
13827         ss->ssl3.clientCertChain = NULL;
13828     }
13829     if (ss->ssl3.ca_list) {
13830         CERT_FreeDistNames(ss->ssl3.ca_list);
13831     }
13832 
13833     /* clean up handshake */
13834     if (ss->ssl3.hs.md5) {
13835         PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
13836     }
13837     if (ss->ssl3.hs.sha) {
13838         PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
13839     }
13840     if (ss->ssl3.hs.shaEchInner) {
13841         PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
13842     }
13843     if (ss->ssl3.hs.shaPostHandshake) {
13844         PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
13845     }
13846     if (ss->ssl3.hs.messages.buf) {
13847         sslBuffer_Clear(&ss->ssl3.hs.messages);
13848     }
13849     if (ss->ssl3.hs.echInnerMessages.buf) {
13850         sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
13851     }
13852 
13853     /* free the SSL3Buffer (msg_body) */
13854     PORT_Free(ss->ssl3.hs.msg_body.buf);
13855 
13856     SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
13857     SECITEM_FreeItem(&ss->ssl3.hs.srvVirtName, PR_FALSE);
13858     SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
13859 
13860     /* Destroy the DTLS data */
13861     if (IS_DTLS(ss)) {
13862         dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
13863         if (ss->ssl3.hs.recvdFragments.buf) {
13864             PORT_Free(ss->ssl3.hs.recvdFragments.buf);
13865         }
13866     }
13867 
13868     /* Destroy remote extensions */
13869     ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
13870     ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.echOuterExtensions);
13871     ssl3_DestroyExtensionData(&ss->xtnData);
13872 
13873     /* Destroy cipher specs */
13874     ssl_DestroyCipherSpecs(&ss->ssl3.hs.cipherSpecs);
13875 
13876     /* Destroy TLS 1.3 keys */
13877     if (ss->ssl3.hs.currentSecret)
13878         PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
13879     if (ss->ssl3.hs.resumptionMasterSecret)
13880         PK11_FreeSymKey(ss->ssl3.hs.resumptionMasterSecret);
13881     if (ss->ssl3.hs.dheSecret)
13882         PK11_FreeSymKey(ss->ssl3.hs.dheSecret);
13883     if (ss->ssl3.hs.clientEarlyTrafficSecret)
13884         PK11_FreeSymKey(ss->ssl3.hs.clientEarlyTrafficSecret);
13885     if (ss->ssl3.hs.clientHsTrafficSecret)
13886         PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
13887     if (ss->ssl3.hs.serverHsTrafficSecret)
13888         PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
13889     if (ss->ssl3.hs.clientTrafficSecret)
13890         PK11_FreeSymKey(ss->ssl3.hs.clientTrafficSecret);
13891     if (ss->ssl3.hs.serverTrafficSecret)
13892         PK11_FreeSymKey(ss->ssl3.hs.serverTrafficSecret);
13893     if (ss->ssl3.hs.earlyExporterSecret)
13894         PK11_FreeSymKey(ss->ssl3.hs.earlyExporterSecret);
13895     if (ss->ssl3.hs.exporterSecret)
13896         PK11_FreeSymKey(ss->ssl3.hs.exporterSecret);
13897 
13898     ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
13899     /* Destroy TLS 1.3 buffered early data. */
13900     tls13_DestroyEarlyData(&ss->ssl3.hs.bufferedEarlyData);
13901 
13902     /* Destroy TLS 1.3 PSKs. */
13903     tls13_DestroyPskList(&ss->ssl3.hs.psks);
13904 
13905     /* TLS 1.3 ECH state. */
13906     PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE);
13907     PORT_Free((void *)ss->ssl3.hs.echPublicName); /* CONST */
13908     sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
13909 }
13910 
13911 /* check if the current cipher spec is FIPS. We only need to
13912  * check the contexts here, if the kea, prf or keys were not FIPS,
13913  * that status would have been rolled up in the create context
13914  * call */
13915 static PRBool
ssl_cipherSpecIsFips(ssl3CipherSpec * spec)13916 ssl_cipherSpecIsFips(ssl3CipherSpec *spec)
13917 {
13918     if (!spec || !spec->cipherDef) {
13919         return PR_FALSE;
13920     }
13921 
13922     if (spec->cipherDef->type != type_aead) {
13923         if (spec->keyMaterial.macContext == NULL) {
13924             return PR_FALSE;
13925         }
13926         if (!PK11_ContextGetFIPSStatus(spec->keyMaterial.macContext)) {
13927             return PR_FALSE;
13928         }
13929     }
13930     if (!spec->cipherContext) {
13931         return PR_FALSE;
13932     }
13933     return PK11_ContextGetFIPSStatus(spec->cipherContext);
13934 }
13935 
13936 /* return true if the current operation is running in FIPS mode */
13937 PRBool
ssl_isFIPS(sslSocket * ss)13938 ssl_isFIPS(sslSocket *ss)
13939 {
13940     if (!ssl_cipherSpecIsFips(ss->ssl3.crSpec)) {
13941         return PR_FALSE;
13942     }
13943     return ssl_cipherSpecIsFips(ss->ssl3.cwSpec);
13944 }
13945 
13946 /*
13947  * parse the policy value for a single algorithm in a cipher_suite,
13948  *   return TRUE if we disallow by the cipher suite by policy
13949  *   (we don't have to parse any more algorithm policies on this cipher suite),
13950  *  otherwise return FALSE.
13951  *   1. If we don't have the required policy, disable by default, disallow by
13952  *      policy and return TRUE (no more processing needed).
13953  *   2. If we have the required policy, and we are disabled, return FALSE,
13954  *      (if we are disabled, we only need to parse policy, not default).
13955  *   3. If we have the required policy, and we aren't adjusting the defaults
13956  *      return FALSE. (only parsing the policy, not default).
13957  *   4. We have the required policy and we are adjusting the defaults.
13958  *      If we are setting default = FALSE, set isDisabled to true so that
13959  *      we don't try to re-enable the cipher suite based on a different
13960  *      algorithm.
13961  */
13962 PRBool
ssl_HandlePolicy(int cipher_suite,SECOidTag policyOid,PRUint32 requiredPolicy,PRBool * isDisabled)13963 ssl_HandlePolicy(int cipher_suite, SECOidTag policyOid,
13964                  PRUint32 requiredPolicy, PRBool *isDisabled)
13965 {
13966     PRUint32 policy;
13967     SECStatus rv;
13968 
13969     /* first fetch the policy for this algorithm */
13970     rv = NSS_GetAlgorithmPolicy(policyOid, &policy);
13971     if (rv != SECSuccess) {
13972         return PR_FALSE; /* no policy value, continue to the next algorithm */
13973     }
13974     /* first, are we allowed by policy, if not turn off allow and disable */
13975     if (!(policy & requiredPolicy)) {
13976         ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE);
13977         ssl_CipherPolicySet(cipher_suite, SSL_NOT_ALLOWED);
13978         return PR_TRUE;
13979     }
13980     /* If we are already disabled, or the policy isn't setting a default
13981      * we are done processing this algorithm */
13982     if (*isDisabled || (policy & NSS_USE_DEFAULT_NOT_VALID)) {
13983         return PR_FALSE;
13984     }
13985     /* set the default value for the cipher suite. If we disable the cipher
13986      * suite, remember that so we don't process the next default. This has
13987      * the effect of disabling the whole cipher suite if any of the
13988      * algorithms it uses are disabled by default. We still have to
13989      * process the upper level because the cipher suite is still allowed
13990      * by policy, and we may still have to disallow it based on other
13991      * algorithms in the cipher suite. */
13992     if (policy & NSS_USE_DEFAULT_SSL_ENABLE) {
13993         ssl_CipherPrefSetDefault(cipher_suite, PR_TRUE);
13994     } else {
13995         *isDisabled = PR_TRUE;
13996         ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE);
13997     }
13998     return PR_FALSE;
13999 }
14000 
14001 #define MAP_NULL(x) (((x) != 0) ? (x) : SEC_OID_NULL_CIPHER)
14002 
14003 SECStatus
ssl3_ApplyNSSPolicy(void)14004 ssl3_ApplyNSSPolicy(void)
14005 {
14006     unsigned i;
14007     SECStatus rv;
14008     PRUint32 policy = 0;
14009 
14010     rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy);
14011     if (rv != SECSuccess || !(policy & NSS_USE_POLICY_IN_SSL)) {
14012         return SECSuccess; /* do nothing */
14013     }
14014 
14015     /* disable every ciphersuite */
14016     for (i = 1; i < PR_ARRAY_SIZE(cipher_suite_defs); ++i) {
14017         const ssl3CipherSuiteDef *suite = &cipher_suite_defs[i];
14018         SECOidTag policyOid;
14019         PRBool isDisabled = PR_FALSE;
14020 
14021         /* if we haven't explicitly disabled it below enable by policy */
14022         ssl_CipherPolicySet(suite->cipher_suite, SSL_ALLOWED);
14023 
14024         /* now check the various key exchange, ciphers and macs and
14025          * if we ever disallow by policy, we are done, go to the next cipher
14026          */
14027         policyOid = MAP_NULL(kea_defs[suite->key_exchange_alg].oid);
14028         if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14029                              NSS_USE_ALG_IN_SSL_KX, &isDisabled)) {
14030             continue;
14031         }
14032 
14033         policyOid = MAP_NULL(ssl_GetBulkCipherDef(suite)->oid);
14034         if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14035                              NSS_USE_ALG_IN_SSL, &isDisabled)) {
14036             continue;
14037         }
14038 
14039         if (ssl_GetBulkCipherDef(suite)->type != type_aead) {
14040             policyOid = MAP_NULL(ssl_GetMacDefByAlg(suite->mac_alg)->oid);
14041             if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14042                                  NSS_USE_ALG_IN_SSL, &isDisabled)) {
14043                 continue;
14044             }
14045         }
14046     }
14047 
14048     rv = ssl3_ConstrainRangeByPolicy();
14049 
14050     return rv;
14051 }
14052 
14053 /* End of ssl3con.c */
14054