Coverage Report

Created: 2024-05-20 06:23

/src/nss/lib/ssl/ssl3con.c
Line
Count
Source (jump to first uncovered line)
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
216
ssl3_CheckCipherSuiteOrderConsistency()
217
1
{
218
1
    unsigned int i;
219
220
1
    PORT_Assert(SSL_NumImplementedCiphers == PR_ARRAY_SIZE(cipherSuites));
221
222
72
    for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) {
223
71
        PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite);
224
71
    }
225
1
}
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
    /* indexed by SSL3KeyExchangeAlgorithm */
238
    /* kea            exchKeyType signKeyType authKeyType ephemeral  oid */
239
    { kea_null, ssl_kea_null, nullKey, ssl_auth_null, PR_FALSE, 0 },
240
    { kea_rsa, ssl_kea_rsa, nullKey, ssl_auth_rsa_decrypt, PR_FALSE, SEC_OID_TLS_RSA },
241
    { kea_dh_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_FALSE, SEC_OID_TLS_DH_DSS },
242
    { kea_dh_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_FALSE, SEC_OID_TLS_DH_RSA },
243
    { kea_dhe_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_TRUE, SEC_OID_TLS_DHE_DSS },
244
    { kea_dhe_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_DHE_RSA },
245
    { kea_dh_anon, ssl_kea_dh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_DH_ANON },
246
    { kea_ecdh_ecdsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_ecdsa, PR_FALSE, SEC_OID_TLS_ECDH_ECDSA },
247
    { kea_ecdhe_ecdsa, ssl_kea_ecdh, ecKey, ssl_auth_ecdsa, PR_TRUE, SEC_OID_TLS_ECDHE_ECDSA },
248
    { kea_ecdh_rsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_rsa, PR_FALSE, SEC_OID_TLS_ECDH_RSA },
249
    { kea_ecdhe_rsa, ssl_kea_ecdh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_ECDHE_RSA },
250
    { kea_ecdh_anon, ssl_kea_ecdh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_ECDH_ANON },
251
    { kea_ecdhe_psk, ssl_kea_ecdh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_ECDHE_PSK },
252
    { kea_dhe_psk, ssl_kea_dh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_DHE_PSK },
253
    { kea_tls13_any, ssl_kea_tls13_any, nullKey, ssl_auth_tls13_any, PR_TRUE, SEC_OID_TLS13_KEA_ANY },
254
};
255
256
/* must use ssl_LookupCipherSuiteDef to access */
257
static const ssl3CipherSuiteDef cipher_suite_defs[] = {
258
    /*  cipher_suite                    bulk_cipher_alg mac_alg key_exchange_alg prf_hash */
259
    /*  Note that the prf_hash_alg is the hash function used by the PRF, see sslimpl.h.  */
260
261
    { TLS_NULL_WITH_NULL_NULL, cipher_null, ssl_mac_null, kea_null, ssl_hash_none },
262
    { TLS_RSA_WITH_NULL_MD5, cipher_null, ssl_mac_md5, kea_rsa, ssl_hash_none },
263
    { TLS_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_rsa, ssl_hash_none },
264
    { TLS_RSA_WITH_NULL_SHA256, cipher_null, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
265
    { TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, ssl_mac_md5, kea_rsa, ssl_hash_none },
266
    { TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_rsa, ssl_hash_none },
267
    { TLS_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_rsa, ssl_hash_none },
268
    { TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_rsa, ssl_hash_none },
269
    { TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
270
    { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
271
      cipher_3des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
272
    { TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
273
    { TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
274
    { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
275
      cipher_3des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
276
277
    /* New TLS cipher suites */
278
    { TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
279
    { TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
280
    { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
281
    { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
282
    { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
283
    { TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
284
    { TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
285
    { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
286
    { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
287
    { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
288
    { TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha384 },
289
290
    { TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, ssl_mac_sha, kea_rsa, ssl_hash_none },
291
292
    { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
293
    { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
294
      cipher_camellia_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
295
    { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
296
      cipher_camellia_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
297
    { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
298
    { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
299
      cipher_camellia_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
300
    { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
301
      cipher_camellia_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
302
303
    { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
304
    { TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha256 },
305
306
    { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
307
    { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
308
    { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha384 },
309
    { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha384 },
310
    { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_ecdsa, ssl_hash_sha384 },
311
    { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_rsa, ssl_hash_sha384 },
312
    { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha256 },
313
    { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
314
    { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
315
    { TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha384 },
316
    { TLS_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha384 },
317
318
    { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
319
320
    { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
321
    { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
322
323
    { TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
324
    { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
325
    { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
326
    { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
327
    { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
328
329
    { TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
330
    { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
331
    { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
332
    { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
333
    { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_ecdsa, ssl_hash_sha256 },
334
    { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
335
336
    { TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
337
    { TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
338
    { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
339
    { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
340
    { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
341
342
    { TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
343
    { TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
344
    { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
345
    { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
346
    { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_rsa, ssl_hash_sha256 },
347
    { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
348
349
    { TLS_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
350
    { TLS_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
351
    { TLS_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha384 },
352
};
353
354
static const CK_MECHANISM_TYPE auth_alg_defs[] = {
355
    CKM_INVALID_MECHANISM, /* ssl_auth_null */
356
    CKM_RSA_PKCS,          /* ssl_auth_rsa_decrypt */
357
    CKM_DSA, /* ? _SHA1 */ /* ssl_auth_dsa */
358
    CKM_INVALID_MECHANISM, /* ssl_auth_kea (unused) */
359
    CKM_ECDSA,             /* ssl_auth_ecdsa */
360
    CKM_ECDH1_DERIVE,      /* ssl_auth_ecdh_rsa */
361
    CKM_ECDH1_DERIVE,      /* ssl_auth_ecdh_ecdsa */
362
    CKM_RSA_PKCS,          /* ssl_auth_rsa_sign */
363
    CKM_RSA_PKCS_PSS,      /* ssl_auth_rsa_pss */
364
    CKM_NSS_HKDF_SHA256,   /* ssl_auth_psk (just check for HKDF) */
365
    CKM_INVALID_MECHANISM  /* ssl_auth_tls13_any */
366
};
367
PR_STATIC_ASSERT(PR_ARRAY_SIZE(auth_alg_defs) == ssl_auth_size);
368
369
static const CK_MECHANISM_TYPE kea_alg_defs[] = {
370
    CKM_INVALID_MECHANISM, /* ssl_kea_null */
371
    CKM_RSA_PKCS,          /* ssl_kea_rsa */
372
    CKM_DH_PKCS_DERIVE,    /* ssl_kea_dh */
373
    CKM_INVALID_MECHANISM, /* ssl_kea_fortezza (unused) */
374
    CKM_ECDH1_DERIVE,      /* ssl_kea_ecdh */
375
    CKM_ECDH1_DERIVE,      /* ssl_kea_ecdh_psk */
376
    CKM_DH_PKCS_DERIVE,    /* ssl_kea_dh_psk */
377
    CKM_INVALID_MECHANISM, /* ssl_kea_tls13_any */
378
    CKM_INVALID_MECHANISM, /* ssl_kea_ecdh_hybrid */
379
    CKM_INVALID_MECHANISM, /* ssl_kea_ecdh_hybrid_psk */
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
0
#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
435
ssl3_Alg2Mech(SSLCipherAlgorithm calg)
436
1.88M
{
437
1.88M
    PORT_Assert(alg2Mech[calg].calg == calg);
438
1.88M
    return alg2Mech[calg].cmech;
439
1.88M
}
440
441
#if defined(TRACE)
442
443
static char *
444
ssl3_DecodeHandshakeType(int msgType)
445
0
{
446
0
    char *rv;
447
0
    static char line[40];
448
449
0
    switch (msgType) {
450
0
        case ssl_hs_hello_request:
451
0
            rv = "hello_request (0)";
452
0
            break;
453
0
        case ssl_hs_client_hello:
454
0
            rv = "client_hello  (1)";
455
0
            break;
456
0
        case ssl_hs_server_hello:
457
0
            rv = "server_hello  (2)";
458
0
            break;
459
0
        case ssl_hs_hello_verify_request:
460
0
            rv = "hello_verify_request (3)";
461
0
            break;
462
0
        case ssl_hs_new_session_ticket:
463
0
            rv = "new_session_ticket (4)";
464
0
            break;
465
0
        case ssl_hs_end_of_early_data:
466
0
            rv = "end_of_early_data (5)";
467
0
            break;
468
0
        case ssl_hs_hello_retry_request:
469
0
            rv = "hello_retry_request (6)";
470
0
            break;
471
0
        case ssl_hs_encrypted_extensions:
472
0
            rv = "encrypted_extensions (8)";
473
0
            break;
474
0
        case ssl_hs_certificate:
475
0
            rv = "certificate  (11)";
476
0
            break;
477
0
        case ssl_hs_server_key_exchange:
478
0
            rv = "server_key_exchange (12)";
479
0
            break;
480
0
        case ssl_hs_certificate_request:
481
0
            rv = "certificate_request (13)";
482
0
            break;
483
0
        case ssl_hs_server_hello_done:
484
0
            rv = "server_hello_done   (14)";
485
0
            break;
486
0
        case ssl_hs_certificate_verify:
487
0
            rv = "certificate_verify  (15)";
488
0
            break;
489
0
        case ssl_hs_client_key_exchange:
490
0
            rv = "client_key_exchange (16)";
491
0
            break;
492
0
        case ssl_hs_finished:
493
0
            rv = "finished     (20)";
494
0
            break;
495
0
        case ssl_hs_certificate_status:
496
0
            rv = "certificate_status  (22)";
497
0
            break;
498
0
        case ssl_hs_key_update:
499
0
            rv = "key_update   (24)";
500
0
            break;
501
0
        case ssl_hs_compressed_certificate:
502
0
            rv = "compressed certificate (25)";
503
0
            break;
504
0
        default:
505
0
            snprintf(line, sizeof(line), "*UNKNOWN* handshake type! (%d)", msgType);
506
0
            rv = line;
507
0
    }
508
0
    return rv;
509
0
}
510
511
static char *
512
ssl3_DecodeContentType(int msgType)
513
0
{
514
0
    char *rv;
515
0
    static char line[40];
516
517
0
    switch (msgType) {
518
0
        case ssl_ct_change_cipher_spec:
519
0
            rv = "change_cipher_spec (20)";
520
0
            break;
521
0
        case ssl_ct_alert:
522
0
            rv = "alert      (21)";
523
0
            break;
524
0
        case ssl_ct_handshake:
525
0
            rv = "handshake  (22)";
526
0
            break;
527
0
        case ssl_ct_application_data:
528
0
            rv = "application_data (23)";
529
0
            break;
530
0
        case ssl_ct_ack:
531
0
            rv = "ack (26)";
532
0
            break;
533
0
        default:
534
0
            snprintf(line, sizeof(line), "*UNKNOWN* record type! (%d)", msgType);
535
0
            rv = line;
536
0
    }
537
0
    return rv;
538
0
}
539
540
#endif
541
542
SSL3Statistics *
543
SSL_GetStatistics(void)
544
13.7k
{
545
13.7k
    return &ssl3stats;
546
13.7k
}
547
548
typedef struct tooLongStr {
549
#if defined(IS_LITTLE_ENDIAN)
550
    PRInt32 low;
551
    PRInt32 high;
552
#else
553
    PRInt32 high;
554
    PRInt32 low;
555
#endif
556
} tooLong;
557
558
void
559
SSL_AtomicIncrementLong(long *x)
560
22.8k
{
561
22.8k
    if ((sizeof *x) == sizeof(PRInt32)) {
562
0
        PR_ATOMIC_INCREMENT((PRInt32 *)x);
563
22.8k
    } else {
564
22.8k
        tooLong *tl = (tooLong *)x;
565
22.8k
        if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
566
0
            PR_ATOMIC_INCREMENT(&tl->high);
567
22.8k
    }
568
22.8k
}
569
570
PRBool
571
ssl3_CipherSuiteAllowedForVersionRange(ssl3CipherSuite cipherSuite,
572
                                       const SSLVersionRange *vrange)
573
986k
{
574
986k
    switch (cipherSuite) {
575
13.7k
        case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
576
27.4k
        case TLS_RSA_WITH_AES_256_CBC_SHA256:
577
41.1k
        case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
578
54.8k
        case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
579
68.6k
        case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
580
82.5k
        case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
581
96.2k
        case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
582
109k
        case TLS_RSA_WITH_AES_128_CBC_SHA256:
583
123k
        case TLS_RSA_WITH_AES_128_GCM_SHA256:
584
138k
        case TLS_RSA_WITH_AES_256_GCM_SHA384:
585
151k
        case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
586
166k
        case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
587
180k
        case TLS_RSA_WITH_NULL_SHA256:
588
193k
        case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
589
207k
        case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
590
221k
        case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
591
235k
        case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
592
250k
        case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
593
263k
        case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
594
277k
        case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
595
291k
        case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
596
304k
        case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
597
318k
        case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
598
332k
        case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
599
332k
            return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2 &&
600
332k
                   vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
601
602
        /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and
603
         * point formats.*/
604
13.8k
        case TLS_ECDH_ECDSA_WITH_NULL_SHA:
605
27.5k
        case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
606
41.7k
        case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
607
55.5k
        case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
608
69.2k
        case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
609
83.0k
        case TLS_ECDHE_ECDSA_WITH_NULL_SHA:
610
96.7k
        case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
611
110k
        case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
612
124k
        case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
613
138k
        case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
614
152k
        case TLS_ECDH_RSA_WITH_NULL_SHA:
615
166k
        case TLS_ECDH_RSA_WITH_RC4_128_SHA:
616
180k
        case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
617
193k
        case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
618
210k
        case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
619
224k
        case TLS_ECDHE_RSA_WITH_NULL_SHA:
620
238k
        case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
621
252k
        case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
622
266k
        case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
623
280k
        case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
624
280k
            return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0 &&
625
280k
                   vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
626
627
13.7k
        case TLS_AES_128_GCM_SHA256:
628
27.5k
        case TLS_AES_256_GCM_SHA384:
629
41.3k
        case TLS_CHACHA20_POLY1305_SHA256:
630
41.3k
            return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_3;
631
632
331k
        default:
633
331k
            return vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
634
986k
    }
635
986k
}
636
637
/* return pointer to ssl3CipherSuiteDef for suite, or NULL */
638
/* XXX This does a linear search.  A binary search would be better. */
639
const ssl3CipherSuiteDef *
640
ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
641
2.88M
{
642
2.88M
    int cipher_suite_def_len =
643
2.88M
        sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
644
2.88M
    int i;
645
646
106M
    for (i = 0; i < cipher_suite_def_len; i++) {
647
106M
        if (cipher_suite_defs[i].cipher_suite == suite)
648
2.88M
            return &cipher_suite_defs[i];
649
106M
    }
650
0
    PORT_Assert(PR_FALSE); /* We should never get here. */
651
0
    PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
652
0
    return NULL;
653
2.88M
}
654
655
/* Find the cipher configuration struct associate with suite */
656
/* XXX This does a linear search.  A binary search would be better. */
657
static ssl3CipherSuiteCfg *
658
ssl_LookupCipherSuiteCfgMutable(ssl3CipherSuite suite,
659
                                ssl3CipherSuiteCfg *suites)
660
689k
{
661
689k
    int i;
662
663
24.5M
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
664
24.5M
        if (suites[i].cipher_suite == suite)
665
689k
            return &suites[i];
666
24.5M
    }
667
    /* return NULL and let the caller handle it.  */
668
0
    PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
669
0
    return NULL;
670
689k
}
671
672
const ssl3CipherSuiteCfg *
673
ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, const ssl3CipherSuiteCfg *suites)
674
13.7k
{
675
13.7k
    return ssl_LookupCipherSuiteCfgMutable(suite,
676
13.7k
                                           CONST_CAST(ssl3CipherSuiteCfg, suites));
677
13.7k
}
678
679
static PRBool
680
ssl_NamedGroupTypeEnabled(const sslSocket *ss, SSLKEAType keaType)
681
585k
{
682
585k
    unsigned int i;
683
1.41M
    for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
684
1.41M
        if (ss->namedGroupPreferences[i] &&
685
1.41M
            ss->namedGroupPreferences[i]->keaType == keaType) {
686
585k
            return PR_TRUE;
687
585k
        }
688
1.41M
    }
689
0
    return PR_FALSE;
690
585k
}
691
692
static PRBool
693
ssl_KEAEnabled(const sslSocket *ss, SSLKEAType keaType)
694
986k
{
695
986k
    switch (keaType) {
696
222k
        case ssl_kea_rsa:
697
222k
            return PR_TRUE;
698
699
303k
        case ssl_kea_dh:
700
303k
        case ssl_kea_dh_psk: {
701
303k
            if (ss->sec.isServer && !ss->opt.enableServerDhe) {
702
0
                return PR_FALSE;
703
0
            }
704
705
303k
            if (ss->sec.isServer) {
706
                /* If the server requires named FFDHE groups, then the client
707
                 * must have included an FFDHE group. peerSupportsFfdheGroups
708
                 * is set to true in ssl_HandleSupportedGroupsXtn(). */
709
0
                if (ss->opt.requireDHENamedGroups &&
710
0
                    !ss->xtnData.peerSupportsFfdheGroups) {
711
0
                    return PR_FALSE;
712
0
                }
713
714
                /* We can use the weak DH group if all of these are true:
715
                 * 1. We don't require named groups.
716
                 * 2. The peer doesn't support named groups.
717
                 * 3. This isn't TLS 1.3.
718
                 * 4. The weak group is enabled. */
719
0
                if (!ss->opt.requireDHENamedGroups &&
720
0
                    !ss->xtnData.peerSupportsFfdheGroups &&
721
0
                    ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
722
0
                    ss->ssl3.dheWeakGroupEnabled) {
723
0
                    return PR_TRUE;
724
0
                }
725
303k
            } else {
726
303k
                if (ss->vrange.min < SSL_LIBRARY_VERSION_TLS_1_3 &&
727
303k
                    !ss->opt.requireDHENamedGroups) {
728
                    /* The client enables DHE cipher suites even if no DHE groups
729
                     * are enabled. Only if this isn't TLS 1.3 and named groups
730
                     * are not required. */
731
137k
                    return PR_TRUE;
732
137k
                }
733
303k
            }
734
165k
            return ssl_NamedGroupTypeEnabled(ss, ssl_kea_dh);
735
303k
        }
736
737
419k
        case ssl_kea_ecdh:
738
419k
        case ssl_kea_ecdh_psk:
739
419k
            return ssl_NamedGroupTypeEnabled(ss, ssl_kea_ecdh);
740
741
0
        case ssl_kea_ecdh_hybrid:
742
0
        case ssl_kea_ecdh_hybrid_psk:
743
0
            if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
744
0
                return PR_FALSE;
745
0
            }
746
0
            return ssl_NamedGroupTypeEnabled(ss, ssl_kea_ecdh_hybrid);
747
748
41.3k
        case ssl_kea_tls13_any:
749
41.3k
            return PR_TRUE;
750
751
0
        case ssl_kea_fortezza:
752
0
        default:
753
0
            PORT_Assert(0);
754
986k
    }
755
0
    return PR_FALSE;
756
986k
}
757
758
static PRBool
759
ssl_HasCert(const sslSocket *ss, PRUint16 maxVersion, SSLAuthType authType)
760
0
{
761
0
    PRCList *cursor;
762
0
    if (authType == ssl_auth_null || authType == ssl_auth_psk || authType == ssl_auth_tls13_any) {
763
0
        return PR_TRUE;
764
0
    }
765
0
    for (cursor = PR_NEXT_LINK(&ss->serverCerts);
766
0
         cursor != &ss->serverCerts;
767
0
         cursor = PR_NEXT_LINK(cursor)) {
768
0
        sslServerCert *cert = (sslServerCert *)cursor;
769
0
        if (!cert->serverKeyPair ||
770
0
            !cert->serverKeyPair->privKey ||
771
0
            !cert->serverCertChain ||
772
0
            !SSL_CERT_IS(cert, authType)) {
773
0
            continue;
774
0
        }
775
        /* When called from ssl3_config_match_init(), all the EC curves will be
776
         * enabled, so this will essentially do nothing (unless we implement
777
         * curve configuration).  However, once we have seen the
778
         * supported_groups extension and this is called from config_match(),
779
         * this will filter out certificates with an unsupported curve.
780
         *
781
         * If we might negotiate TLS 1.3, skip this test as group configuration
782
         * doesn't affect choices in TLS 1.3.
783
         */
784
0
        if (maxVersion < SSL_LIBRARY_VERSION_TLS_1_3 &&
785
0
            (authType == ssl_auth_ecdsa ||
786
0
             authType == ssl_auth_ecdh_ecdsa ||
787
0
             authType == ssl_auth_ecdh_rsa) &&
788
0
            !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
789
0
            continue;
790
0
        }
791
0
        return PR_TRUE;
792
0
    }
793
0
    if (authType == ssl_auth_rsa_sign) {
794
0
        return ssl_HasCert(ss, maxVersion, ssl_auth_rsa_pss);
795
0
    }
796
0
    return PR_FALSE;
797
0
}
798
799
/* return true if the scheme is allowed by policy, This prevents
800
 * failures later when our actual signatures are rejected by
801
 * policy by either ssl code, or lower level NSS code */
802
static PRBool
803
ssl_SchemePolicyOK(SSLSignatureScheme scheme, PRUint32 require)
804
235k
{
805
    /* Hash policy. */
806
235k
    PRUint32 policy;
807
235k
    SECOidTag hashOID = ssl3_HashTypeToOID(ssl_SignatureSchemeToHashType(scheme));
808
235k
    SECOidTag sigOID;
809
810
    /* policy bits needed to enable a SignatureScheme */
811
235k
    SECStatus rv = NSS_GetAlgorithmPolicy(hashOID, &policy);
812
235k
    if (rv == SECSuccess &&
813
235k
        (policy & require) != require) {
814
0
        return PR_FALSE;
815
0
    }
816
817
    /* ssl_SignatureSchemeToAuthType reports rsa for rsa_pss_rsae, but we
818
     * actually implement pss signatures when we sign, so just use RSA_PSS
819
     * for all RSA PSS Siganture schemes */
820
235k
    if (ssl_IsRsaPssSignatureScheme(scheme)) {
821
42.3k
        sigOID = SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
822
193k
    } else {
823
193k
        sigOID = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme));
824
193k
    }
825
    /* Signature Policy. */
826
235k
    rv = NSS_GetAlgorithmPolicy(sigOID, &policy);
827
235k
    if (rv == SECSuccess &&
828
235k
        (policy & require) != require) {
829
0
        return PR_FALSE;
830
0
    }
831
235k
    return PR_TRUE;
832
235k
}
833
834
/* Check that a signature scheme is accepted.
835
 * Both by policy and by having a token that supports it. */
836
static PRBool
837
ssl_SignatureSchemeAccepted(PRUint16 minVersion,
838
                            SSLSignatureScheme scheme,
839
                            PRBool forCert)
840
232k
{
841
    /* Disable RSA-PSS schemes if there are no tokens to verify them. */
842
232k
    if (ssl_IsRsaPssSignatureScheme(scheme)) {
843
41.1k
        if (!PK11_TokenExists(auth_alg_defs[ssl_auth_rsa_pss])) {
844
0
            return PR_FALSE;
845
0
        }
846
190k
    } else if (!forCert && ssl_IsRsaPkcs1SignatureScheme(scheme)) {
847
        /* Disable PKCS#1 signatures if we are limited to TLS 1.3.
848
         * We still need to advertise PKCS#1 signatures in CH and CR
849
         * for certificate signatures.
850
         */
851
0
        if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_3) {
852
0
            return PR_FALSE;
853
0
        }
854
190k
    } else if (ssl_IsDsaSignatureScheme(scheme)) {
855
        /* DSA: not in TLS 1.3, and check policy. */
856
54.8k
        if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_3) {
857
0
            return PR_FALSE;
858
0
        }
859
54.8k
    }
860
861
232k
    return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy);
862
232k
}
863
864
static SECStatus
865
ssl_CheckSignatureSchemes(sslSocket *ss)
866
26.3k
{
867
26.3k
    if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_2) {
868
0
        return SECSuccess;
869
0
    }
870
871
    /* If this is a server using TLS 1.3, we just need to have one signature
872
     * scheme for which we have a usable certificate.
873
     *
874
     * Note: Certificates for earlier TLS versions are checked along with the
875
     * cipher suite in ssl3_config_match_init. */
876
26.3k
    if (ss->sec.isServer && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
877
0
        PRBool foundCert = PR_FALSE;
878
0
        for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
879
0
            SSLAuthType authType =
880
0
                ssl_SignatureSchemeToAuthType(ss->ssl3.signatureSchemes[i]);
881
0
            if (ssl_HasCert(ss, ss->vrange.max, authType)) {
882
0
                foundCert = PR_TRUE;
883
0
                break;
884
0
            }
885
0
        }
886
0
        if (!foundCert) {
887
0
            PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
888
0
            return SECFailure;
889
0
        }
890
0
    }
891
892
    /* Ensure that there is a signature scheme that can be accepted.*/
893
26.3k
    for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
894
26.3k
        if (ssl_SignatureSchemeAccepted(ss->vrange.min,
895
26.3k
                                        ss->ssl3.signatureSchemes[i],
896
26.3k
                                        PR_FALSE /* forCert */)) {
897
26.3k
            return SECSuccess;
898
26.3k
        }
899
26.3k
    }
900
0
    PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
901
0
    return SECFailure;
902
26.3k
}
903
904
/* For a server, check that a signature scheme that can be used with the
905
 * provided authType is both enabled and usable. */
906
static PRBool
907
ssl_HasSignatureScheme(const sslSocket *ss, SSLAuthType authType)
908
0
{
909
0
    PORT_Assert(ss->sec.isServer);
910
0
    PORT_Assert(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version);
911
0
    PORT_Assert(authType != ssl_auth_null);
912
0
    PORT_Assert(authType != ssl_auth_tls13_any);
913
0
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2 ||
914
0
        authType == ssl_auth_rsa_decrypt ||
915
0
        authType == ssl_auth_ecdh_rsa ||
916
0
        authType == ssl_auth_ecdh_ecdsa) {
917
0
        return PR_TRUE;
918
0
    }
919
0
    for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
920
0
        SSLSignatureScheme scheme = ss->ssl3.signatureSchemes[i];
921
0
        SSLAuthType schemeAuthType = ssl_SignatureSchemeToAuthType(scheme);
922
0
        PRBool acceptable = authType == schemeAuthType ||
923
0
                            (schemeAuthType == ssl_auth_rsa_pss &&
924
0
                             authType == ssl_auth_rsa_sign);
925
0
        if (acceptable && ssl_SignatureSchemeAccepted(ss->version, scheme, PR_FALSE /* forCert */)) {
926
0
            return PR_TRUE;
927
0
        }
928
0
    }
929
0
    return PR_FALSE;
930
0
}
931
932
/* Initialize the suite->isPresent value for config_match
933
 * Returns count of enabled ciphers supported by extant tokens,
934
 * regardless of policy or user preference.
935
 * If this returns zero, the user cannot do SSL v3.
936
 */
937
unsigned int
938
ssl3_config_match_init(sslSocket *ss)
939
26.3k
{
940
26.3k
    ssl3CipherSuiteCfg *suite;
941
26.3k
    const ssl3CipherSuiteDef *cipher_def;
942
26.3k
    SSLCipherAlgorithm cipher_alg;
943
26.3k
    CK_MECHANISM_TYPE cipher_mech;
944
26.3k
    SSLAuthType authType;
945
26.3k
    SSLKEAType keaType;
946
26.3k
    unsigned int i;
947
26.3k
    unsigned int numPresent = 0;
948
26.3k
    unsigned int numEnabled = 0;
949
950
26.3k
    PORT_Assert(ss);
951
26.3k
    if (!ss) {
952
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
953
0
        return 0;
954
0
    }
955
26.3k
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
956
0
        return 0;
957
0
    }
958
26.3k
    if (ss->sec.isServer && ss->psk &&
959
26.3k
        PR_CLIST_IS_EMPTY(&ss->serverCerts) &&
960
26.3k
        (ss->opt.requestCertificate || ss->opt.requireCertificate)) {
961
        /* PSK and certificate auth cannot be combined. */
962
0
        PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
963
0
        return 0;
964
0
    }
965
26.3k
    if (ssl_CheckSignatureSchemes(ss) != SECSuccess) {
966
0
        return 0; /* Code already set. */
967
0
    }
968
969
26.3k
    ssl_FilterSupportedGroups(ss);
970
1.89M
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
971
1.87M
        suite = &ss->cipherSuites[i];
972
1.87M
        if (suite->enabled) {
973
1.87M
            ++numEnabled;
974
            /* We need the cipher defs to see if we have a token that can handle
975
             * this cipher.  It isn't part of the static definition.
976
             */
977
1.87M
            cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
978
1.87M
            if (!cipher_def) {
979
0
                suite->isPresent = PR_FALSE;
980
0
                continue;
981
0
            }
982
1.87M
            cipher_alg = ssl_GetBulkCipherDef(cipher_def)->calg;
983
1.87M
            cipher_mech = ssl3_Alg2Mech(cipher_alg);
984
985
            /* Mark the suites that are backed by real tokens, certs and keys */
986
1.87M
            suite->isPresent = PR_TRUE;
987
988
1.87M
            authType = kea_defs[cipher_def->key_exchange_alg].authKeyType;
989
1.87M
            if (authType != ssl_auth_null && authType != ssl_auth_tls13_any) {
990
1.79M
                if (ss->sec.isServer &&
991
1.79M
                    !(ssl_HasCert(ss, ss->vrange.max, authType) &&
992
0
                      ssl_HasSignatureScheme(ss, authType))) {
993
0
                    suite->isPresent = PR_FALSE;
994
1.79M
                } else if (!PK11_TokenExists(auth_alg_defs[authType])) {
995
0
                    suite->isPresent = PR_FALSE;
996
0
                }
997
1.79M
            }
998
999
1.87M
            keaType = kea_defs[cipher_def->key_exchange_alg].exchKeyType;
1000
1.87M
            if (keaType != ssl_kea_null &&
1001
1.87M
                keaType != ssl_kea_tls13_any &&
1002
1.87M
                !PK11_TokenExists(kea_alg_defs[keaType])) {
1003
0
                suite->isPresent = PR_FALSE;
1004
0
            }
1005
1006
1.87M
            if (cipher_alg != ssl_calg_null &&
1007
1.87M
                !PK11_TokenExists(cipher_mech)) {
1008
0
                suite->isPresent = PR_FALSE;
1009
0
            }
1010
1011
1.87M
            if (suite->isPresent) {
1012
1.87M
                ++numPresent;
1013
1.87M
            }
1014
1.87M
        }
1015
1.87M
    }
1016
26.3k
    PORT_AssertArg(numPresent > 0 || numEnabled == 0);
1017
26.3k
    if (numPresent == 0) {
1018
0
        PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
1019
0
    }
1020
26.3k
    return numPresent;
1021
26.3k
}
1022
1023
/* Return PR_TRUE if suite is usable.  This if the suite is permitted by policy,
1024
 * enabled, has a certificate (as needed), has a viable key agreement method, is
1025
 * usable with the negotiated TLS version, and is otherwise usable. */
1026
PRBool
1027
ssl3_config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy,
1028
                  const SSLVersionRange *vrange, const sslSocket *ss)
1029
986k
{
1030
986k
    const ssl3CipherSuiteDef *cipher_def;
1031
986k
    const ssl3KEADef *kea_def;
1032
1033
986k
    if (!suite) {
1034
0
        PORT_Assert(suite);
1035
0
        return PR_FALSE;
1036
0
    }
1037
1038
986k
    PORT_Assert(policy != SSL_NOT_ALLOWED);
1039
986k
    if (policy == SSL_NOT_ALLOWED)
1040
0
        return PR_FALSE;
1041
1042
986k
    if (!suite->enabled || !suite->isPresent)
1043
0
        return PR_FALSE;
1044
1045
986k
    if ((suite->policy == SSL_NOT_ALLOWED) ||
1046
986k
        (suite->policy > policy))
1047
0
        return PR_FALSE;
1048
1049
986k
    PORT_Assert(ss != NULL);
1050
986k
    cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
1051
986k
    PORT_Assert(cipher_def != NULL);
1052
986k
    kea_def = &kea_defs[cipher_def->key_exchange_alg];
1053
986k
    PORT_Assert(kea_def != NULL);
1054
986k
    if (!ssl_KEAEnabled(ss, kea_def->exchKeyType)) {
1055
0
        return PR_FALSE;
1056
0
    }
1057
1058
986k
    if (ss->sec.isServer && !ssl_HasCert(ss, vrange->max, kea_def->authKeyType)) {
1059
0
        return PR_FALSE;
1060
0
    }
1061
1062
    /* If a PSK is selected, disable suites that use a different hash than
1063
     * the PSK. We advertise non-PSK-compatible suites in the CH, as we could
1064
     * fallback to certificate auth. The client handler will check hash
1065
     * compatibility before committing to use the PSK. */
1066
986k
    if (ss->xtnData.selectedPsk) {
1067
0
        if (ss->xtnData.selectedPsk->hash != cipher_def->prf_hash) {
1068
0
            return PR_FALSE;
1069
0
        }
1070
0
    }
1071
1072
986k
    return ssl3_CipherSuiteAllowedForVersionRange(suite->cipher_suite, vrange);
1073
986k
}
1074
1075
/* For TLS 1.3, when resuming, check for a ciphersuite that is both compatible
1076
 * with the identified ciphersuite and enabled. */
1077
static PRBool
1078
tls13_ResumptionCompatible(sslSocket *ss, ssl3CipherSuite suite)
1079
0
{
1080
0
    SSLVersionRange vrange = { SSL_LIBRARY_VERSION_TLS_1_3,
1081
0
                               SSL_LIBRARY_VERSION_TLS_1_3 };
1082
0
    SSLHashType hash = tls13_GetHashForCipherSuite(suite);
1083
0
    for (unsigned int i = 0; i < PR_ARRAY_SIZE(cipher_suite_defs); i++) {
1084
0
        if (cipher_suite_defs[i].prf_hash == hash) {
1085
0
            const ssl3CipherSuiteCfg *suiteCfg =
1086
0
                ssl_LookupCipherSuiteCfg(cipher_suite_defs[i].cipher_suite,
1087
0
                                         ss->cipherSuites);
1088
0
            if (suite && ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) {
1089
0
                return PR_TRUE;
1090
0
            }
1091
0
        }
1092
0
    }
1093
0
    return PR_FALSE;
1094
0
}
1095
1096
/*
1097
 * Null compression, mac and encryption functions
1098
 */
1099
SECStatus
1100
Null_Cipher(void *ctx, unsigned char *output, unsigned int *outputLen, unsigned int maxOutputLen,
1101
            const unsigned char *input, unsigned int inputLen)
1102
98.6k
{
1103
98.6k
    if (inputLen > maxOutputLen) {
1104
0
        *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */
1105
0
        PORT_SetError(SEC_ERROR_OUTPUT_LEN);
1106
0
        return SECFailure;
1107
0
    }
1108
98.6k
    *outputLen = inputLen;
1109
98.6k
    if (inputLen > 0 && input != output) {
1110
95.8k
        PORT_Memcpy(output, input, inputLen);
1111
95.8k
    }
1112
98.6k
    return SECSuccess;
1113
98.6k
}
1114
1115
/*
1116
 * SSL3 Utility functions
1117
 */
1118
1119
static void
1120
ssl_SetSpecVersions(sslSocket *ss, ssl3CipherSpec *spec)
1121
26.8k
{
1122
26.8k
    spec->version = ss->version;
1123
26.8k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
1124
117
        tls13_SetSpecRecordVersion(ss, spec);
1125
26.7k
    } else if (IS_DTLS(ss)) {
1126
0
        spec->recordVersion = dtls_TLSVersionToDTLSVersion(ss->version);
1127
26.7k
    } else {
1128
26.7k
        spec->recordVersion = ss->version;
1129
26.7k
    }
1130
26.8k
}
1131
1132
/* allowLargerPeerVersion controls whether the function will select the
1133
 * highest enabled SSL version or fail when peerVersion is greater than the
1134
 * highest enabled version.
1135
 *
1136
 * If allowLargerPeerVersion is true, peerVersion is the peer's highest
1137
 * enabled version rather than the peer's selected version.
1138
 */
1139
SECStatus
1140
ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
1141
                      PRBool allowLargerPeerVersion)
1142
0
{
1143
0
    SSL3ProtocolVersion negotiated;
1144
1145
    /* Prevent negotiating to a lower version in response to a TLS 1.3 HRR. */
1146
0
    if (ss->ssl3.hs.helloRetry) {
1147
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
1148
0
        return SECFailure;
1149
0
    }
1150
1151
0
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
1152
0
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
1153
0
        return SECFailure;
1154
0
    }
1155
1156
0
    if (peerVersion < ss->vrange.min ||
1157
0
        (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
1158
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
1159
0
        return SECFailure;
1160
0
    }
1161
1162
0
    negotiated = PR_MIN(peerVersion, ss->vrange.max);
1163
0
    PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, negotiated));
1164
0
    if (ss->firstHsDone && ss->version != negotiated) {
1165
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
1166
0
        return SECFailure;
1167
0
    }
1168
1169
0
    ss->version = negotiated;
1170
0
    return SECSuccess;
1171
0
}
1172
1173
/* Used by the client when the server produces a version number.
1174
 * This reads, validates, and normalizes the value. */
1175
SECStatus
1176
ssl_ClientReadVersion(sslSocket *ss, PRUint8 **b, unsigned int *len,
1177
                      SSL3ProtocolVersion *version)
1178
12.9k
{
1179
12.9k
    SSL3ProtocolVersion v;
1180
12.9k
    PRUint32 temp;
1181
12.9k
    SECStatus rv;
1182
1183
12.9k
    rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, b, len);
1184
12.9k
    if (rv != SECSuccess) {
1185
5
        return SECFailure; /* alert has been sent */
1186
5
    }
1187
12.9k
    v = (SSL3ProtocolVersion)temp;
1188
1189
12.9k
    if (IS_DTLS(ss)) {
1190
0
        v = dtls_DTLSVersionToTLSVersion(v);
1191
        /* Check for failure. */
1192
0
        if (!v || v > SSL_LIBRARY_VERSION_MAX_SUPPORTED) {
1193
0
            SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
1194
0
            return SECFailure;
1195
0
        }
1196
0
    }
1197
1198
    /* You can't negotiate TLS 1.3 this way. */
1199
12.9k
    if (v >= SSL_LIBRARY_VERSION_TLS_1_3) {
1200
10
        SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
1201
10
        return SECFailure;
1202
10
    }
1203
12.9k
    *version = v;
1204
12.9k
    return SECSuccess;
1205
12.9k
}
1206
1207
SECStatus
1208
ssl3_GetNewRandom(SSL3Random random)
1209
13.6k
{
1210
13.6k
    SECStatus rv;
1211
1212
13.6k
    rv = PK11_GenerateRandom(random, SSL3_RANDOM_LENGTH);
1213
13.6k
    if (rv != SECSuccess) {
1214
0
        ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
1215
0
    }
1216
13.6k
    return rv;
1217
13.6k
}
1218
1219
SECStatus
1220
ssl3_SignHashesWithPrivKey(SSL3Hashes *hash, SECKEYPrivateKey *key,
1221
                           SSLSignatureScheme scheme, PRBool isTls, SECItem *buf)
1222
0
{
1223
0
    SECStatus rv = SECFailure;
1224
0
    PRBool doDerEncode = PR_FALSE;
1225
0
    PRBool useRsaPss = ssl_IsRsaPssSignatureScheme(scheme);
1226
0
    SECItem hashItem;
1227
1228
0
    buf->data = NULL;
1229
1230
0
    switch (SECKEY_GetPrivateKeyType(key)) {
1231
0
        case rsaKey:
1232
0
            hashItem.data = hash->u.raw;
1233
0
            hashItem.len = hash->len;
1234
0
            break;
1235
0
        case dsaKey:
1236
0
            doDerEncode = isTls;
1237
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1238
             * In that case, we use just the SHA1 part. */
1239
0
            if (hash->hashAlg == ssl_hash_none) {
1240
0
                hashItem.data = hash->u.s.sha;
1241
0
                hashItem.len = sizeof(hash->u.s.sha);
1242
0
            } else {
1243
0
                hashItem.data = hash->u.raw;
1244
0
                hashItem.len = hash->len;
1245
0
            }
1246
0
            break;
1247
0
        case ecKey:
1248
0
            doDerEncode = PR_TRUE;
1249
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1250
             * In that case, we use just the SHA1 part. */
1251
0
            if (hash->hashAlg == ssl_hash_none) {
1252
0
                hashItem.data = hash->u.s.sha;
1253
0
                hashItem.len = sizeof(hash->u.s.sha);
1254
0
            } else {
1255
0
                hashItem.data = hash->u.raw;
1256
0
                hashItem.len = hash->len;
1257
0
            }
1258
0
            break;
1259
0
        default:
1260
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
1261
0
            goto done;
1262
0
    }
1263
0
    PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
1264
1265
0
    if (useRsaPss || hash->hashAlg == ssl_hash_none) {
1266
0
        CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1267
0
        int signatureLen = PK11_SignatureLen(key);
1268
1269
0
        SECItem *params = NULL;
1270
0
        CK_RSA_PKCS_PSS_PARAMS pssParams;
1271
0
        SECItem pssParamsItem = { siBuffer,
1272
0
                                  (unsigned char *)&pssParams,
1273
0
                                  sizeof(pssParams) };
1274
1275
0
        if (signatureLen <= 0) {
1276
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
1277
0
            goto done;
1278
0
        }
1279
1280
0
        buf->len = (unsigned)signatureLen;
1281
0
        buf->data = (unsigned char *)PORT_Alloc(signatureLen);
1282
0
        if (!buf->data)
1283
0
            goto done; /* error code was set. */
1284
1285
0
        if (useRsaPss) {
1286
0
            pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1287
0
            pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1288
0
            pssParams.sLen = hashItem.len;
1289
0
            params = &pssParamsItem;
1290
0
            mech = CKM_RSA_PKCS_PSS;
1291
0
        }
1292
1293
0
        rv = PK11_SignWithMechanism(key, mech, params, buf, &hashItem);
1294
0
    } else {
1295
0
        SECOidTag hashOID = ssl3_HashTypeToOID(hash->hashAlg);
1296
0
        rv = SGN_Digest(key, hashOID, buf, &hashItem);
1297
0
    }
1298
0
    if (rv != SECSuccess) {
1299
0
        ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
1300
0
    } else if (doDerEncode) {
1301
0
        SECItem derSig = { siBuffer, NULL, 0 };
1302
1303
        /* This also works for an ECDSA signature */
1304
0
        rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
1305
0
        if (rv == SECSuccess) {
1306
0
            PORT_Free(buf->data); /* discard unencoded signature. */
1307
0
            *buf = derSig;        /* give caller encoded signature. */
1308
0
        } else if (derSig.data) {
1309
0
            PORT_Free(derSig.data);
1310
0
        }
1311
0
    }
1312
1313
0
    PRINT_BUF(60, (NULL, "signed hashes", (unsigned char *)buf->data, buf->len));
1314
0
done:
1315
0
    if (rv != SECSuccess && buf->data) {
1316
0
        PORT_Free(buf->data);
1317
0
        buf->data = NULL;
1318
0
    }
1319
0
    return rv;
1320
0
}
1321
1322
/* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
1323
SECStatus
1324
ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash, SECKEYPrivateKey *key,
1325
                SECItem *buf)
1326
0
{
1327
0
    SECStatus rv = SECFailure;
1328
0
    PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
1329
0
    SSLSignatureScheme scheme = ss->ssl3.hs.signatureScheme;
1330
1331
0
    rv = ssl3_SignHashesWithPrivKey(hash, key, scheme, isTLS, buf);
1332
0
    if (rv != SECSuccess) {
1333
0
        return SECFailure;
1334
0
    }
1335
1336
0
    if (ss->sec.isServer) {
1337
0
        ss->sec.signatureScheme = scheme;
1338
0
        ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
1339
0
    }
1340
1341
0
    return SECSuccess;
1342
0
}
1343
1344
/* Called from ssl3_VerifySignedHashes and tls13_HandleCertificateVerify. */
1345
SECStatus
1346
ssl_VerifySignedHashesWithPubKey(sslSocket *ss, SECKEYPublicKey *key,
1347
                                 SSLSignatureScheme scheme,
1348
                                 SSL3Hashes *hash, SECItem *buf)
1349
2.12k
{
1350
2.12k
    SECItem *signature = NULL;
1351
2.12k
    SECStatus rv = SECFailure;
1352
2.12k
    SECItem hashItem;
1353
2.12k
    SECOidTag encAlg;
1354
2.12k
    SECOidTag hashAlg;
1355
2.12k
    void *pwArg = ss->pkcs11PinArg;
1356
2.12k
    PRBool isRsaPssScheme = ssl_IsRsaPssSignatureScheme(scheme);
1357
1358
2.12k
    PRINT_BUF(60, (NULL, "check signed hashes", buf->data, buf->len));
1359
1360
2.12k
    hashAlg = ssl3_HashTypeToOID(hash->hashAlg);
1361
2.12k
    switch (SECKEY_GetPublicKeyType(key)) {
1362
1.47k
        case rsaKey:
1363
1.47k
            encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
1364
1.47k
            hashItem.data = hash->u.raw;
1365
1.47k
            hashItem.len = hash->len;
1366
1.47k
            if (scheme == ssl_sig_none) {
1367
631
                scheme = ssl_sig_rsa_pkcs1_sha1md5;
1368
631
            }
1369
1.47k
            break;
1370
3
        case dsaKey:
1371
3
            encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
1372
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1373
             * In that case, we use just the SHA1 part. */
1374
3
            if (hash->hashAlg == ssl_hash_none) {
1375
0
                hashItem.data = hash->u.s.sha;
1376
0
                hashItem.len = sizeof(hash->u.s.sha);
1377
3
            } else {
1378
3
                hashItem.data = hash->u.raw;
1379
3
                hashItem.len = hash->len;
1380
3
            }
1381
            /* Allow DER encoded DSA signatures in SSL 3.0 */
1382
3
            if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0 ||
1383
3
                buf->len != SECKEY_SignatureLen(key)) {
1384
3
                signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key));
1385
3
                if (!signature) {
1386
1
                    PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1387
1
                    goto loser;
1388
1
                }
1389
2
                buf = signature;
1390
2
            }
1391
2
            if (scheme == ssl_sig_none) {
1392
0
                scheme = ssl_sig_dsa_sha1;
1393
0
            }
1394
2
            break;
1395
1396
645
        case ecKey:
1397
645
            encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
1398
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1399
             * In that case, we use just the SHA1 part.
1400
             * ECDSA signatures always encode the integers r and s using ASN.1
1401
             * (unlike DSA where ASN.1 encoding is used with TLS but not with
1402
             * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
1403
             */
1404
645
            if (hash->hashAlg == ssl_hash_none) {
1405
199
                hashAlg = SEC_OID_SHA1;
1406
199
                hashItem.data = hash->u.s.sha;
1407
199
                hashItem.len = sizeof(hash->u.s.sha);
1408
446
            } else {
1409
446
                hashItem.data = hash->u.raw;
1410
446
                hashItem.len = hash->len;
1411
446
            }
1412
645
            if (scheme == ssl_sig_none) {
1413
199
                scheme = ssl_sig_ecdsa_sha1;
1414
199
            }
1415
645
            break;
1416
1417
0
        default:
1418
0
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
1419
0
            goto loser;
1420
2.12k
    }
1421
1422
2.12k
    PRINT_BUF(60, (NULL, "hash(es) to be verified",
1423
2.12k
                   hashItem.data, hashItem.len));
1424
1425
2.12k
    if (isRsaPssScheme ||
1426
2.12k
        hashAlg == SEC_OID_UNKNOWN ||
1427
2.12k
        SECKEY_GetPublicKeyType(key) == dsaKey) {
1428
        /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1429
         * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1430
         * above always removes the DER encoding of DSA signatures when
1431
         * present. Thus DSA signatures are always verified with PK11_Verify.
1432
         */
1433
1.15k
        CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1434
1435
1.15k
        SECItem *params = NULL;
1436
1.15k
        CK_RSA_PKCS_PSS_PARAMS pssParams;
1437
1.15k
        SECItem pssParamsItem = { siBuffer,
1438
1.15k
                                  (unsigned char *)&pssParams,
1439
1.15k
                                  sizeof(pssParams) };
1440
1441
1.15k
        if (isRsaPssScheme) {
1442
525
            pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1443
525
            pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1444
525
            pssParams.sLen = hashItem.len;
1445
525
            params = &pssParamsItem;
1446
525
            mech = CKM_RSA_PKCS_PSS;
1447
525
        }
1448
1449
1.15k
        rv = PK11_VerifyWithMechanism(key, mech, params, buf, &hashItem, pwArg);
1450
1.15k
    } else {
1451
968
        rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
1452
968
                                    pwArg);
1453
968
    }
1454
2.12k
    if (signature) {
1455
2
        SECITEM_FreeItem(signature, PR_TRUE);
1456
2
    }
1457
2.12k
    if (rv != SECSuccess) {
1458
2.12k
        ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1459
2.12k
    }
1460
2.12k
    if (!ss->sec.isServer) {
1461
2.12k
        ss->sec.signatureScheme = scheme;
1462
2.12k
        ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
1463
2.12k
    }
1464
1465
2.12k
loser:
1466
2.12k
#ifdef UNSAFE_FUZZER_MODE
1467
2.12k
    rv = SECSuccess;
1468
2.12k
    PORT_SetError(0);
1469
2.12k
#endif
1470
2.12k
    return rv;
1471
2.12k
}
1472
1473
/* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
1474
SECStatus
1475
ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme, SSL3Hashes *hash,
1476
                        SECItem *buf)
1477
2.12k
{
1478
2.12k
    SECKEYPublicKey *pubKey =
1479
2.12k
        SECKEY_ExtractPublicKey(&ss->sec.peerCert->subjectPublicKeyInfo);
1480
2.12k
    if (pubKey == NULL) {
1481
0
        ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
1482
0
        return SECFailure;
1483
0
    }
1484
2.12k
    SECStatus rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, scheme,
1485
2.12k
                                                    hash, buf);
1486
2.12k
    SECKEY_DestroyPublicKey(pubKey);
1487
2.12k
    return rv;
1488
2.12k
}
1489
1490
/* Caller must set hiLevel error code. */
1491
/* Called from ssl3_ComputeDHKeyHash
1492
 * which are called from ssl3_HandleServerKeyExchange.
1493
 *
1494
 * hashAlg: ssl_hash_none indicates the pre-1.2, MD5/SHA1 combination hash.
1495
 */
1496
SECStatus
1497
ssl3_ComputeCommonKeyHash(SSLHashType hashAlg,
1498
                          PRUint8 *hashBuf, unsigned int bufLen,
1499
                          SSL3Hashes *hashes)
1500
2.12k
{
1501
2.12k
    SECStatus rv;
1502
2.12k
    SECOidTag hashOID;
1503
2.12k
    PRUint32 policy;
1504
1505
2.12k
    if (hashAlg == ssl_hash_none) {
1506
830
        if ((NSS_GetAlgorithmPolicy(SEC_OID_SHA1, &policy) == SECSuccess) &&
1507
830
            !(policy & NSS_USE_ALG_IN_SSL_KX)) {
1508
0
            ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1509
0
            return SECFailure;
1510
0
        }
1511
830
        rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen);
1512
830
        if (rv != SECSuccess) {
1513
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
1514
0
            return rv;
1515
0
        }
1516
830
        rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen);
1517
830
        if (rv != SECSuccess) {
1518
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
1519
0
            return rv;
1520
0
        }
1521
830
        hashes->len = MD5_LENGTH + SHA1_LENGTH;
1522
1.29k
    } else {
1523
1.29k
        hashOID = ssl3_HashTypeToOID(hashAlg);
1524
1.29k
        if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) &&
1525
1.29k
            !(policy & NSS_USE_ALG_IN_SSL_KX)) {
1526
0
            ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1527
0
            return SECFailure;
1528
0
        }
1529
1.29k
        hashes->len = HASH_ResultLenByOidTag(hashOID);
1530
1.29k
        if (hashes->len == 0 || hashes->len > sizeof(hashes->u.raw)) {
1531
0
            ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1532
0
            return SECFailure;
1533
0
        }
1534
1.29k
        rv = PK11_HashBuf(hashOID, hashes->u.raw, hashBuf, bufLen);
1535
1.29k
        if (rv != SECSuccess) {
1536
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
1537
0
            return rv;
1538
0
        }
1539
1.29k
    }
1540
2.12k
    hashes->hashAlg = hashAlg;
1541
2.12k
    return SECSuccess;
1542
2.12k
}
1543
1544
/* Caller must set hiLevel error code. */
1545
/* Called from ssl3_HandleServerKeyExchange. */
1546
static SECStatus
1547
ssl3_ComputeDHKeyHash(sslSocket *ss, SSLHashType hashAlg, SSL3Hashes *hashes,
1548
                      SECItem dh_p, SECItem dh_g, SECItem dh_Ys, PRBool padY)
1549
7
{
1550
7
    sslBuffer buf = SSL_BUFFER_EMPTY;
1551
7
    SECStatus rv;
1552
7
    unsigned int yLen;
1553
7
    unsigned int i;
1554
1555
7
    PORT_Assert(dh_p.data);
1556
7
    PORT_Assert(dh_g.data);
1557
7
    PORT_Assert(dh_Ys.data);
1558
1559
7
    rv = sslBuffer_Append(&buf, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
1560
7
    if (rv != SECSuccess) {
1561
0
        goto loser;
1562
0
    }
1563
7
    rv = sslBuffer_Append(&buf, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
1564
7
    if (rv != SECSuccess) {
1565
0
        goto loser;
1566
0
    }
1567
    /* p */
1568
7
    rv = sslBuffer_AppendVariable(&buf, dh_p.data, dh_p.len, 2);
1569
7
    if (rv != SECSuccess) {
1570
0
        goto loser;
1571
0
    }
1572
    /* g */
1573
7
    rv = sslBuffer_AppendVariable(&buf, dh_g.data, dh_g.len, 2);
1574
7
    if (rv != SECSuccess) {
1575
0
        goto loser;
1576
0
    }
1577
    /* y - complicated by padding */
1578
7
    yLen = padY ? dh_p.len : dh_Ys.len;
1579
7
    rv = sslBuffer_AppendNumber(&buf, yLen, 2);
1580
7
    if (rv != SECSuccess) {
1581
0
        goto loser;
1582
0
    }
1583
    /* If we're padding Y, dh_Ys can't be longer than dh_p. */
1584
7
    PORT_Assert(!padY || dh_p.len >= dh_Ys.len);
1585
7
    for (i = dh_Ys.len; i < yLen; ++i) {
1586
0
        rv = sslBuffer_AppendNumber(&buf, 0, 1);
1587
0
        if (rv != SECSuccess) {
1588
0
            goto loser;
1589
0
        }
1590
0
    }
1591
7
    rv = sslBuffer_Append(&buf, dh_Ys.data, dh_Ys.len);
1592
7
    if (rv != SECSuccess) {
1593
0
        goto loser;
1594
0
    }
1595
1596
7
    rv = ssl3_ComputeCommonKeyHash(hashAlg, SSL_BUFFER_BASE(&buf),
1597
7
                                   SSL_BUFFER_LEN(&buf), hashes);
1598
7
    if (rv != SECSuccess) {
1599
0
        goto loser;
1600
0
    }
1601
1602
7
    PRINT_BUF(95, (NULL, "DHkey hash: ", SSL_BUFFER_BASE(&buf),
1603
7
                   SSL_BUFFER_LEN(&buf)));
1604
7
    if (hashAlg == ssl_hash_none) {
1605
4
        PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",
1606
4
                       hashes->u.s.md5, MD5_LENGTH));
1607
4
        PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",
1608
4
                       hashes->u.s.sha, SHA1_LENGTH));
1609
4
    } else {
1610
3
        PRINT_BUF(95, (NULL, "DHkey hash: result",
1611
3
                       hashes->u.raw, hashes->len));
1612
3
    }
1613
1614
7
    sslBuffer_Clear(&buf);
1615
7
    return SECSuccess;
1616
1617
0
loser:
1618
0
    sslBuffer_Clear(&buf);
1619
0
    return SECFailure;
1620
7
}
1621
1622
static SECStatus
1623
ssl3_SetupPendingCipherSpec(sslSocket *ss, SSLSecretDirection direction,
1624
                            const ssl3CipherSuiteDef *suiteDef,
1625
                            ssl3CipherSpec **specp)
1626
18.3k
{
1627
18.3k
    ssl3CipherSpec *spec;
1628
18.3k
    const ssl3CipherSpec *prev;
1629
1630
18.3k
    prev = (direction == ssl_secret_write) ? ss->ssl3.cwSpec : ss->ssl3.crSpec;
1631
18.3k
    if (prev->epoch == PR_UINT16_MAX) {
1632
0
        PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
1633
0
        return SECFailure;
1634
0
    }
1635
1636
18.3k
    spec = ssl_CreateCipherSpec(ss, direction);
1637
18.3k
    if (!spec) {
1638
0
        return SECFailure;
1639
0
    }
1640
1641
18.3k
    spec->cipherDef = ssl_GetBulkCipherDef(suiteDef);
1642
18.3k
    spec->macDef = ssl_GetMacDef(ss, suiteDef);
1643
1644
18.3k
    spec->epoch = prev->epoch + 1;
1645
18.3k
    spec->nextSeqNum = 0;
1646
18.3k
    if (IS_DTLS(ss) && direction == ssl_secret_read) {
1647
0
        dtls_InitRecvdRecords(&spec->recvdRecords);
1648
0
    }
1649
18.3k
    ssl_SetSpecVersions(ss, spec);
1650
1651
18.3k
    ssl_SaveCipherSpec(ss, spec);
1652
18.3k
    *specp = spec;
1653
18.3k
    return SECSuccess;
1654
18.3k
}
1655
1656
/* Fill in the pending cipher spec with info from the selected ciphersuite.
1657
** This is as much initialization as we can do without having key material.
1658
** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1659
** Caller must hold the ssl3 handshake lock.
1660
** Acquires & releases SpecWriteLock.
1661
*/
1662
SECStatus
1663
ssl3_SetupBothPendingCipherSpecs(sslSocket *ss)
1664
9.18k
{
1665
9.18k
    ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
1666
9.18k
    SSL3KeyExchangeAlgorithm kea;
1667
9.18k
    const ssl3CipherSuiteDef *suiteDef;
1668
9.18k
    SECStatus rv;
1669
1670
9.18k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1671
9.18k
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
1672
1673
9.18k
    ssl_GetSpecWriteLock(ss); /*******************************/
1674
1675
    /* This hack provides maximal interoperability with SSL 3 servers. */
1676
9.18k
    if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
1677
        /* SSL records are not being MACed. */
1678
5.12k
        ss->ssl3.cwSpec->version = ss->version;
1679
5.12k
    }
1680
1681
9.18k
    SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1682
9.18k
                SSL_GETPID(), ss->fd, suite));
1683
1684
9.18k
    suiteDef = ssl_LookupCipherSuiteDef(suite);
1685
9.18k
    if (suiteDef == NULL) {
1686
0
        goto loser;
1687
0
    }
1688
1689
9.18k
    if (IS_DTLS(ss)) {
1690
        /* Double-check that we did not pick an RC4 suite */
1691
0
        PORT_Assert(suiteDef->bulk_cipher_alg != cipher_rc4);
1692
0
    }
1693
1694
9.18k
    ss->ssl3.hs.suite_def = suiteDef;
1695
1696
9.18k
    kea = suiteDef->key_exchange_alg;
1697
9.18k
    ss->ssl3.hs.kea_def = &kea_defs[kea];
1698
9.18k
    PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
1699
1700
9.18k
    rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_read, suiteDef,
1701
9.18k
                                     &ss->ssl3.prSpec);
1702
9.18k
    if (rv != SECSuccess) {
1703
0
        goto loser;
1704
0
    }
1705
9.18k
    rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_write, suiteDef,
1706
9.18k
                                     &ss->ssl3.pwSpec);
1707
9.18k
    if (rv != SECSuccess) {
1708
0
        goto loser;
1709
0
    }
1710
1711
9.18k
    if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) {
1712
105
        ss->ssl3.prSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,
1713
105
                                                  ss->opt.recordSizeLimit);
1714
105
        ss->ssl3.pwSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,
1715
105
                                                  ss->xtnData.recordSizeLimit);
1716
105
    }
1717
1718
9.18k
    ssl_ReleaseSpecWriteLock(ss); /*******************************/
1719
9.18k
    return SECSuccess;
1720
1721
0
loser:
1722
0
    ssl_ReleaseSpecWriteLock(ss);
1723
0
    return SECFailure;
1724
9.18k
}
1725
1726
/* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data which
1727
 * is included in the MAC or AEAD additional data) to |buf|. See
1728
 * https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the definition of the
1729
 * AEAD additional data.
1730
 *
1731
 * TLS pseudo-header includes the record's version field, SSL's doesn't. Which
1732
 * pseudo-header definition to use should be decided based on the version of
1733
 * the protocol that was negotiated when the cipher spec became current, NOT
1734
 * based on the version value in the record itself, and the decision is passed
1735
 * to this function as the |includesVersion| argument. But, the |version|
1736
 * argument should be the record's version value.
1737
 */
1738
static SECStatus
1739
ssl3_BuildRecordPseudoHeader(DTLSEpoch epoch,
1740
                             sslSequenceNumber seqNum,
1741
                             SSLContentType ct,
1742
                             PRBool includesVersion,
1743
                             SSL3ProtocolVersion version,
1744
                             PRBool isDTLS,
1745
                             int length,
1746
                             sslBuffer *buf, SSL3ProtocolVersion v)
1747
0
{
1748
0
    SECStatus rv;
1749
0
    if (isDTLS && v < SSL_LIBRARY_VERSION_TLS_1_3) {
1750
0
        rv = sslBuffer_AppendNumber(buf, epoch, 2);
1751
0
        if (rv != SECSuccess) {
1752
0
            return SECFailure;
1753
0
        }
1754
0
        rv = sslBuffer_AppendNumber(buf, seqNum, 6);
1755
0
    } else {
1756
0
        rv = sslBuffer_AppendNumber(buf, seqNum, 8);
1757
0
    }
1758
0
    if (rv != SECSuccess) {
1759
0
        return SECFailure;
1760
0
    }
1761
0
    rv = sslBuffer_AppendNumber(buf, ct, 1);
1762
0
    if (rv != SECSuccess) {
1763
0
        return SECFailure;
1764
0
    }
1765
1766
    /* SSL3 MAC doesn't include the record's version field. */
1767
0
    if (includesVersion) {
1768
        /* TLS MAC and AEAD additional data include version. */
1769
0
        rv = sslBuffer_AppendNumber(buf, version, 2);
1770
0
        if (rv != SECSuccess) {
1771
0
            return SECFailure;
1772
0
        }
1773
0
    }
1774
0
    rv = sslBuffer_AppendNumber(buf, length, 2);
1775
0
    if (rv != SECSuccess) {
1776
0
        return SECFailure;
1777
0
    }
1778
1779
0
    return SECSuccess;
1780
0
}
1781
1782
/* Initialize encryption and MAC contexts for pending spec.
1783
 * Master Secret already is derived.
1784
 * Caller holds Spec write lock.
1785
 */
1786
static SECStatus
1787
ssl3_InitPendingContexts(sslSocket *ss, ssl3CipherSpec *spec)
1788
9.32k
{
1789
9.32k
    CK_MECHANISM_TYPE encMechanism;
1790
9.32k
    CK_ATTRIBUTE_TYPE encMode;
1791
9.32k
    SECItem macParam;
1792
9.32k
    CK_ULONG macLength;
1793
9.32k
    SECItem iv;
1794
9.32k
    SSLCipherAlgorithm calg;
1795
1796
9.32k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1797
9.32k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1798
1799
9.32k
    calg = spec->cipherDef->calg;
1800
9.32k
    PORT_Assert(alg2Mech[calg].calg == calg);
1801
1802
9.32k
    if (spec->cipherDef->type != type_aead) {
1803
8.64k
        macLength = spec->macDef->mac_size;
1804
1805
        /*
1806
        ** Now setup the MAC contexts,
1807
        **   crypto contexts are setup below.
1808
        */
1809
8.64k
        macParam.data = (unsigned char *)&macLength;
1810
8.64k
        macParam.len = sizeof(macLength);
1811
8.64k
        macParam.type = siBuffer;
1812
1813
8.64k
        spec->keyMaterial.macContext = PK11_CreateContextBySymKey(
1814
8.64k
            spec->macDef->mmech, CKA_SIGN, spec->keyMaterial.macKey, &macParam);
1815
8.64k
        if (!spec->keyMaterial.macContext) {
1816
0
            ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1817
0
            return SECFailure;
1818
0
        }
1819
8.64k
    }
1820
1821
    /*
1822
    ** Now setup the crypto contexts.
1823
    */
1824
9.32k
    if (calg == ssl_calg_null) {
1825
948
        spec->cipher = Null_Cipher;
1826
948
        return SECSuccess;
1827
948
    }
1828
1829
8.37k
    encMechanism = ssl3_Alg2Mech(calg);
1830
8.37k
    encMode = (spec->direction == ssl_secret_write) ? CKA_ENCRYPT : CKA_DECRYPT;
1831
8.37k
    if (spec->cipherDef->type == type_aead) {
1832
684
        encMode |= CKA_NSS_MESSAGE;
1833
684
        iv.data = NULL;
1834
684
        iv.len = 0;
1835
7.69k
    } else {
1836
7.69k
        spec->cipher = (SSLCipher)PK11_CipherOp;
1837
7.69k
        iv.data = spec->keyMaterial.iv;
1838
7.69k
        iv.len = spec->cipherDef->iv_size;
1839
7.69k
    }
1840
1841
    /*
1842
     * build the context
1843
     */
1844
8.37k
    spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode,
1845
8.37k
                                                     spec->keyMaterial.key,
1846
8.37k
                                                     &iv);
1847
8.37k
    if (!spec->cipherContext) {
1848
0
        ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1849
0
        return SECFailure;
1850
0
    }
1851
1852
8.37k
    return SECSuccess;
1853
8.37k
}
1854
1855
/* Complete the initialization of all keys, ciphers, MACs and their contexts
1856
 * for the pending Cipher Spec.
1857
 * Called from: ssl3_SendClientKeyExchange  (for Full handshake)
1858
 *              ssl3_HandleRSAClientKeyExchange (for Full handshake)
1859
 *              ssl3_HandleServerHello      (for session restart)
1860
 *              ssl3_HandleClientHello      (for session restart)
1861
 * Sets error code, but caller probably should override to disambiguate.
1862
 *
1863
 * If |secret| is a master secret from a previous connection is reused, |derive|
1864
 * is PR_FALSE.  If the secret is a pre-master secret, then |derive| is PR_TRUE
1865
 * and the master secret is derived from |secret|.
1866
 */
1867
SECStatus
1868
ssl3_InitPendingCipherSpecs(sslSocket *ss, PK11SymKey *secret, PRBool derive)
1869
4.66k
{
1870
4.66k
    PK11SymKey *masterSecret;
1871
4.66k
    ssl3CipherSpec *pwSpec;
1872
4.66k
    ssl3CipherSpec *prSpec;
1873
4.66k
    SECStatus rv;
1874
1875
4.66k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1876
4.66k
    PORT_Assert(secret);
1877
1878
4.66k
    ssl_GetSpecWriteLock(ss); /**************************************/
1879
1880
4.66k
    PORT_Assert(ss->ssl3.pwSpec);
1881
4.66k
    PORT_Assert(ss->ssl3.cwSpec->epoch == ss->ssl3.crSpec->epoch);
1882
4.66k
    prSpec = ss->ssl3.prSpec;
1883
4.66k
    pwSpec = ss->ssl3.pwSpec;
1884
1885
4.66k
    if (ss->ssl3.cwSpec->epoch == PR_UINT16_MAX) {
1886
        /* The problem here is that we have rehandshaked too many
1887
         * times (you are not allowed to wrap the epoch). The
1888
         * spec says you should be discarding the connection
1889
         * and start over, so not much we can do here. */
1890
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1891
0
        goto loser;
1892
0
    }
1893
1894
4.66k
    if (derive) {
1895
4.66k
        rv = ssl3_ComputeMasterSecret(ss, secret, &masterSecret);
1896
4.66k
        if (rv != SECSuccess) {
1897
0
            goto loser;
1898
0
        }
1899
4.66k
    } else {
1900
0
        masterSecret = secret;
1901
0
    }
1902
1903
4.66k
    PORT_Assert(masterSecret);
1904
4.66k
    rv = ssl3_DeriveConnectionKeys(ss, masterSecret);
1905
4.66k
    if (rv != SECSuccess) {
1906
0
        if (derive) {
1907
            /* masterSecret was created here. */
1908
0
            PK11_FreeSymKey(masterSecret);
1909
0
        }
1910
0
        goto loser;
1911
0
    }
1912
1913
    /* Both cipher specs maintain a reference to the master secret, since each
1914
     * is managed and freed independently. */
1915
4.66k
    prSpec->masterSecret = masterSecret;
1916
4.66k
    pwSpec->masterSecret = PK11_ReferenceSymKey(masterSecret);
1917
4.66k
    rv = ssl3_InitPendingContexts(ss, ss->ssl3.prSpec);
1918
4.66k
    if (rv != SECSuccess) {
1919
0
        goto loser;
1920
0
    }
1921
1922
4.66k
    rv = ssl3_InitPendingContexts(ss, ss->ssl3.pwSpec);
1923
4.66k
    if (rv != SECSuccess) {
1924
0
        goto loser;
1925
0
    }
1926
1927
4.66k
    ssl_ReleaseSpecWriteLock(ss); /******************************/
1928
4.66k
    return SECSuccess;
1929
1930
0
loser:
1931
0
    ssl_ReleaseSpecWriteLock(ss); /******************************/
1932
0
    ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
1933
0
    return SECFailure;
1934
4.66k
}
1935
1936
/*
1937
 * 60 bytes is 3 times the maximum length MAC size that is supported.
1938
 */
1939
static const unsigned char mac_pad_1[60] = {
1940
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1941
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1942
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1943
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1944
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1945
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1946
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1947
    0x36, 0x36, 0x36, 0x36
1948
};
1949
static const unsigned char mac_pad_2[60] = {
1950
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1951
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1952
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1953
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1954
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1955
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1956
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1957
    0x5c, 0x5c, 0x5c, 0x5c
1958
};
1959
1960
/* Called from: ssl3_SendRecord()
1961
** Caller must already hold the SpecReadLock. (wish we could assert that!)
1962
*/
1963
static SECStatus
1964
ssl3_ComputeRecordMAC(
1965
    ssl3CipherSpec *spec,
1966
    const unsigned char *header,
1967
    unsigned int headerLen,
1968
    const PRUint8 *input,
1969
    int inputLen,
1970
    unsigned char *outbuf,
1971
    unsigned int *outLen)
1972
0
{
1973
0
    PK11Context *context;
1974
0
    int macSize = spec->macDef->mac_size;
1975
0
    SECStatus rv;
1976
1977
0
    PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen));
1978
0
    PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLen));
1979
1980
0
    if (spec->macDef->mac == ssl_mac_null) {
1981
0
        *outLen = 0;
1982
0
        return SECSuccess;
1983
0
    }
1984
1985
0
    context = spec->keyMaterial.macContext;
1986
0
    rv = PK11_DigestBegin(context);
1987
0
    rv |= PK11_DigestOp(context, header, headerLen);
1988
0
    rv |= PK11_DigestOp(context, input, inputLen);
1989
0
    rv |= PK11_DigestFinal(context, outbuf, outLen, macSize);
1990
0
    PORT_Assert(rv != SECSuccess || *outLen == (unsigned)macSize);
1991
1992
0
    PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLen));
1993
1994
0
    if (rv != SECSuccess) {
1995
0
        rv = SECFailure;
1996
0
        ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
1997
0
    }
1998
0
    return rv;
1999
0
}
2000
2001
/* Called from: ssl3_HandleRecord()
2002
 * Caller must already hold the SpecReadLock. (wish we could assert that!)
2003
 *
2004
 * On entry:
2005
 *   originalLen >= inputLen >= MAC size
2006
 */
2007
static SECStatus
2008
ssl3_ComputeRecordMACConstantTime(
2009
    ssl3CipherSpec *spec,
2010
    const unsigned char *header,
2011
    unsigned int headerLen,
2012
    const PRUint8 *input,
2013
    int inputLen,
2014
    int originalLen,
2015
    unsigned char *outbuf,
2016
    unsigned int *outLen)
2017
0
{
2018
0
    CK_MECHANISM_TYPE macType;
2019
0
    CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
2020
0
    SECItem param, inputItem, outputItem;
2021
0
    int macSize = spec->macDef->mac_size;
2022
0
    SECStatus rv;
2023
0
2024
0
    PORT_Assert(inputLen >= spec->macDef->mac_size);
2025
0
    PORT_Assert(originalLen >= inputLen);
2026
0
2027
0
    if (spec->macDef->mac == ssl_mac_null) {
2028
0
        *outLen = 0;
2029
0
        return SECSuccess;
2030
0
    }
2031
0
2032
0
    macType = CKM_NSS_HMAC_CONSTANT_TIME;
2033
0
    if (spec->version == SSL_LIBRARY_VERSION_3_0) {
2034
0
        macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME;
2035
0
    }
2036
0
2037
0
    params.macAlg = spec->macDef->mmech;
2038
0
    params.ulBodyTotalLen = originalLen;
2039
0
    params.pHeader = (unsigned char *)header; /* const cast */
2040
0
    params.ulHeaderLen = headerLen;
2041
0
2042
0
    param.data = (unsigned char *)&params;
2043
0
    param.len = sizeof(params);
2044
0
    param.type = 0;
2045
0
2046
0
    inputItem.data = (unsigned char *)input;
2047
0
    inputItem.len = inputLen;
2048
0
    inputItem.type = 0;
2049
0
2050
0
    outputItem.data = outbuf;
2051
0
    outputItem.len = *outLen;
2052
0
    outputItem.type = 0;
2053
0
2054
0
    rv = PK11_SignWithSymKey(spec->keyMaterial.macKey, macType, &param,
2055
0
                             &outputItem, &inputItem);
2056
0
    if (rv != SECSuccess) {
2057
0
        if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) {
2058
0
            /* ssl3_ComputeRecordMAC() expects the MAC to have been removed
2059
0
             * from the input length already. */
2060
0
            return ssl3_ComputeRecordMAC(spec, header, headerLen,
2061
0
                                         input, inputLen - macSize,
2062
0
                                         outbuf, outLen);
2063
0
        }
2064
0
2065
0
        *outLen = 0;
2066
0
        rv = SECFailure;
2067
0
        ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2068
0
        return rv;
2069
0
    }
2070
0
2071
0
    PORT_Assert(outputItem.len == (unsigned)macSize);
2072
0
    *outLen = outputItem.len;
2073
0
2074
0
    return rv;
2075
0
}
2076
2077
static PRBool
2078
ssl3_ClientAuthTokenPresent(sslSessionID *sid)
2079
157k
{
2080
157k
    PK11SlotInfo *slot = NULL;
2081
157k
    PRBool isPresent = PR_TRUE;
2082
2083
    /* we only care if we are doing client auth */
2084
157k
    if (!sid || !sid->u.ssl3.clAuthValid) {
2085
157k
        return PR_TRUE;
2086
157k
    }
2087
2088
    /* get the slot */
2089
0
    slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
2090
0
                             sid->u.ssl3.clAuthSlotID);
2091
0
    if (slot == NULL ||
2092
0
        !PK11_IsPresent(slot) ||
2093
0
        sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) ||
2094
0
        sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) ||
2095
0
        sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) ||
2096
0
        (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
2097
0
        isPresent = PR_FALSE;
2098
0
    }
2099
0
    if (slot) {
2100
0
        PK11_FreeSlot(slot);
2101
0
    }
2102
0
    return isPresent;
2103
157k
}
2104
2105
/* Caller must hold the spec read lock. */
2106
SECStatus
2107
ssl3_MACEncryptRecord(ssl3CipherSpec *cwSpec,
2108
                      PRBool isServer,
2109
                      PRBool isDTLS,
2110
                      SSLContentType ct,
2111
                      const PRUint8 *pIn,
2112
                      PRUint32 contentLen,
2113
                      sslBuffer *wrBuf)
2114
0
{
2115
0
    SECStatus rv;
2116
0
    PRUint32 macLen = 0;
2117
0
    PRUint32 fragLen;
2118
0
    PRUint32 p1Len, p2Len, oddLen = 0;
2119
0
    unsigned int ivLen = 0;
2120
0
    unsigned char pseudoHeaderBuf[13];
2121
0
    sslBuffer pseudoHeader = SSL_BUFFER(pseudoHeaderBuf);
2122
0
    unsigned int len;
2123
2124
0
    if (cwSpec->cipherDef->type == type_block &&
2125
0
        cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
2126
        /* Prepend the per-record explicit IV using technique 2b from
2127
         * RFC 4346 section 6.2.3.2: The IV is a cryptographically
2128
         * strong random number XORed with the CBC residue from the previous
2129
         * record.
2130
         */
2131
0
        ivLen = cwSpec->cipherDef->iv_size;
2132
0
        if (ivLen > SSL_BUFFER_SPACE(wrBuf)) {
2133
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2134
0
            return SECFailure;
2135
0
        }
2136
0
        rv = PK11_GenerateRandom(SSL_BUFFER_NEXT(wrBuf), ivLen);
2137
0
        if (rv != SECSuccess) {
2138
0
            ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
2139
0
            return rv;
2140
0
        }
2141
0
        rv = cwSpec->cipher(cwSpec->cipherContext,
2142
0
                            SSL_BUFFER_NEXT(wrBuf), /* output */
2143
0
                            &len,                   /* outlen */
2144
0
                            ivLen,                  /* max outlen */
2145
0
                            SSL_BUFFER_NEXT(wrBuf), /* input */
2146
0
                            ivLen);                 /* input len */
2147
0
        if (rv != SECSuccess || len != ivLen) {
2148
0
            PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2149
0
            return SECFailure;
2150
0
        }
2151
2152
0
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2153
0
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2154
0
    }
2155
0
    rv = ssl3_BuildRecordPseudoHeader(
2156
0
        cwSpec->epoch, cwSpec->nextSeqNum, ct,
2157
0
        cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->recordVersion,
2158
0
        isDTLS, contentLen, &pseudoHeader, cwSpec->version);
2159
0
    PORT_Assert(rv == SECSuccess);
2160
0
    if (cwSpec->cipherDef->type == type_aead) {
2161
0
        const unsigned int nonceLen = cwSpec->cipherDef->explicit_nonce_size;
2162
0
        const unsigned int tagLen = cwSpec->cipherDef->tag_size;
2163
0
        unsigned int ivOffset = 0;
2164
0
        CK_GENERATOR_FUNCTION gen;
2165
        /* ivOut includes the iv and the nonce and is the internal iv/nonce
2166
         * for the AEAD function. On Encrypt, this is an in/out parameter */
2167
0
        unsigned char ivOut[MAX_IV_LENGTH];
2168
0
        ivLen = cwSpec->cipherDef->iv_size;
2169
2170
0
        PORT_Assert((ivLen + nonceLen) <= MAX_IV_LENGTH);
2171
0
        PORT_Assert((ivLen + nonceLen) >= sizeof(sslSequenceNumber));
2172
2173
0
        if (nonceLen + contentLen + tagLen > SSL_BUFFER_SPACE(wrBuf)) {
2174
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2175
0
            return SECFailure;
2176
0
        }
2177
2178
0
        if (nonceLen == 0) {
2179
0
            ivOffset = ivLen - sizeof(sslSequenceNumber);
2180
0
            gen = CKG_GENERATE_COUNTER_XOR;
2181
0
        } else {
2182
0
            ivOffset = ivLen;
2183
0
            gen = CKG_GENERATE_COUNTER;
2184
0
        }
2185
0
        ivOffset = tls13_SetupAeadIv(isDTLS, cwSpec->version, ivOut, cwSpec->keyMaterial.iv,
2186
0
                                     ivOffset, ivLen, cwSpec->epoch);
2187
0
        rv = tls13_AEAD(cwSpec->cipherContext,
2188
0
                        PR_FALSE,
2189
0
                        gen, ivOffset * BPB,                /* iv generator params */
2190
0
                        ivOut,                              /* iv in  */
2191
0
                        ivOut,                              /* iv out */
2192
0
                        ivLen + nonceLen,                   /* full iv length */
2193
0
                        NULL, 0,                            /* nonce is generated*/
2194
0
                        SSL_BUFFER_BASE(&pseudoHeader),     /* aad */
2195
0
                        SSL_BUFFER_LEN(&pseudoHeader),      /* aadlen */
2196
0
                        SSL_BUFFER_NEXT(wrBuf) + nonceLen,  /* output  */
2197
0
                        &len,                               /* out len */
2198
0
                        SSL_BUFFER_SPACE(wrBuf) - nonceLen, /* max out */
2199
0
                        tagLen,
2200
0
                        pIn, contentLen); /* input   */
2201
0
        if (rv != SECSuccess) {
2202
0
            PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2203
0
            return SECFailure;
2204
0
        }
2205
0
        len += nonceLen; /* include the nonce at the beginning */
2206
        /* copy out the generated iv if we are using explict nonces */
2207
0
        if (nonceLen) {
2208
0
            PORT_Memcpy(SSL_BUFFER_NEXT(wrBuf), ivOut + ivLen, nonceLen);
2209
0
        }
2210
2211
0
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2212
0
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2213
0
    } else {
2214
0
        int blockSize = cwSpec->cipherDef->block_size;
2215
2216
        /*
2217
         * Add the MAC
2218
         */
2219
0
        rv = ssl3_ComputeRecordMAC(cwSpec, SSL_BUFFER_BASE(&pseudoHeader),
2220
0
                                   SSL_BUFFER_LEN(&pseudoHeader),
2221
0
                                   pIn, contentLen,
2222
0
                                   SSL_BUFFER_NEXT(wrBuf) + contentLen, &macLen);
2223
0
        if (rv != SECSuccess) {
2224
0
            ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2225
0
            return SECFailure;
2226
0
        }
2227
0
        p1Len = contentLen;
2228
0
        p2Len = macLen;
2229
0
        fragLen = contentLen + macLen; /* needs to be encrypted */
2230
0
        PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
2231
2232
        /*
2233
         * Pad the text (if we're doing a block cipher)
2234
         * then Encrypt it
2235
         */
2236
0
        if (cwSpec->cipherDef->type == type_block) {
2237
0
            unsigned char *pBuf;
2238
0
            int padding_length;
2239
0
            int i;
2240
2241
0
            oddLen = contentLen % blockSize;
2242
            /* Assume blockSize is a power of two */
2243
0
            padding_length = blockSize - 1 - ((fragLen) & (blockSize - 1));
2244
0
            fragLen += padding_length + 1;
2245
0
            PORT_Assert((fragLen % blockSize) == 0);
2246
2247
            /* Pad according to TLS rules (also acceptable to SSL3). */
2248
0
            pBuf = SSL_BUFFER_NEXT(wrBuf) + fragLen - 1;
2249
0
            for (i = padding_length + 1; i > 0; --i) {
2250
0
                *pBuf-- = padding_length;
2251
0
            }
2252
            /* now, if contentLen is not a multiple of block size, fix it */
2253
0
            p2Len = fragLen - p1Len;
2254
0
        }
2255
0
        if (p1Len < 256) {
2256
0
            oddLen = p1Len;
2257
0
            p1Len = 0;
2258
0
        } else {
2259
0
            p1Len -= oddLen;
2260
0
        }
2261
0
        if (oddLen) {
2262
0
            p2Len += oddLen;
2263
0
            PORT_Assert((blockSize < 2) ||
2264
0
                        (p2Len % blockSize) == 0);
2265
0
            memmove(SSL_BUFFER_NEXT(wrBuf) + p1Len, pIn + p1Len, oddLen);
2266
0
        }
2267
0
        if (p1Len > 0) {
2268
0
            unsigned int cipherBytesPart1 = 0;
2269
0
            rv = cwSpec->cipher(cwSpec->cipherContext,
2270
0
                                SSL_BUFFER_NEXT(wrBuf), /* output */
2271
0
                                &cipherBytesPart1,      /* actual outlen */
2272
0
                                p1Len,                  /* max outlen */
2273
0
                                pIn,
2274
0
                                p1Len); /* input, and inputlen */
2275
0
            PORT_Assert(rv == SECSuccess && cipherBytesPart1 == p1Len);
2276
0
            if (rv != SECSuccess || cipherBytesPart1 != p1Len) {
2277
0
                PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2278
0
                return SECFailure;
2279
0
            }
2280
0
            rv = sslBuffer_Skip(wrBuf, p1Len, NULL);
2281
0
            PORT_Assert(rv == SECSuccess);
2282
0
        }
2283
0
        if (p2Len > 0) {
2284
0
            unsigned int cipherBytesPart2 = 0;
2285
0
            rv = cwSpec->cipher(cwSpec->cipherContext,
2286
0
                                SSL_BUFFER_NEXT(wrBuf),
2287
0
                                &cipherBytesPart2, /* output and actual outLen */
2288
0
                                p2Len,             /* max outlen */
2289
0
                                SSL_BUFFER_NEXT(wrBuf),
2290
0
                                p2Len); /* input and inputLen*/
2291
0
            PORT_Assert(rv == SECSuccess && cipherBytesPart2 == p2Len);
2292
0
            if (rv != SECSuccess || cipherBytesPart2 != p2Len) {
2293
0
                PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2294
0
                return SECFailure;
2295
0
            }
2296
0
            rv = sslBuffer_Skip(wrBuf, p2Len, NULL);
2297
0
            PORT_Assert(rv == SECSuccess);
2298
0
        }
2299
0
    }
2300
2301
0
    return SECSuccess;
2302
0
}
2303
2304
/* Note: though this can report failure, it shouldn't. */
2305
SECStatus
2306
ssl_InsertRecordHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec,
2307
                       SSLContentType contentType, sslBuffer *wrBuf,
2308
                       PRBool *needsLength)
2309
37.5k
{
2310
37.5k
    SECStatus rv;
2311
2312
#ifndef UNSAFE_FUZZER_MODE
2313
    if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
2314
        cwSpec->epoch > TrafficKeyClearText) {
2315
        if (IS_DTLS(ss)) {
2316
            return dtls13_InsertCipherTextHeader(ss, cwSpec, wrBuf,
2317
                                                 needsLength);
2318
        }
2319
        contentType = ssl_ct_application_data;
2320
    }
2321
#endif
2322
37.5k
    rv = sslBuffer_AppendNumber(wrBuf, contentType, 1);
2323
37.5k
    if (rv != SECSuccess) {
2324
0
        return SECFailure;
2325
0
    }
2326
2327
37.5k
    rv = sslBuffer_AppendNumber(wrBuf, cwSpec->recordVersion, 2);
2328
37.5k
    if (rv != SECSuccess) {
2329
0
        return SECFailure;
2330
0
    }
2331
37.5k
    if (IS_DTLS(ss)) {
2332
0
        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->epoch, 2);
2333
0
        if (rv != SECSuccess) {
2334
0
            return SECFailure;
2335
0
        }
2336
0
        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->nextSeqNum, 6);
2337
0
        if (rv != SECSuccess) {
2338
0
            return SECFailure;
2339
0
        }
2340
0
    }
2341
37.5k
    *needsLength = PR_TRUE;
2342
37.5k
    return SECSuccess;
2343
37.5k
}
2344
2345
SECStatus
2346
ssl_ProtectRecord(sslSocket *ss, ssl3CipherSpec *cwSpec, SSLContentType ct,
2347
                  const PRUint8 *pIn, PRUint32 contentLen, sslBuffer *wrBuf)
2348
37.5k
{
2349
37.5k
    PRBool needsLength;
2350
37.5k
    unsigned int lenOffset;
2351
37.5k
    SECStatus rv;
2352
2353
37.5k
    PORT_Assert(cwSpec->direction == ssl_secret_write);
2354
37.5k
    PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
2355
37.5k
    PORT_Assert(cwSpec->cipherDef->max_records <= RECORD_SEQ_MAX);
2356
2357
37.5k
    if (cwSpec->nextSeqNum >= cwSpec->cipherDef->max_records) {
2358
0
        SSL_TRC(3, ("%d: SSL[-]: write sequence number at limit 0x%0llx",
2359
0
                    SSL_GETPID(), cwSpec->nextSeqNum));
2360
0
        PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
2361
0
        return SECFailure;
2362
0
    }
2363
2364
37.5k
    rv = ssl_InsertRecordHeader(ss, cwSpec, ct, wrBuf, &needsLength);
2365
37.5k
    if (rv != SECSuccess) {
2366
0
        return SECFailure;
2367
0
    }
2368
37.5k
    if (needsLength) {
2369
37.5k
        rv = sslBuffer_Skip(wrBuf, 2, &lenOffset);
2370
37.5k
        if (rv != SECSuccess) {
2371
0
            return SECFailure;
2372
0
        }
2373
37.5k
    }
2374
2375
37.5k
#ifdef UNSAFE_FUZZER_MODE
2376
37.5k
    {
2377
37.5k
        unsigned int len;
2378
37.5k
        rv = Null_Cipher(NULL, SSL_BUFFER_NEXT(wrBuf), &len,
2379
37.5k
                         SSL_BUFFER_SPACE(wrBuf), pIn, contentLen);
2380
37.5k
        if (rv != SECSuccess) {
2381
0
            return SECFailure; /* error was set */
2382
0
        }
2383
37.5k
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2384
37.5k
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2385
37.5k
    }
2386
#else
2387
    if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
2388
        PRUint8 *cipherText = SSL_BUFFER_NEXT(wrBuf);
2389
        unsigned int bufLen = SSL_BUFFER_LEN(wrBuf);
2390
        rv = tls13_ProtectRecord(ss, cwSpec, ct, pIn, contentLen, wrBuf);
2391
        if (rv != SECSuccess) {
2392
            return SECFailure;
2393
        }
2394
        if (IS_DTLS(ss)) {
2395
            bufLen = SSL_BUFFER_LEN(wrBuf) - bufLen;
2396
            rv = dtls13_MaskSequenceNumber(ss, cwSpec,
2397
                                           SSL_BUFFER_BASE(wrBuf),
2398
                                           cipherText, bufLen);
2399
        }
2400
    } else {
2401
        rv = ssl3_MACEncryptRecord(cwSpec, ss->sec.isServer, IS_DTLS(ss), ct,
2402
                                   pIn, contentLen, wrBuf);
2403
    }
2404
#endif
2405
37.5k
    if (rv != SECSuccess) {
2406
0
        return SECFailure; /* error was set */
2407
0
    }
2408
2409
37.5k
    if (needsLength) {
2410
        /* Insert the length. */
2411
37.5k
        rv = sslBuffer_InsertLength(wrBuf, lenOffset, 2);
2412
37.5k
        if (rv != SECSuccess) {
2413
0
            PORT_Assert(0); /* Can't fail. */
2414
0
            return SECFailure;
2415
0
        }
2416
37.5k
    }
2417
2418
37.5k
    ++cwSpec->nextSeqNum;
2419
37.5k
    return SECSuccess;
2420
37.5k
}
2421
2422
SECStatus
2423
ssl_ProtectNextRecord(sslSocket *ss, ssl3CipherSpec *spec, SSLContentType ct,
2424
                      const PRUint8 *pIn, unsigned int nIn,
2425
                      unsigned int *written)
2426
37.5k
{
2427
37.5k
    sslBuffer *wrBuf = &ss->sec.writeBuf;
2428
37.5k
    unsigned int contentLen;
2429
37.5k
    unsigned int spaceNeeded;
2430
37.5k
    SECStatus rv;
2431
2432
37.5k
    contentLen = PR_MIN(nIn, spec->recordSizeLimit);
2433
37.5k
    spaceNeeded = contentLen + SSL3_BUFFER_FUDGE;
2434
37.5k
    if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
2435
37.5k
        spec->cipherDef->type == type_block) {
2436
4.63k
        spaceNeeded += spec->cipherDef->iv_size;
2437
4.63k
    }
2438
37.5k
    if (spaceNeeded > SSL_BUFFER_SPACE(wrBuf)) {
2439
0
        rv = sslBuffer_Grow(wrBuf, spaceNeeded);
2440
0
        if (rv != SECSuccess) {
2441
0
            SSL_DBG(("%d: SSL3[%d]: failed to expand write buffer to %d",
2442
0
                     SSL_GETPID(), ss->fd, spaceNeeded));
2443
0
            return SECFailure;
2444
0
        }
2445
0
    }
2446
2447
37.5k
    rv = ssl_ProtectRecord(ss, spec, ct, pIn, contentLen, wrBuf);
2448
37.5k
    if (rv != SECSuccess) {
2449
0
        return SECFailure;
2450
0
    }
2451
37.5k
    PRINT_BUF(50, (ss, "send (encrypted) record data:",
2452
37.5k
                   SSL_BUFFER_BASE(wrBuf), SSL_BUFFER_LEN(wrBuf)));
2453
37.5k
    *written = contentLen;
2454
37.5k
    return SECSuccess;
2455
37.5k
}
2456
2457
/* Process the plain text before sending it.
2458
 * Returns the number of bytes of plaintext that were successfully sent
2459
 *  plus the number of bytes of plaintext that were copied into the
2460
 *  output (write) buffer.
2461
 * Returns -1 on an error.  PR_WOULD_BLOCK_ERROR is set if the error is blocking
2462
 *  and not terminal.
2463
 *
2464
 * Notes on the use of the private ssl flags:
2465
 * (no private SSL flags)
2466
 *    Attempt to make and send SSL records for all plaintext
2467
 *    If non-blocking and a send gets WOULD_BLOCK,
2468
 *    or if the pending (ciphertext) buffer is not empty,
2469
 *    then buffer remaining bytes of ciphertext into pending buf,
2470
 *    and continue to do that for all succssive records until all
2471
 *    bytes are used.
2472
 * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2473
 *    As above, except this suppresses all write attempts, and forces
2474
 *    all ciphertext into the pending ciphertext buffer.
2475
 * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
2476
 *    Forces the use of the provided epoch
2477
 */
2478
PRInt32
2479
ssl3_SendRecord(sslSocket *ss,
2480
                ssl3CipherSpec *cwSpec, /* non-NULL for DTLS retransmits */
2481
                SSLContentType ct,
2482
                const PRUint8 *pIn, /* input buffer */
2483
                PRInt32 nIn,        /* bytes of input */
2484
                PRInt32 flags)
2485
38.0k
{
2486
38.0k
    sslBuffer *wrBuf = &ss->sec.writeBuf;
2487
38.0k
    ssl3CipherSpec *spec;
2488
38.0k
    SECStatus rv;
2489
38.0k
    PRInt32 totalSent = 0;
2490
2491
38.0k
    SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
2492
38.0k
                SSL_GETPID(), ss->fd, ssl3_DecodeContentType(ct),
2493
38.0k
                nIn));
2494
38.0k
    PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn));
2495
2496
38.0k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2497
38.0k
    PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
2498
2499
38.0k
    if (ss->ssl3.fatalAlertSent) {
2500
581
        SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent",
2501
581
                    SSL_GETPID(), ss->fd));
2502
581
        if (ct != ssl_ct_alert) {
2503
            /* If we are sending an alert, then we already have an
2504
             * error, so don't overwrite. */
2505
0
            PORT_SetError(SSL_ERROR_HANDSHAKE_FAILED);
2506
0
        }
2507
581
        return -1;
2508
581
    }
2509
2510
    /* check for Token Presence */
2511
37.4k
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
2512
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
2513
0
        return -1;
2514
0
    }
2515
2516
37.4k
    if (ss->recordWriteCallback) {
2517
0
        PRUint16 epoch;
2518
0
        ssl_GetSpecReadLock(ss);
2519
0
        epoch = ss->ssl3.cwSpec->epoch;
2520
0
        ssl_ReleaseSpecReadLock(ss);
2521
0
        rv = ss->recordWriteCallback(ss->fd, epoch, ct, pIn, nIn,
2522
0
                                     ss->recordWriteCallbackArg);
2523
0
        if (rv != SECSuccess) {
2524
0
            return -1;
2525
0
        }
2526
0
        return nIn;
2527
0
    }
2528
2529
37.4k
    if (cwSpec) {
2530
        /* cwSpec can only be set for retransmissions of the DTLS handshake. */
2531
0
        PORT_Assert(IS_DTLS(ss) &&
2532
0
                    (ct == ssl_ct_handshake ||
2533
0
                     ct == ssl_ct_change_cipher_spec));
2534
0
        spec = cwSpec;
2535
37.4k
    } else {
2536
37.4k
        spec = ss->ssl3.cwSpec;
2537
37.4k
    }
2538
2539
75.0k
    while (nIn > 0) {
2540
37.5k
        unsigned int written = 0;
2541
37.5k
        PRInt32 sent;
2542
2543
37.5k
        ssl_GetSpecReadLock(ss);
2544
37.5k
        rv = ssl_ProtectNextRecord(ss, spec, ct, pIn, nIn, &written);
2545
37.5k
        ssl_ReleaseSpecReadLock(ss);
2546
37.5k
        if (rv != SECSuccess) {
2547
0
            goto loser;
2548
0
        }
2549
2550
37.5k
        PORT_Assert(written > 0);
2551
        /* DTLS should not fragment non-application data here. */
2552
37.5k
        if (IS_DTLS(ss) && ct != ssl_ct_application_data) {
2553
0
            PORT_Assert(written == nIn);
2554
0
        }
2555
2556
37.5k
        pIn += written;
2557
37.5k
        nIn -= written;
2558
37.5k
        PORT_Assert(nIn >= 0);
2559
2560
        /* If there's still some previously saved ciphertext,
2561
         * or the caller doesn't want us to send the data yet,
2562
         * then add all our new ciphertext to the amount previously saved.
2563
         */
2564
37.5k
        if ((ss->pendingBuf.len > 0) ||
2565
37.5k
            (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2566
2567
13.9k
            rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf),
2568
13.9k
                                   SSL_BUFFER_LEN(wrBuf));
2569
13.9k
            if (rv != SECSuccess) {
2570
                /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2571
0
                goto loser;
2572
0
            }
2573
2574
13.9k
            if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2575
4.66k
                ss->handshakeBegun = 1;
2576
4.66k
                sent = ssl_SendSavedWriteData(ss);
2577
4.66k
                if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2578
0
                    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2579
0
                    goto loser;
2580
0
                }
2581
4.66k
                if (ss->pendingBuf.len) {
2582
0
                    flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2583
0
                }
2584
4.66k
            }
2585
23.6k
        } else {
2586
23.6k
            PORT_Assert(SSL_BUFFER_LEN(wrBuf) > 0);
2587
23.6k
            ss->handshakeBegun = 1;
2588
23.6k
            sent = ssl_DefSend(ss, SSL_BUFFER_BASE(wrBuf),
2589
23.6k
                               SSL_BUFFER_LEN(wrBuf),
2590
23.6k
                               flags & ~ssl_SEND_FLAG_MASK);
2591
23.6k
            if (sent < 0) {
2592
0
                if (PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
2593
0
                    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2594
0
                    goto loser;
2595
0
                }
2596
                /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
2597
0
                sent = 0;
2598
0
            }
2599
23.6k
            if (SSL_BUFFER_LEN(wrBuf) > (unsigned int)sent) {
2600
0
                if (IS_DTLS(ss)) {
2601
                    /* DTLS just says no in this case. No buffering */
2602
0
                    PORT_SetError(PR_WOULD_BLOCK_ERROR);
2603
0
                    goto loser;
2604
0
                }
2605
                /* now take all the remaining unsent new ciphertext and
2606
                 * append it to the buffer of previously unsent ciphertext.
2607
                 */
2608
0
                rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf) + sent,
2609
0
                                       SSL_BUFFER_LEN(wrBuf) - sent);
2610
0
                if (rv != SECSuccess) {
2611
                    /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2612
0
                    goto loser;
2613
0
                }
2614
0
            }
2615
23.6k
        }
2616
37.5k
        wrBuf->len = 0;
2617
37.5k
        totalSent += written;
2618
37.5k
    }
2619
37.4k
    return totalSent;
2620
2621
0
loser:
2622
    /* Don't leave bits of buffer lying around. */
2623
0
    wrBuf->len = 0;
2624
0
    return -1;
2625
37.4k
}
2626
2627
5.00k
#define SSL3_PENDING_HIGH_WATER 1024
2628
2629
/* Attempt to send the content of "in" in an SSL application_data record.
2630
 * Returns "len" or -1 on failure.
2631
 */
2632
int
2633
ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
2634
                         PRInt32 len, PRInt32 flags)
2635
2.50k
{
2636
2.50k
    PRInt32 totalSent = 0;
2637
2.50k
    PRInt32 discarded = 0;
2638
2.50k
    PRBool splitNeeded = PR_FALSE;
2639
2640
2.50k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2641
    /* These flags for internal use only */
2642
2.50k
    PORT_Assert(!(flags & ssl_SEND_FLAG_NO_RETRANSMIT));
2643
2.50k
    if (len < 0 || !in) {
2644
0
        PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2645
0
        return -1;
2646
0
    }
2647
2648
2.50k
    if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
2649
2.50k
        !ssl_SocketIsBlocking(ss)) {
2650
0
        PORT_Assert(!ssl_SocketIsBlocking(ss));
2651
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
2652
0
        return -1;
2653
0
    }
2654
2655
2.50k
    if (ss->appDataBuffered && len) {
2656
0
        PORT_Assert(in[0] == (unsigned char)(ss->appDataBuffered));
2657
0
        if (in[0] != (unsigned char)(ss->appDataBuffered)) {
2658
0
            PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2659
0
            return -1;
2660
0
        }
2661
0
        in++;
2662
0
        len--;
2663
0
        discarded = 1;
2664
0
    }
2665
2666
    /* We will split the first byte of the record into its own record, as
2667
     * explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h.
2668
     */
2669
2.50k
    if (len > 1 && ss->opt.cbcRandomIV &&
2670
2.50k
        ss->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
2671
2.50k
        ss->ssl3.cwSpec->cipherDef->type == type_block /* CBC */) {
2672
484
        splitNeeded = PR_TRUE;
2673
484
    }
2674
2675
5.49k
    while (len > totalSent) {
2676
2.98k
        PRInt32 sent, toSend;
2677
2678
2.98k
        if (totalSent > 0) {
2679
            /*
2680
             * The thread yield is intended to give the reader thread a
2681
             * chance to get some cycles while the writer thread is in
2682
             * the middle of a large application data write.  (See
2683
             * Bugzilla bug 127740, comment #1.)
2684
             */
2685
484
            ssl_ReleaseXmitBufLock(ss);
2686
484
            PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */
2687
484
            ssl_GetXmitBufLock(ss);
2688
484
        }
2689
2690
2.98k
        if (splitNeeded) {
2691
484
            toSend = 1;
2692
484
            splitNeeded = PR_FALSE;
2693
2.50k
        } else {
2694
2.50k
            toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
2695
2.50k
        }
2696
2697
        /*
2698
         * Note that the 0 epoch is OK because flags will never require
2699
         * its use, as guaranteed by the PORT_Assert above.
2700
         */
2701
2.98k
        sent = ssl3_SendRecord(ss, NULL, ssl_ct_application_data,
2702
2.98k
                               in + totalSent, toSend, flags);
2703
2.98k
        if (sent < 0) {
2704
0
            if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
2705
0
                PORT_Assert(ss->lastWriteBlocked);
2706
0
                break;
2707
0
            }
2708
0
            return -1; /* error code set by ssl3_SendRecord */
2709
0
        }
2710
2.98k
        totalSent += sent;
2711
2.98k
        if (ss->pendingBuf.len) {
2712
            /* must be a non-blocking socket */
2713
0
            PORT_Assert(!ssl_SocketIsBlocking(ss));
2714
0
            PORT_Assert(ss->lastWriteBlocked);
2715
0
            break;
2716
0
        }
2717
2.98k
    }
2718
2.50k
    if (ss->pendingBuf.len) {
2719
        /* Must be non-blocking. */
2720
0
        PORT_Assert(!ssl_SocketIsBlocking(ss));
2721
0
        if (totalSent > 0) {
2722
0
            ss->appDataBuffered = 0x100 | in[totalSent - 1];
2723
0
        }
2724
2725
0
        totalSent = totalSent + discarded - 1;
2726
0
        if (totalSent <= 0) {
2727
0
            PORT_SetError(PR_WOULD_BLOCK_ERROR);
2728
0
            totalSent = SECFailure;
2729
0
        }
2730
0
        return totalSent;
2731
0
    }
2732
2.50k
    ss->appDataBuffered = 0;
2733
2.50k
    return totalSent + discarded;
2734
2.50k
}
2735
2736
/* Attempt to send buffered handshake messages.
2737
 * Always set sendBuf.len to 0, even when returning SECFailure.
2738
 *
2739
 * Depending on whether we are doing DTLS or not, this either calls
2740
 *
2741
 * - ssl3_FlushHandshakeMessages if non-DTLS
2742
 * - dtls_FlushHandshakeMessages if DTLS
2743
 *
2744
 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
2745
 *             ssl3_AppendHandshake(), ssl3_SendClientHello(),
2746
 *             ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
2747
 *             ssl3_SendFinished(),
2748
 */
2749
SECStatus
2750
ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
2751
30.4k
{
2752
30.4k
    if (IS_DTLS(ss)) {
2753
0
        return dtls_FlushHandshakeMessages(ss, flags);
2754
0
    }
2755
30.4k
    return ssl3_FlushHandshakeMessages(ss, flags);
2756
30.4k
}
2757
2758
/* Attempt to send the content of sendBuf buffer in an SSL handshake record.
2759
 * Always set sendBuf.len to 0, even when returning SECFailure.
2760
 *
2761
 * Called from ssl3_FlushHandshake
2762
 */
2763
static SECStatus
2764
ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
2765
30.4k
{
2766
30.4k
    static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2767
30.4k
    PRInt32 count = -1;
2768
30.4k
    SECStatus rv;
2769
2770
30.4k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2771
30.4k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2772
2773
30.4k
    if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
2774
7.39k
        return SECSuccess;
2775
2776
    /* only these flags are allowed */
2777
23.0k
    PORT_Assert(!(flags & ~allowedFlags));
2778
23.0k
    if ((flags & ~allowedFlags) != 0) {
2779
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
2780
0
        return SECFailure;
2781
0
    }
2782
23.0k
    count = ssl3_SendRecord(ss, NULL, ssl_ct_handshake,
2783
23.0k
                            ss->sec.ci.sendBuf.buf,
2784
23.0k
                            ss->sec.ci.sendBuf.len, flags);
2785
23.0k
    if (count < 0) {
2786
0
        int err = PORT_GetError();
2787
0
        PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
2788
0
        if (err == PR_WOULD_BLOCK_ERROR) {
2789
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2790
0
        }
2791
0
        rv = SECFailure;
2792
23.0k
    } else if ((unsigned int)count < ss->sec.ci.sendBuf.len) {
2793
        /* short write should never happen */
2794
0
        PORT_Assert((unsigned int)count >= ss->sec.ci.sendBuf.len);
2795
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2796
0
        rv = SECFailure;
2797
23.0k
    } else {
2798
23.0k
        rv = SECSuccess;
2799
23.0k
    }
2800
2801
    /* Whether we succeeded or failed, toss the old handshake data. */
2802
23.0k
    ss->sec.ci.sendBuf.len = 0;
2803
23.0k
    return rv;
2804
23.0k
}
2805
2806
/*
2807
 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
2808
 * the remote client sends a negative response to our certificate request.
2809
 * Returns SECFailure if the application has required client auth.
2810
 *         SECSuccess otherwise.
2811
 */
2812
SECStatus
2813
ssl3_HandleNoCertificate(sslSocket *ss)
2814
0
{
2815
0
    ssl3_CleanupPeerCerts(ss);
2816
2817
    /* If the server has required client-auth blindly but doesn't
2818
     * actually look at the certificate it won't know that no
2819
     * certificate was presented so we shutdown the socket to ensure
2820
     * an error.  We only do this if we haven't already completed the
2821
     * first handshake because if we're redoing the handshake we
2822
     * know the server is paying attention to the certificate.
2823
     */
2824
0
    if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
2825
0
        (!ss->firstHsDone &&
2826
0
         (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
2827
0
        PRFileDesc *lower;
2828
2829
0
        ssl_UncacheSessionID(ss);
2830
2831
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
2832
0
            SSL3_SendAlert(ss, alert_fatal, certificate_required);
2833
0
        } else {
2834
0
            SSL3_SendAlert(ss, alert_fatal, bad_certificate);
2835
0
        }
2836
2837
0
        lower = ss->fd->lower;
2838
#ifdef _WIN32
2839
        lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
2840
#else
2841
0
        lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
2842
0
#endif
2843
0
        PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
2844
0
        return SECFailure;
2845
0
    }
2846
0
    return SECSuccess;
2847
0
}
2848
2849
/************************************************************************
2850
 * Alerts
2851
 */
2852
2853
/*
2854
** Acquires both handshake and XmitBuf locks.
2855
** Called from: ssl3_IllegalParameter   <-
2856
**              ssl3_HandshakeFailure   <-
2857
**              ssl3_HandleAlert    <- ssl3_HandleRecord.
2858
**              ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
2859
**              ssl3_ConsumeHandshakeVariable <-
2860
**              ssl3_HandleHelloRequest <-
2861
**              ssl3_HandleServerHello  <-
2862
**              ssl3_HandleServerKeyExchange <-
2863
**              ssl3_HandleCertificateRequest <-
2864
**              ssl3_HandleServerHelloDone <-
2865
**              ssl3_HandleClientHello  <-
2866
**              ssl3_HandleV2ClientHello <-
2867
**              ssl3_HandleCertificateVerify <-
2868
**              ssl3_HandleClientKeyExchange <-
2869
**              ssl3_HandleCertificate  <-
2870
**              ssl3_HandleFinished <-
2871
**              ssl3_HandleHandshakeMessage <-
2872
**              ssl3_HandlePostHelloHandshakeMessage <-
2873
**              ssl3_HandleRecord   <-
2874
**
2875
*/
2876
SECStatus
2877
SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
2878
7.39k
{
2879
7.39k
    PRUint8 bytes[2];
2880
7.39k
    SECStatus rv;
2881
7.39k
    PRBool needHsLock = !ssl_HaveSSL3HandshakeLock(ss);
2882
2883
    /* Check that if I need the HS lock I also need the Xmit lock */
2884
7.39k
    PORT_Assert(!needHsLock || !ssl_HaveXmitBufLock(ss));
2885
2886
7.39k
    SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
2887
7.39k
                SSL_GETPID(), ss->fd, level, desc));
2888
2889
7.39k
    bytes[0] = level;
2890
7.39k
    bytes[1] = desc;
2891
2892
7.39k
    if (needHsLock) {
2893
562
        ssl_GetSSL3HandshakeLock(ss);
2894
562
    }
2895
7.39k
    if (level == alert_fatal) {
2896
6.91k
        if (ss->sec.ci.sid) {
2897
6.91k
            ssl_UncacheSessionID(ss);
2898
6.91k
        }
2899
6.91k
    }
2900
2901
7.39k
    rv = tls13_SetAlertCipherSpec(ss);
2902
7.39k
    if (rv != SECSuccess) {
2903
0
        if (needHsLock) {
2904
0
            ssl_ReleaseSSL3HandshakeLock(ss);
2905
0
        }
2906
0
        return rv;
2907
0
    }
2908
2909
7.39k
    ssl_GetXmitBufLock(ss);
2910
7.39k
    rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
2911
7.39k
    if (rv == SECSuccess) {
2912
7.39k
        PRInt32 sent;
2913
7.39k
        sent = ssl3_SendRecord(ss, NULL, ssl_ct_alert, bytes, 2,
2914
7.39k
                               (desc == no_certificate) ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
2915
7.39k
        rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
2916
7.39k
    }
2917
7.39k
    if (level == alert_fatal) {
2918
6.91k
        ss->ssl3.fatalAlertSent = PR_TRUE;
2919
6.91k
    }
2920
7.39k
    ssl_ReleaseXmitBufLock(ss);
2921
7.39k
    if (needHsLock) {
2922
562
        ssl_ReleaseSSL3HandshakeLock(ss);
2923
562
    }
2924
7.39k
    if (rv == SECSuccess && ss->alertSentCallback) {
2925
0
        SSLAlert alert = { level, desc };
2926
0
        ss->alertSentCallback(ss->fd, ss->alertSentCallbackArg, &alert);
2927
0
    }
2928
7.39k
    return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
2929
7.39k
}
2930
2931
/*
2932
 * Send illegal_parameter alert.  Set generic error number.
2933
 */
2934
static SECStatus
2935
ssl3_IllegalParameter(sslSocket *ss)
2936
8
{
2937
8
    (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
2938
8
    PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2939
8
                                   : SSL_ERROR_BAD_SERVER);
2940
8
    return SECFailure;
2941
8
}
2942
2943
/*
2944
 * Send handshake_Failure alert.  Set generic error number.
2945
 */
2946
static SECStatus
2947
ssl3_HandshakeFailure(sslSocket *ss)
2948
0
{
2949
0
    (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
2950
0
    PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2951
0
                                   : SSL_ERROR_BAD_SERVER);
2952
0
    return SECFailure;
2953
0
}
2954
2955
void
2956
ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode)
2957
437
{
2958
437
    SSL3AlertDescription desc = bad_certificate;
2959
437
    PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
2960
2961
437
    switch (errCode) {
2962
0
        case SEC_ERROR_LIBRARY_FAILURE:
2963
0
            desc = unsupported_certificate;
2964
0
            break;
2965
0
        case SEC_ERROR_EXPIRED_CERTIFICATE:
2966
0
            desc = certificate_expired;
2967
0
            break;
2968
0
        case SEC_ERROR_REVOKED_CERTIFICATE:
2969
0
            desc = certificate_revoked;
2970
0
            break;
2971
0
        case SEC_ERROR_INADEQUATE_KEY_USAGE:
2972
0
        case SEC_ERROR_INADEQUATE_CERT_TYPE:
2973
0
            desc = certificate_unknown;
2974
0
            break;
2975
0
        case SEC_ERROR_UNTRUSTED_CERT:
2976
0
            desc = isTLS ? access_denied : certificate_unknown;
2977
0
            break;
2978
0
        case SEC_ERROR_UNKNOWN_ISSUER:
2979
0
        case SEC_ERROR_UNTRUSTED_ISSUER:
2980
0
            desc = isTLS ? unknown_ca : certificate_unknown;
2981
0
            break;
2982
0
        case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
2983
0
            desc = isTLS ? unknown_ca : certificate_expired;
2984
0
            break;
2985
2986
0
        case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
2987
0
        case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
2988
0
        case SEC_ERROR_CA_CERT_INVALID:
2989
0
        case SEC_ERROR_BAD_SIGNATURE:
2990
437
        default:
2991
437
            desc = bad_certificate;
2992
437
            break;
2993
437
    }
2994
437
    SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
2995
437
             SSL_GETPID(), ss->fd, errCode));
2996
2997
437
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
2998
437
}
2999
3000
/*
3001
 * Send decode_error alert.  Set generic error number.
3002
 */
3003
SECStatus
3004
ssl3_DecodeError(sslSocket *ss)
3005
605
{
3006
605
    (void)SSL3_SendAlert(ss, alert_fatal,
3007
605
                         ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error
3008
605
                                                               : illegal_parameter);
3009
605
    PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3010
605
                                   : SSL_ERROR_BAD_SERVER);
3011
605
    return SECFailure;
3012
605
}
3013
3014
/* Called from ssl3_HandleRecord.
3015
** Caller must hold both RecvBuf and Handshake locks.
3016
*/
3017
static SECStatus
3018
ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
3019
8.92k
{
3020
8.92k
    SSL3AlertLevel level;
3021
8.92k
    SSL3AlertDescription desc;
3022
8.92k
    int error;
3023
3024
8.92k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3025
8.92k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3026
3027
8.92k
    SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
3028
3029
8.92k
    if (buf->len != 2) {
3030
43
        (void)ssl3_DecodeError(ss);
3031
43
        PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
3032
43
        return SECFailure;
3033
43
    }
3034
8.88k
    level = (SSL3AlertLevel)buf->buf[0];
3035
8.88k
    desc = (SSL3AlertDescription)buf->buf[1];
3036
8.88k
    buf->len = 0;
3037
8.88k
    SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
3038
8.88k
                SSL_GETPID(), ss->fd, level, desc));
3039
3040
8.88k
    if (ss->alertReceivedCallback) {
3041
0
        SSLAlert alert = { level, desc };
3042
0
        ss->alertReceivedCallback(ss->fd, ss->alertReceivedCallbackArg, &alert);
3043
0
    }
3044
3045
8.88k
    switch (desc) {
3046
2
        case close_notify:
3047
2
            ss->recvdCloseNotify = 1;
3048
2
            error = SSL_ERROR_CLOSE_NOTIFY_ALERT;
3049
2
            break;
3050
282
        case unexpected_message:
3051
282
            error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
3052
282
            break;
3053
246
        case bad_record_mac:
3054
246
            error = SSL_ERROR_BAD_MAC_ALERT;
3055
246
            break;
3056
239
        case decryption_failed_RESERVED:
3057
239
            error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
3058
239
            break;
3059
262
        case record_overflow:
3060
262
            error = SSL_ERROR_RECORD_OVERFLOW_ALERT;
3061
262
            break;
3062
195
        case decompression_failure:
3063
195
            error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
3064
195
            break;
3065
204
        case handshake_failure:
3066
204
            error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
3067
204
            break;
3068
199
        case no_certificate:
3069
199
            error = SSL_ERROR_NO_CERTIFICATE;
3070
199
            break;
3071
210
        case certificate_required:
3072
210
            error = SSL_ERROR_RX_CERTIFICATE_REQUIRED_ALERT;
3073
210
            break;
3074
249
        case bad_certificate:
3075
249
            error = SSL_ERROR_BAD_CERT_ALERT;
3076
249
            break;
3077
209
        case unsupported_certificate:
3078
209
            error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;
3079
209
            break;
3080
388
        case certificate_revoked:
3081
388
            error = SSL_ERROR_REVOKED_CERT_ALERT;
3082
388
            break;
3083
224
        case certificate_expired:
3084
224
            error = SSL_ERROR_EXPIRED_CERT_ALERT;
3085
224
            break;
3086
292
        case certificate_unknown:
3087
292
            error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
3088
292
            break;
3089
239
        case illegal_parameter:
3090
239
            error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;
3091
239
            break;
3092
268
        case inappropriate_fallback:
3093
268
            error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
3094
268
            break;
3095
3096
        /* All alerts below are TLS only. */
3097
241
        case unknown_ca:
3098
241
            error = SSL_ERROR_UNKNOWN_CA_ALERT;
3099
241
            break;
3100
341
        case access_denied:
3101
341
            error = SSL_ERROR_ACCESS_DENIED_ALERT;
3102
341
            break;
3103
234
        case decode_error:
3104
234
            error = SSL_ERROR_DECODE_ERROR_ALERT;
3105
234
            break;
3106
257
        case decrypt_error:
3107
257
            error = SSL_ERROR_DECRYPT_ERROR_ALERT;
3108
257
            break;
3109
381
        case export_restriction:
3110
381
            error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
3111
381
            break;
3112
220
        case protocol_version:
3113
220
            error = SSL_ERROR_PROTOCOL_VERSION_ALERT;
3114
220
            break;
3115
218
        case insufficient_security:
3116
218
            error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
3117
218
            break;
3118
320
        case internal_error:
3119
320
            error = SSL_ERROR_INTERNAL_ERROR_ALERT;
3120
320
            break;
3121
383
        case user_canceled:
3122
383
            error = SSL_ERROR_USER_CANCELED_ALERT;
3123
383
            break;
3124
240
        case no_renegotiation:
3125
240
            error = SSL_ERROR_NO_RENEGOTIATION_ALERT;
3126
240
            break;
3127
3128
        /* Alerts for TLS client hello extensions */
3129
203
        case missing_extension:
3130
203
            error = SSL_ERROR_MISSING_EXTENSION_ALERT;
3131
203
            break;
3132
223
        case unsupported_extension:
3133
223
            error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT;
3134
223
            break;
3135
200
        case certificate_unobtainable:
3136
200
            error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT;
3137
200
            break;
3138
205
        case unrecognized_name:
3139
205
            error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
3140
205
            break;
3141
299
        case bad_certificate_status_response:
3142
299
            error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT;
3143
299
            break;
3144
197
        case bad_certificate_hash_value:
3145
197
            error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT;
3146
197
            break;
3147
461
        case no_application_protocol:
3148
461
            error = SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL;
3149
461
            break;
3150
215
        case ech_required:
3151
215
            error = SSL_ERROR_ECH_REQUIRED_ALERT;
3152
215
            break;
3153
336
        default:
3154
336
            error = SSL_ERROR_RX_UNKNOWN_ALERT;
3155
336
            break;
3156
8.88k
    }
3157
8.88k
    if ((ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) &&
3158
8.88k
        (ss->ssl3.hs.ws != wait_server_hello)) {
3159
        /* TLS 1.3 requires all but "end of data" alerts to be
3160
         * treated as fatal. */
3161
0
        switch (desc) {
3162
0
            case close_notify:
3163
0
            case user_canceled:
3164
0
                break;
3165
0
            default:
3166
0
                level = alert_fatal;
3167
0
        }
3168
0
    }
3169
8.88k
    if (level == alert_fatal) {
3170
12
        ssl_UncacheSessionID(ss);
3171
12
        if ((ss->ssl3.hs.ws == wait_server_hello) &&
3172
12
            (desc == handshake_failure)) {
3173
            /* XXX This is a hack.  We're assuming that any handshake failure
3174
             * XXX on the client hello is a failure to match ciphers.
3175
             */
3176
1
            error = SSL_ERROR_NO_CYPHER_OVERLAP;
3177
1
        }
3178
12
        PORT_SetError(error);
3179
12
        return SECFailure;
3180
12
    }
3181
8.87k
    if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
3182
        /* I'm a server. I've requested a client cert. He hasn't got one. */
3183
0
        SECStatus rv;
3184
3185
0
        PORT_Assert(ss->sec.isServer);
3186
0
        ss->ssl3.hs.ws = wait_client_key;
3187
0
        rv = ssl3_HandleNoCertificate(ss);
3188
0
        return rv;
3189
0
    }
3190
8.87k
    return SECSuccess;
3191
8.87k
}
3192
3193
/*
3194
 * Change Cipher Specs
3195
 * Called from ssl3_HandleServerHelloDone,
3196
 *             ssl3_HandleClientHello,
3197
 * and         ssl3_HandleFinished
3198
 *
3199
 * Acquires and releases spec write lock, to protect switching the current
3200
 * and pending write spec pointers.
3201
 */
3202
3203
SECStatus
3204
ssl3_SendChangeCipherSpecsInt(sslSocket *ss)
3205
4.66k
{
3206
4.66k
    PRUint8 change = change_cipher_spec_choice;
3207
4.66k
    SECStatus rv;
3208
3209
4.66k
    SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
3210
4.66k
                SSL_GETPID(), ss->fd));
3211
3212
4.66k
    rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3213
4.66k
    if (rv != SECSuccess) {
3214
0
        return SECFailure; /* error code set by ssl3_FlushHandshake */
3215
0
    }
3216
3217
4.66k
    if (!IS_DTLS(ss)) {
3218
4.66k
        PRInt32 sent;
3219
4.66k
        sent = ssl3_SendRecord(ss, NULL, ssl_ct_change_cipher_spec,
3220
4.66k
                               &change, 1, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3221
4.66k
        if (sent < 0) {
3222
0
            return SECFailure; /* error code set by ssl3_SendRecord */
3223
0
        }
3224
4.66k
    } else {
3225
0
        rv = dtls_QueueMessage(ss, ssl_ct_change_cipher_spec, &change, 1);
3226
0
        if (rv != SECSuccess) {
3227
0
            return SECFailure;
3228
0
        }
3229
0
    }
3230
4.66k
    return SECSuccess;
3231
4.66k
}
3232
3233
static SECStatus
3234
ssl3_SendChangeCipherSpecs(sslSocket *ss)
3235
4.66k
{
3236
4.66k
    SECStatus rv;
3237
3238
4.66k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3239
4.66k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3240
3241
4.66k
    rv = ssl3_SendChangeCipherSpecsInt(ss);
3242
4.66k
    if (rv != SECSuccess) {
3243
0
        return rv; /* Error code set. */
3244
0
    }
3245
3246
    /* swap the pending and current write specs. */
3247
4.66k
    ssl_GetSpecWriteLock(ss); /**************************************/
3248
3249
4.66k
    ssl_CipherSpecRelease(ss->ssl3.cwSpec);
3250
4.66k
    ss->ssl3.cwSpec = ss->ssl3.pwSpec;
3251
4.66k
    ss->ssl3.pwSpec = NULL;
3252
3253
4.66k
    SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
3254
4.66k
                SSL_GETPID(), ss->fd));
3255
3256
    /* With DTLS, we need to set a holddown timer in case the final
3257
     * message got lost */
3258
4.66k
    if (IS_DTLS(ss) && ss->ssl3.crSpec->epoch == ss->ssl3.cwSpec->epoch) {
3259
0
        rv = dtls_StartHolddownTimer(ss);
3260
0
    }
3261
4.66k
    ssl_ReleaseSpecWriteLock(ss); /**************************************/
3262
3263
4.66k
    return rv;
3264
4.66k
}
3265
3266
/* Called from ssl3_HandleRecord.
3267
** Caller must hold both RecvBuf and Handshake locks.
3268
*
3269
* Acquires and releases spec write lock, to protect switching the current
3270
* and pending write spec pointers.
3271
*/
3272
static SECStatus
3273
ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
3274
4.52k
{
3275
4.52k
    SSL3WaitState ws = ss->ssl3.hs.ws;
3276
4.52k
    SSL3ChangeCipherSpecChoice change;
3277
3278
4.52k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3279
4.52k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3280
3281
4.52k
    SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
3282
4.52k
                SSL_GETPID(), ss->fd));
3283
3284
    /* For DTLS: Ignore this if we aren't expecting it.  Don't kill a connection
3285
     *           as a result of receiving trash.
3286
     * For TLS: Maybe ignore, but only after checking format. */
3287
4.52k
    if (ws != wait_change_cipher && IS_DTLS(ss)) {
3288
        /* Ignore this because it's out of order. */
3289
0
        SSL_TRC(3, ("%d: SSL3[%d]: discard out of order "
3290
0
                    "DTLS change_cipher_spec",
3291
0
                    SSL_GETPID(), ss->fd));
3292
0
        buf->len = 0;
3293
0
        return SECSuccess;
3294
0
    }
3295
3296
    /* Handshake messages should not span ChangeCipherSpec. */
3297
4.52k
    if (ss->ssl3.hs.header_bytes) {
3298
8
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3299
8
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3300
8
        return SECFailure;
3301
8
    }
3302
4.51k
    if (buf->len != 1) {
3303
27
        (void)ssl3_DecodeError(ss);
3304
27
        PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3305
27
        return SECFailure;
3306
27
    }
3307
4.49k
    change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
3308
4.49k
    if (change != change_cipher_spec_choice) {
3309
        /* illegal_parameter is correct here for both SSL3 and TLS. */
3310
8
        (void)ssl3_IllegalParameter(ss);
3311
8
        PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3312
8
        return SECFailure;
3313
8
    }
3314
3315
4.48k
    buf->len = 0;
3316
4.48k
    if (ws != wait_change_cipher) {
3317
        /* Ignore a CCS for TLS 1.3. This only happens if the server sends a
3318
         * HelloRetryRequest.  In other cases, the CCS will fail decryption and
3319
         * will be discarded by ssl3_HandleRecord(). */
3320
208
        if (ws == wait_server_hello &&
3321
208
            ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
3322
208
            ss->ssl3.hs.helloRetry) {
3323
202
            PORT_Assert(!ss->sec.isServer);
3324
202
            return SECSuccess;
3325
202
        }
3326
        /* Note: For a server, we can't test ss->ssl3.hs.helloRetry or
3327
         * ss->version because the server might be stateless (and so it won't
3328
         * have set either value yet). Set a flag so that at least we will
3329
         * guarantee that the server will treat any ClientHello properly. */
3330
6
        if (ws == wait_client_hello &&
3331
6
            ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3 &&
3332
6
            !ss->ssl3.hs.receivedCcs) {
3333
0
            PORT_Assert(ss->sec.isServer);
3334
0
            ss->ssl3.hs.receivedCcs = PR_TRUE;
3335
0
            return SECSuccess;
3336
0
        }
3337
6
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3338
6
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3339
6
        return SECFailure;
3340
6
    }
3341
3342
4.27k
    SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
3343
4.27k
                SSL_GETPID(), ss->fd));
3344
4.27k
    ssl_GetSpecWriteLock(ss); /*************************************/
3345
4.27k
    PORT_Assert(ss->ssl3.prSpec);
3346
4.27k
    ssl_CipherSpecRelease(ss->ssl3.crSpec);
3347
4.27k
    ss->ssl3.crSpec = ss->ssl3.prSpec;
3348
4.27k
    ss->ssl3.prSpec = NULL;
3349
4.27k
    ssl_ReleaseSpecWriteLock(ss); /*************************************/
3350
3351
4.27k
    ss->ssl3.hs.ws = wait_finished;
3352
4.27k
    return SECSuccess;
3353
4.48k
}
3354
3355
static CK_MECHANISM_TYPE
3356
ssl3_GetMgfMechanismByHashType(SSLHashType hash)
3357
525
{
3358
525
    switch (hash) {
3359
437
        case ssl_hash_sha256:
3360
437
            return CKG_MGF1_SHA256;
3361
15
        case ssl_hash_sha384:
3362
15
            return CKG_MGF1_SHA384;
3363
73
        case ssl_hash_sha512:
3364
73
            return CKG_MGF1_SHA512;
3365
0
        default:
3366
0
            PORT_Assert(0);
3367
525
    }
3368
0
    return CKG_MGF1_SHA256;
3369
525
}
3370
3371
/* Function valid for >= TLS 1.2, only. */
3372
static CK_MECHANISM_TYPE
3373
ssl3_GetHashMechanismByHashType(SSLHashType hashType)
3374
6.75k
{
3375
6.75k
    switch (hashType) {
3376
73
        case ssl_hash_sha512:
3377
73
            return CKM_SHA512;
3378
986
        case ssl_hash_sha384:
3379
986
            return CKM_SHA384;
3380
1.13k
        case ssl_hash_sha256:
3381
5.69k
        case ssl_hash_none:
3382
            /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
3383
5.69k
            return CKM_SHA256;
3384
0
        case ssl_hash_sha1:
3385
0
            return CKM_SHA_1;
3386
0
        default:
3387
0
            PORT_Assert(0);
3388
6.75k
    }
3389
0
    return CKM_SHA256;
3390
6.75k
}
3391
3392
/* Function valid for >= TLS 1.2, only. */
3393
static CK_MECHANISM_TYPE
3394
ssl3_GetPrfHashMechanism(sslSocket *ss)
3395
6.22k
{
3396
6.22k
    return ssl3_GetHashMechanismByHashType(ss->ssl3.hs.suite_def->prf_hash);
3397
6.22k
}
3398
3399
static SSLHashType
3400
ssl3_GetSuitePrfHash(sslSocket *ss)
3401
2.94k
{
3402
    /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
3403
2.94k
    if (ss->ssl3.hs.suite_def->prf_hash == ssl_hash_none) {
3404
2.23k
        return ssl_hash_sha256;
3405
2.23k
    }
3406
703
    return ss->ssl3.hs.suite_def->prf_hash;
3407
2.94k
}
3408
3409
/* This method completes the derivation of the MS from the PMS.
3410
**
3411
** 1. Derive the MS, if possible, else return an error.
3412
**
3413
** 2. Check the version if |pms_version| is non-zero and if wrong,
3414
**    return an error.
3415
**
3416
** 3. If |msp| is nonzero, return MS in |*msp|.
3417
3418
** Called from:
3419
**   ssl3_ComputeMasterSecretInt
3420
**   tls_ComputeExtendedMasterSecretInt
3421
*/
3422
static SECStatus
3423
ssl3_ComputeMasterSecretFinish(sslSocket *ss,
3424
                               CK_MECHANISM_TYPE master_derive,
3425
                               CK_MECHANISM_TYPE key_derive,
3426
                               CK_VERSION *pms_version,
3427
                               SECItem *params, CK_FLAGS keyFlags,
3428
                               PK11SymKey *pms, PK11SymKey **msp)
3429
4.66k
{
3430
4.66k
    PK11SymKey *ms = NULL;
3431
3432
4.66k
    ms = PK11_DeriveWithFlags(pms, master_derive,
3433
4.66k
                              params, key_derive,
3434
4.66k
                              CKA_DERIVE, 0, keyFlags);
3435
4.66k
    if (!ms) {
3436
0
        ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3437
0
        return SECFailure;
3438
0
    }
3439
3440
4.66k
    if (pms_version && ss->opt.detectRollBack) {
3441
1.20k
        SSL3ProtocolVersion client_version;
3442
1.20k
        client_version = pms_version->major << 8 | pms_version->minor;
3443
3444
1.20k
        if (IS_DTLS(ss)) {
3445
0
            client_version = dtls_DTLSVersionToTLSVersion(client_version);
3446
0
        }
3447
3448
1.20k
        if (client_version != ss->clientHelloVersion) {
3449
            /* Destroy MS.  Version roll-back detected. */
3450
0
            PK11_FreeSymKey(ms);
3451
0
            ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3452
0
            return SECFailure;
3453
0
        }
3454
1.20k
    }
3455
3456
4.66k
    if (msp) {
3457
4.66k
        *msp = ms;
3458
4.66k
    } else {
3459
0
        PK11_FreeSymKey(ms);
3460
0
    }
3461
3462
4.66k
    return SECSuccess;
3463
4.66k
}
3464
3465
/*  Compute the ordinary (pre draft-ietf-tls-session-hash) master
3466
 ** secret and return it in |*msp|.
3467
 **
3468
 ** Called from: ssl3_ComputeMasterSecret
3469
 */
3470
static SECStatus
3471
ssl3_ComputeMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3472
                            PK11SymKey **msp)
3473
4.66k
{
3474
4.66k
    PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
3475
4.66k
    PRBool isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3476
    /*
3477
     * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
3478
     * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
3479
     * data into a 48-byte value, and does not expect to return the version.
3480
     */
3481
4.66k
    PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
3482
4.66k
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh) ||
3483
4.66k
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh_hybrid));
3484
4.66k
    CK_MECHANISM_TYPE master_derive;
3485
4.66k
    CK_MECHANISM_TYPE key_derive;
3486
4.66k
    SECItem params;
3487
4.66k
    CK_FLAGS keyFlags;
3488
4.66k
    CK_VERSION pms_version;
3489
4.66k
    CK_VERSION *pms_version_ptr = NULL;
3490
    /* master_params may be used as a CK_SSL3_MASTER_KEY_DERIVE_PARAMS */
3491
4.66k
    CK_TLS12_MASTER_KEY_DERIVE_PARAMS master_params;
3492
4.66k
    unsigned int master_params_len;
3493
3494
4.66k
    if (isTLS12) {
3495
1.58k
        if (isDH)
3496
643
            master_derive = CKM_TLS12_MASTER_KEY_DERIVE_DH;
3497
944
        else
3498
944
            master_derive = CKM_TLS12_MASTER_KEY_DERIVE;
3499
1.58k
        key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3500
1.58k
        keyFlags = CKF_SIGN | CKF_VERIFY;
3501
3.07k
    } else if (isTLS) {
3502
3.07k
        if (isDH)
3503
2.81k
            master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
3504
256
        else
3505
256
            master_derive = CKM_TLS_MASTER_KEY_DERIVE;
3506
3.07k
        key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3507
3.07k
        keyFlags = CKF_SIGN | CKF_VERIFY;
3508
3.07k
    } else {
3509
0
        if (isDH)
3510
0
            master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
3511
0
        else
3512
0
            master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
3513
0
        key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3514
0
        keyFlags = 0;
3515
0
    }
3516
3517
4.66k
    if (!isDH) {
3518
1.20k
        pms_version_ptr = &pms_version;
3519
1.20k
    }
3520
3521
4.66k
    master_params.pVersion = pms_version_ptr;
3522
4.66k
    master_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
3523
4.66k
    master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3524
4.66k
    master_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
3525
4.66k
    master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3526
4.66k
    if (isTLS12) {
3527
1.58k
        master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3528
1.58k
        master_params_len = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS);
3529
3.07k
    } else {
3530
        /* prfHashMechanism is not relevant with this PRF */
3531
3.07k
        master_params_len = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS);
3532
3.07k
    }
3533
3534
4.66k
    params.data = (unsigned char *)&master_params;
3535
4.66k
    params.len = master_params_len;
3536
3537
4.66k
    return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3538
4.66k
                                          pms_version_ptr, &params,
3539
4.66k
                                          keyFlags, pms, msp);
3540
4.66k
}
3541
3542
/* Compute the draft-ietf-tls-session-hash master
3543
** secret and return it in |*msp|.
3544
**
3545
** Called from: ssl3_ComputeMasterSecret
3546
*/
3547
static SECStatus
3548
tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3549
                                   PK11SymKey **msp)
3550
0
{
3551
0
    ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3552
0
    CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS extended_master_params;
3553
0
    SSL3Hashes hashes;
3554
    /*
3555
     * Determine whether to use the DH/ECDH or RSA derivation modes.
3556
     */
3557
    /*
3558
     * TODO(ekr@rtfm.com): Verify that the slot can handle this key expansion
3559
     * mode. Bug 1198298 */
3560
0
    PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
3561
0
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh) ||
3562
0
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh_hybrid));
3563
0
    CK_MECHANISM_TYPE master_derive;
3564
0
    CK_MECHANISM_TYPE key_derive;
3565
0
    SECItem params;
3566
0
    const CK_FLAGS keyFlags = CKF_SIGN | CKF_VERIFY;
3567
0
    CK_VERSION pms_version;
3568
0
    CK_VERSION *pms_version_ptr = NULL;
3569
0
    SECStatus rv;
3570
3571
0
    rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0);
3572
0
    if (rv != SECSuccess) {
3573
0
        PORT_Assert(0); /* Should never fail */
3574
0
        ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3575
0
        return SECFailure;
3576
0
    }
3577
3578
0
    if (isDH) {
3579
0
        master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH;
3580
0
    } else {
3581
0
        master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE;
3582
0
        pms_version_ptr = &pms_version;
3583
0
    }
3584
3585
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
3586
        /* TLS 1.2+ */
3587
0
        extended_master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3588
0
        key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3589
0
    } else {
3590
        /* TLS < 1.2 */
3591
0
        extended_master_params.prfHashMechanism = CKM_TLS_PRF;
3592
0
        key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3593
0
    }
3594
3595
0
    extended_master_params.pVersion = pms_version_ptr;
3596
0
    extended_master_params.pSessionHash = hashes.u.raw;
3597
0
    extended_master_params.ulSessionHashLen = hashes.len;
3598
3599
0
    params.data = (unsigned char *)&extended_master_params;
3600
0
    params.len = sizeof extended_master_params;
3601
3602
0
    return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3603
0
                                          pms_version_ptr, &params,
3604
0
                                          keyFlags, pms, msp);
3605
0
}
3606
3607
/* Wrapper method to compute the master secret and return it in |*msp|.
3608
**
3609
** Called from ssl3_ComputeMasterSecret
3610
*/
3611
static SECStatus
3612
ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
3613
                         PK11SymKey **msp)
3614
4.66k
{
3615
4.66k
    PORT_Assert(pms != NULL);
3616
4.66k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3617
3618
4.66k
    if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
3619
0
        return tls_ComputeExtendedMasterSecretInt(ss, pms, msp);
3620
4.66k
    } else {
3621
4.66k
        return ssl3_ComputeMasterSecretInt(ss, pms, msp);
3622
4.66k
    }
3623
4.66k
}
3624
3625
/*
3626
 * Derive encryption and MAC Keys (and IVs) from master secret
3627
 * Sets a useful error code when returning SECFailure.
3628
 *
3629
 * Called only from ssl3_InitPendingCipherSpec(),
3630
 * which in turn is called from
3631
 *              ssl3_SendRSAClientKeyExchange    (for Full handshake)
3632
 *              ssl3_SendDHClientKeyExchange     (for Full handshake)
3633
 *              ssl3_HandleClientKeyExchange    (for Full handshake)
3634
 *              ssl3_HandleServerHello          (for session restart)
3635
 *              ssl3_HandleClientHello          (for session restart)
3636
 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
3637
 * ssl3_InitPendingCipherSpec does that.
3638
 *
3639
 */
3640
static SECStatus
3641
ssl3_DeriveConnectionKeys(sslSocket *ss, PK11SymKey *masterSecret)
3642
4.66k
{
3643
4.66k
    ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3644
4.66k
    ssl3CipherSpec *prSpec = ss->ssl3.prSpec;
3645
4.66k
    ssl3CipherSpec *clientSpec;
3646
4.66k
    ssl3CipherSpec *serverSpec;
3647
4.66k
    PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
3648
4.66k
    PRBool isTLS12 =
3649
4.66k
        (PRBool)(isTLS && ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3650
4.66k
    const ssl3BulkCipherDef *cipher_def = pwSpec->cipherDef;
3651
4.66k
    PK11SlotInfo *slot = NULL;
3652
4.66k
    PK11SymKey *derivedKeyHandle = NULL;
3653
4.66k
    void *pwArg = ss->pkcs11PinArg;
3654
4.66k
    int keySize;
3655
4.66k
    CK_TLS12_KEY_MAT_PARAMS key_material_params; /* may be used as a
3656
                                                  * CK_SSL3_KEY_MAT_PARAMS */
3657
4.66k
    unsigned int key_material_params_len;
3658
4.66k
    CK_SSL3_KEY_MAT_OUT returnedKeys;
3659
4.66k
    CK_MECHANISM_TYPE key_derive;
3660
4.66k
    CK_MECHANISM_TYPE bulk_mechanism;
3661
4.66k
    SSLCipherAlgorithm calg;
3662
4.66k
    SECItem params;
3663
4.66k
    PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == ssl_calg_null);
3664
3665
4.66k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3666
4.66k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3667
4.66k
    PORT_Assert(masterSecret);
3668
3669
    /* These functions operate in terms of who is writing specs. */
3670
4.66k
    if (ss->sec.isServer) {
3671
0
        clientSpec = prSpec;
3672
0
        serverSpec = pwSpec;
3673
4.66k
    } else {
3674
4.66k
        clientSpec = pwSpec;
3675
4.66k
        serverSpec = prSpec;
3676
4.66k
    }
3677
3678
    /*
3679
     * generate the key material
3680
     */
3681
4.66k
    if (cipher_def->type == type_block &&
3682
4.66k
        ss->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
3683
        /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
3684
1.15k
        key_material_params.ulIVSizeInBits = 0;
3685
1.15k
        PORT_Memset(clientSpec->keyMaterial.iv, 0, cipher_def->iv_size);
3686
1.15k
        PORT_Memset(serverSpec->keyMaterial.iv, 0, cipher_def->iv_size);
3687
1.15k
    }
3688
3689
4.66k
    key_material_params.bIsExport = PR_FALSE;
3690
4.66k
    key_material_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
3691
4.66k
    key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3692
4.66k
    key_material_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
3693
4.66k
    key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3694
4.66k
    key_material_params.pReturnedKeyMaterial = &returnedKeys;
3695
3696
4.66k
    if (skipKeysAndIVs) {
3697
474
        keySize = 0;
3698
474
        returnedKeys.pIVClient = NULL;
3699
474
        returnedKeys.pIVServer = NULL;
3700
474
        key_material_params.ulKeySizeInBits = 0;
3701
474
        key_material_params.ulIVSizeInBits = 0;
3702
4.18k
    } else {
3703
4.18k
        keySize = cipher_def->key_size;
3704
4.18k
        returnedKeys.pIVClient = clientSpec->keyMaterial.iv;
3705
4.18k
        returnedKeys.pIVServer = serverSpec->keyMaterial.iv;
3706
4.18k
        key_material_params.ulKeySizeInBits = cipher_def->secret_key_size * BPB;
3707
4.18k
        key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB;
3708
4.18k
    }
3709
4.66k
    key_material_params.ulMacSizeInBits = pwSpec->macDef->mac_size * BPB;
3710
3711
4.66k
    calg = cipher_def->calg;
3712
4.66k
    bulk_mechanism = ssl3_Alg2Mech(calg);
3713
3714
4.66k
    if (isTLS12) {
3715
1.58k
        key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3716
1.58k
        key_material_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3717
1.58k
        key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS);
3718
3.07k
    } else if (isTLS) {
3719
3.07k
        key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3720
3.07k
        key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
3721
3.07k
    } else {
3722
0
        key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3723
0
        key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
3724
0
    }
3725
3726
4.66k
    params.data = (unsigned char *)&key_material_params;
3727
4.66k
    params.len = key_material_params_len;
3728
3729
    /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
3730
     * DERIVE by DEFAULT */
3731
4.66k
    derivedKeyHandle = PK11_Derive(masterSecret, key_derive, &params,
3732
4.66k
                                   bulk_mechanism, CKA_ENCRYPT, keySize);
3733
4.66k
    if (!derivedKeyHandle) {
3734
0
        ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3735
0
        return SECFailure;
3736
0
    }
3737
    /* we really should use the actual mac'ing mechanism here, but we
3738
     * don't because these types are used to map keytype anyway and both
3739
     * mac's map to the same keytype.
3740
     */
3741
4.66k
    slot = PK11_GetSlotFromKey(derivedKeyHandle);
3742
3743
4.66k
    PK11_FreeSlot(slot); /* slot is held until the key is freed */
3744
4.66k
    clientSpec->keyMaterial.macKey =
3745
4.66k
        PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3746
4.66k
                              CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret,
3747
4.66k
                              PR_TRUE, pwArg);
3748
4.66k
    if (clientSpec->keyMaterial.macKey == NULL) {
3749
0
        goto loser; /* loser sets err */
3750
0
    }
3751
4.66k
    serverSpec->keyMaterial.macKey =
3752
4.66k
        PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3753
4.66k
                              CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret,
3754
4.66k
                              PR_TRUE, pwArg);
3755
4.66k
    if (serverSpec->keyMaterial.macKey == NULL) {
3756
0
        goto loser; /* loser sets err */
3757
0
    }
3758
4.66k
    if (!skipKeysAndIVs) {
3759
4.18k
        clientSpec->keyMaterial.key =
3760
4.18k
            PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3761
4.18k
                                  bulk_mechanism, returnedKeys.hClientKey,
3762
4.18k
                                  PR_TRUE, pwArg);
3763
4.18k
        if (clientSpec->keyMaterial.key == NULL) {
3764
0
            goto loser; /* loser sets err */
3765
0
        }
3766
4.18k
        serverSpec->keyMaterial.key =
3767
4.18k
            PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3768
4.18k
                                  bulk_mechanism, returnedKeys.hServerKey,
3769
4.18k
                                  PR_TRUE, pwArg);
3770
4.18k
        if (serverSpec->keyMaterial.key == NULL) {
3771
0
            goto loser; /* loser sets err */
3772
0
        }
3773
4.18k
    }
3774
4.66k
    PK11_FreeSymKey(derivedKeyHandle);
3775
4.66k
    return SECSuccess;
3776
3777
0
loser:
3778
0
    PK11_FreeSymKey(derivedKeyHandle);
3779
0
    ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3780
0
    return SECFailure;
3781
4.66k
}
3782
3783
void
3784
ssl3_CoalesceEchHandshakeHashes(sslSocket *ss)
3785
0
{
3786
    /* |sha| contains the CHOuter transcript, which is the singular
3787
     * transcript if not doing ECH. If the server responded with 1.2,
3788
     * contexts are not yet initialized. */
3789
0
    if (ss->ssl3.hs.echAccepted) {
3790
0
        if (ss->ssl3.hs.sha) {
3791
0
            PORT_Assert(ss->ssl3.hs.shaEchInner);
3792
0
            PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
3793
0
            ss->ssl3.hs.sha = ss->ssl3.hs.shaEchInner;
3794
0
            ss->ssl3.hs.shaEchInner = NULL;
3795
0
        }
3796
0
    } else {
3797
0
        if (ss->ssl3.hs.shaEchInner) {
3798
0
            PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
3799
0
            ss->ssl3.hs.shaEchInner = NULL;
3800
0
        }
3801
0
    }
3802
0
}
3803
3804
/* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
3805
 * buffered messages in ss->ssl3.hs.messages. Called from
3806
 * ssl3_NegotiateCipherSuite(), tls13_HandleClientHelloPart2(),
3807
 * and ssl3_HandleServerHello. */
3808
SECStatus
3809
ssl3_InitHandshakeHashes(sslSocket *ss)
3810
12.5k
{
3811
12.5k
    SSL_TRC(30, ("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
3812
3813
12.5k
    PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
3814
12.5k
    if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
3815
5.84k
        ss->ssl3.hs.hashType = handshake_hash_record;
3816
6.70k
    } else {
3817
6.70k
        PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha);
3818
        /*
3819
         * note: We should probably lookup an SSL3 slot for these
3820
         * handshake hashes in hopes that we wind up with the same slots
3821
         * that the master secret will wind up in ...
3822
         */
3823
6.70k
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
3824
            /* determine the hash from the prf */
3825
113
            const SECOidData *hash_oid =
3826
113
                SECOID_FindOIDByMechanism(ssl3_GetPrfHashMechanism(ss));
3827
3828
            /* Get the PKCS #11 mechanism for the Hash from the cipher suite (prf_hash)
3829
             * Convert that to the OidTag. We can then use that OidTag to create our
3830
             * PK11Context */
3831
113
            PORT_Assert(hash_oid != NULL);
3832
113
            if (hash_oid == NULL) {
3833
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3834
0
                return SECFailure;
3835
0
            }
3836
3837
113
            ss->ssl3.hs.sha = PK11_CreateDigestContext(hash_oid->offset);
3838
113
            if (ss->ssl3.hs.sha == NULL) {
3839
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3840
0
                return SECFailure;
3841
0
            }
3842
113
            ss->ssl3.hs.hashType = handshake_hash_single;
3843
113
            if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3844
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3845
0
                return SECFailure;
3846
0
            }
3847
3848
            /* Transcript hash used on ECH client. */
3849
113
            if (!ss->sec.isServer && ss->ssl3.hs.echHpkeCtx) {
3850
0
                ss->ssl3.hs.shaEchInner = PK11_CreateDigestContext(hash_oid->offset);
3851
0
                if (ss->ssl3.hs.shaEchInner == NULL) {
3852
0
                    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3853
0
                    return SECFailure;
3854
0
                }
3855
0
                if (PK11_DigestBegin(ss->ssl3.hs.shaEchInner) != SECSuccess) {
3856
0
                    ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3857
0
                    return SECFailure;
3858
0
                }
3859
0
            }
3860
6.59k
        } else {
3861
            /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
3862
             * created successfully. */
3863
6.59k
            ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
3864
6.59k
            if (ss->ssl3.hs.md5 == NULL) {
3865
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3866
0
                return SECFailure;
3867
0
            }
3868
6.59k
            ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
3869
6.59k
            if (ss->ssl3.hs.sha == NULL) {
3870
0
                PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
3871
0
                ss->ssl3.hs.md5 = NULL;
3872
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3873
0
                return SECFailure;
3874
0
            }
3875
6.59k
            ss->ssl3.hs.hashType = handshake_hash_combo;
3876
3877
6.59k
            if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
3878
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3879
0
                return SECFailure;
3880
0
            }
3881
6.59k
            if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3882
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3883
0
                return SECFailure;
3884
0
            }
3885
6.59k
        }
3886
6.70k
    }
3887
3888
12.5k
    if (ss->ssl3.hs.hashType != handshake_hash_record &&
3889
12.5k
        ss->ssl3.hs.messages.len > 0) {
3890
        /* When doing ECH, ssl3_UpdateHandshakeHashes will store outer messages
3891
         * into the both the outer and inner transcripts.
3892
         * ssl3_UpdateDefaultHandshakeHashes uses the default context which is
3893
         * the outer when doing client ECH. For ECH shared-mode or backend
3894
         * servers only the hs.messages buffer is used. */
3895
6.70k
        if (ssl3_UpdateDefaultHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
3896
6.70k
                                              ss->ssl3.hs.messages.len) != SECSuccess) {
3897
0
            return SECFailure;
3898
0
        }
3899
        /* When doing ECH, deriving the accept_confirmation value requires all
3900
         * messages up to and including the ServerHello
3901
         * (see draft-ietf-tls-esni-14, Section 7.2).
3902
         *
3903
         * Don't free the transcript buffer until confirmation calculation. */
3904
6.70k
        if (!ss->ssl3.hs.echHpkeCtx && !ss->opt.enableTls13BackendEch) {
3905
6.70k
            sslBuffer_Clear(&ss->ssl3.hs.messages);
3906
6.70k
        }
3907
6.70k
    }
3908
12.5k
    if (ss->ssl3.hs.shaEchInner &&
3909
12.5k
        ss->ssl3.hs.echInnerMessages.len > 0) {
3910
0
        if (PK11_DigestOp(ss->ssl3.hs.shaEchInner, ss->ssl3.hs.echInnerMessages.buf,
3911
0
                          ss->ssl3.hs.echInnerMessages.len) != SECSuccess) {
3912
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3913
0
            return SECFailure;
3914
0
        }
3915
0
        if (!ss->ssl3.hs.echHpkeCtx) {
3916
0
            sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
3917
0
        }
3918
0
    }
3919
3920
12.5k
    return SECSuccess;
3921
12.5k
}
3922
3923
void
3924
ssl3_RestartHandshakeHashes(sslSocket *ss)
3925
13.7k
{
3926
13.7k
    SSL_TRC(30, ("%d: SSL3[%d]: reset handshake hashes",
3927
13.7k
                 SSL_GETPID(), ss->fd));
3928
13.7k
    ss->ssl3.hs.hashType = handshake_hash_unknown;
3929
13.7k
    ss->ssl3.hs.messages.len = 0;
3930
13.7k
    ss->ssl3.hs.echInnerMessages.len = 0;
3931
13.7k
    if (ss->ssl3.hs.md5) {
3932
2.83k
        PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
3933
2.83k
        ss->ssl3.hs.md5 = NULL;
3934
2.83k
    }
3935
13.7k
    if (ss->ssl3.hs.sha) {
3936
2.83k
        PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
3937
2.83k
        ss->ssl3.hs.sha = NULL;
3938
2.83k
    }
3939
13.7k
    if (ss->ssl3.hs.shaEchInner) {
3940
0
        PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
3941
0
        ss->ssl3.hs.shaEchInner = NULL;
3942
0
    }
3943
13.7k
    if (ss->ssl3.hs.shaPostHandshake) {
3944
0
        PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
3945
0
        ss->ssl3.hs.shaPostHandshake = NULL;
3946
0
    }
3947
13.7k
}
3948
3949
/* Add the provided bytes to the handshake hash context. When doing
3950
 * TLS 1.3 ECH, |target| may be provided to specify only the inner/outer
3951
 * transcript, else the input is added to both contexts. This happens
3952
 * only on the client. On the server, only the default context is used. */
3953
SECStatus
3954
ssl3_UpdateHandshakeHashesInt(sslSocket *ss, const unsigned char *b,
3955
                              unsigned int l, sslBuffer *target)
3956
121k
{
3957
3958
121k
    SECStatus rv = SECSuccess;
3959
121k
    PRBool explicit = (target != NULL);
3960
121k
    PRBool appendToEchInner = !ss->sec.isServer &&
3961
121k
                              ss->ssl3.hs.echHpkeCtx &&
3962
121k
                              !explicit;
3963
121k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3964
121k
    PORT_Assert(target != &ss->ssl3.hs.echInnerMessages ||
3965
121k
                !ss->sec.isServer);
3966
3967
121k
    if (target == NULL) {
3968
        /* Default context. */
3969
114k
        target = &ss->ssl3.hs.messages;
3970
114k
    }
3971
    /* With TLS 1.3, and versions TLS.1.1 and older, we keep the hash(es)
3972
     * always up to date. However, we must initially buffer the handshake
3973
     * messages, until we know what to do.
3974
     * If ss->ssl3.hs.hashType != handshake_hash_unknown,
3975
     * it means we know what to do. We calculate (hash our input),
3976
     * and we stop appending to the buffer.
3977
     *
3978
     * With TLS 1.2, we always append all handshake messages,
3979
     * and never update the hash, because the hash function we must use for
3980
     * certificate_verify might be different from the hash function we use
3981
     * when signing other handshake hashes. */
3982
121k
    if (ss->ssl3.hs.hashType == handshake_hash_unknown ||
3983
121k
        ss->ssl3.hs.hashType == handshake_hash_record) {
3984
54.9k
        rv = sslBuffer_Append(target, b, l);
3985
54.9k
        if (rv != SECSuccess) {
3986
0
            return SECFailure;
3987
0
        }
3988
54.9k
        if (appendToEchInner) {
3989
0
            return sslBuffer_Append(&ss->ssl3.hs.echInnerMessages, b, l);
3990
0
        }
3991
54.9k
        return SECSuccess;
3992
54.9k
    }
3993
3994
66.6k
    PRINT_BUF(90, (ss, "handshake hash input:", b, l));
3995
3996
66.6k
    if (ss->ssl3.hs.hashType == handshake_hash_single) {
3997
259
        PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
3998
259
        if (target == &ss->ssl3.hs.messages) {
3999
259
            rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
4000
259
            if (rv != SECSuccess) {
4001
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4002
0
                return rv;
4003
0
            }
4004
259
        }
4005
259
        if (ss->ssl3.hs.shaEchInner &&
4006
259
            (target == &ss->ssl3.hs.echInnerMessages || !explicit)) {
4007
0
            rv = PK11_DigestOp(ss->ssl3.hs.shaEchInner, b, l);
4008
0
            if (rv != SECSuccess) {
4009
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4010
0
                return rv;
4011
0
            }
4012
0
        }
4013
66.4k
    } else if (ss->ssl3.hs.hashType == handshake_hash_combo) {
4014
66.4k
        rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
4015
66.4k
        if (rv != SECSuccess) {
4016
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4017
0
            return rv;
4018
0
        }
4019
66.4k
        rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
4020
66.4k
        if (rv != SECSuccess) {
4021
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4022
0
            return rv;
4023
0
        }
4024
66.4k
    }
4025
66.6k
    return rv;
4026
66.6k
}
4027
4028
static SECStatus
4029
ssl3_UpdateDefaultHandshakeHashes(sslSocket *ss, const unsigned char *b,
4030
                                  unsigned int l)
4031
6.81k
{
4032
6.81k
    return ssl3_UpdateHandshakeHashesInt(ss, b, l,
4033
6.81k
                                         &ss->ssl3.hs.messages);
4034
6.81k
}
4035
4036
static SECStatus
4037
ssl3_UpdateInnerHandshakeHashes(sslSocket *ss, const unsigned char *b,
4038
                                unsigned int l)
4039
0
{
4040
0
    return ssl3_UpdateHandshakeHashesInt(ss, b, l,
4041
0
                                         &ss->ssl3.hs.echInnerMessages);
4042
0
}
4043
4044
/*
4045
 * Handshake messages
4046
 */
4047
/* Called from  ssl3_InitHandshakeHashes()
4048
**      ssl3_AppendHandshake()
4049
**      ssl3_HandleV2ClientHello()
4050
**      ssl3_HandleHandshakeMessage()
4051
** Caller must hold the ssl3Handshake lock.
4052
*/
4053
SECStatus
4054
ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l)
4055
114k
{
4056
114k
    return ssl3_UpdateHandshakeHashesInt(ss, b, l, NULL);
4057
114k
}
4058
4059
SECStatus
4060
ssl3_UpdatePostHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l)
4061
0
{
4062
0
    SECStatus rv = SECSuccess;
4063
4064
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4065
4066
0
    PRINT_BUF(90, (ss, "post handshake hash input:", b, l));
4067
4068
0
    PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single);
4069
0
    PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
4070
0
    rv = PK11_DigestOp(ss->ssl3.hs.shaPostHandshake, b, l);
4071
0
    if (rv != SECSuccess) {
4072
0
        PORT_SetError(SSL_ERROR_DIGEST_FAILURE);
4073
0
    }
4074
0
    return rv;
4075
0
}
4076
4077
/* The next two functions serve to append the handshake header.
4078
   The first one additionally writes to seqNumberBuffer
4079
   the sequence number of the message we are generating.
4080
   This function is used when generating the keyUpdate message in dtls13_enqueueKeyUpdateMessage.
4081
*/
4082
SECStatus
4083
ssl3_AppendHandshakeHeaderAndStashSeqNum(sslSocket *ss, SSLHandshakeType t, PRUint32 length, PRUint64 *sendMessageSeqOut)
4084
9.33k
{
4085
9.33k
    PORT_Assert(t != ssl_hs_client_hello);
4086
9.33k
    SECStatus rv;
4087
4088
    /* If we already have a message in place, we need to enqueue it.
4089
     * This empties the buffer. This is a convenient place to call
4090
     * dtls_StageHandshakeMessage to mark the message boundary.
4091
     */
4092
9.33k
    if (IS_DTLS(ss)) {
4093
0
        rv = dtls_StageHandshakeMessage(ss);
4094
0
        if (rv != SECSuccess) {
4095
0
            return rv;
4096
0
        }
4097
0
    }
4098
4099
9.33k
    SSL_TRC(30, ("%d: SSL3[%d]: append handshake header: type %s",
4100
9.33k
                 SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
4101
4102
9.33k
    rv = ssl3_AppendHandshakeNumber(ss, t, 1);
4103
9.33k
    if (rv != SECSuccess) {
4104
0
        return rv; /* error code set by AppendHandshake, if applicable. */
4105
0
    }
4106
9.33k
    rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4107
9.33k
    if (rv != SECSuccess) {
4108
0
        return rv; /* error code set by AppendHandshake, if applicable. */
4109
0
    }
4110
4111
9.33k
    if (IS_DTLS(ss)) {
4112
        /* RFC 9147. 5.2.  DTLS Handshake Message Format.
4113
         * In DTLS 1.3, the message transcript is computed over the original TLS
4114
         * 1.3-style Handshake messages without the message_seq,
4115
         * fragment_offset, and fragment_length values.  Note that this is a
4116
         * change from DTLS 1.2 where those values were included in the transcript. */
4117
0
        PRBool suppressHash = ss->version == SSL_LIBRARY_VERSION_TLS_1_3 ? PR_TRUE : PR_FALSE;
4118
4119
        /* Note that we make an unfragmented message here. We fragment in the
4120
         * transmission code, if necessary */
4121
0
        rv = ssl3_AppendHandshakeNumberSuppressHash(ss, ss->ssl3.hs.sendMessageSeq, 2, suppressHash);
4122
0
        if (rv != SECSuccess) {
4123
0
            return rv; /* error code set by AppendHandshake, if applicable. */
4124
0
        }
4125
        /* In case if we provide a buffer for the sequence message,
4126
        we write down sendMessageSeq to the buffer. */
4127
0
        if (sendMessageSeqOut != NULL) {
4128
0
            *sendMessageSeqOut = ss->ssl3.hs.sendMessageSeq;
4129
0
        }
4130
0
        ss->ssl3.hs.sendMessageSeq++;
4131
4132
        /* 0 is the fragment offset, because it's not fragmented yet */
4133
0
        rv = ssl3_AppendHandshakeNumberSuppressHash(ss, 0, 3, suppressHash);
4134
0
        if (rv != SECSuccess) {
4135
0
            return rv; /* error code set by AppendHandshake, if applicable. */
4136
0
        }
4137
4138
        /* Fragment length -- set to the packet length because not fragmented */
4139
0
        rv = ssl3_AppendHandshakeNumberSuppressHash(ss, length, 3, suppressHash);
4140
0
        if (rv != SECSuccess) {
4141
0
            return rv; /* error code set by AppendHandshake, if applicable. */
4142
0
        }
4143
0
    }
4144
4145
9.33k
    return rv; /* error code set by AppendHandshake, if applicable. */
4146
9.33k
}
4147
4148
/* The function calls the ssl3_AppendHandshakeHeaderAndStashSeqNum implemented above.
4149
   As in the majority of the cases we do not need the last parameter,
4150
   we separate out this function. */
4151
SECStatus
4152
ssl3_AppendHandshakeHeader(sslSocket *ss, SSLHandshakeType t, PRUint32 length)
4153
9.33k
{
4154
9.33k
    return ssl3_AppendHandshakeHeaderAndStashSeqNum(ss, t, length, NULL);
4155
9.33k
}
4156
4157
/**************************************************************************
4158
 * Consume Handshake functions.
4159
 *
4160
 * All data used in these functions is protected by two locks,
4161
 * the RecvBufLock and the SSL3HandshakeLock
4162
 **************************************************************************/
4163
4164
/* Read up the next "bytes" number of bytes from the (decrypted) input
4165
 * stream "b" (which is *length bytes long). Copy them into buffer "v".
4166
 * Reduces *length by bytes.  Advances *b by bytes.
4167
 *
4168
 * If this function returns SECFailure, it has already sent an alert,
4169
 * and has set a generic error code.  The caller should probably
4170
 * override the generic error code by setting another.
4171
 */
4172
SECStatus
4173
ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRUint32 bytes, PRUint8 **b,
4174
                      PRUint32 *length)
4175
15.0k
{
4176
15.0k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4177
15.0k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4178
4179
15.0k
    if ((PRUint32)bytes > *length) {
4180
27
        return ssl3_DecodeError(ss);
4181
27
    }
4182
15.0k
    PORT_Memcpy(v, *b, bytes);
4183
15.0k
    PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4184
15.0k
    *b += bytes;
4185
15.0k
    *length -= bytes;
4186
15.0k
    return SECSuccess;
4187
15.0k
}
4188
4189
/* Read up the next "bytes" number of bytes from the (decrypted) input
4190
 * stream "b" (which is *length bytes long), and interpret them as an
4191
 * integer in network byte order.  Sets *num to the received value.
4192
 * Reduces *length by bytes.  Advances *b by bytes.
4193
 *
4194
 * On error, an alert has been sent, and a generic error code has been set.
4195
 */
4196
SECStatus
4197
ssl3_ConsumeHandshakeNumber64(sslSocket *ss, PRUint64 *num, PRUint32 bytes,
4198
                              PRUint8 **b, PRUint32 *length)
4199
126k
{
4200
126k
    PRUint8 *buf = *b;
4201
126k
    PRUint32 i;
4202
4203
126k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4204
126k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4205
4206
126k
    *num = 0;
4207
126k
    if (bytes > sizeof(*num)) {
4208
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4209
0
        return SECFailure;
4210
0
    }
4211
4212
126k
    if (bytes > *length) {
4213
102
        return ssl3_DecodeError(ss);
4214
102
    }
4215
126k
    PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4216
4217
377k
    for (i = 0; i < bytes; i++) {
4218
250k
        *num = (*num << 8) + buf[i];
4219
250k
    }
4220
126k
    *b += bytes;
4221
126k
    *length -= bytes;
4222
126k
    return SECSuccess;
4223
126k
}
4224
4225
SECStatus
4226
ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRUint32 *num, PRUint32 bytes,
4227
                            PRUint8 **b, PRUint32 *length)
4228
126k
{
4229
126k
    PRUint64 num64;
4230
126k
    SECStatus rv;
4231
4232
126k
    PORT_Assert(bytes <= sizeof(*num));
4233
126k
    if (bytes > sizeof(*num)) {
4234
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4235
0
        return SECFailure;
4236
0
    }
4237
126k
    rv = ssl3_ConsumeHandshakeNumber64(ss, &num64, bytes, b, length);
4238
126k
    if (rv != SECSuccess) {
4239
102
        return SECFailure;
4240
102
    }
4241
126k
    *num = num64 & 0xffffffff;
4242
126k
    return SECSuccess;
4243
126k
}
4244
4245
/* Read in two values from the incoming decrypted byte stream "b", which is
4246
 * *length bytes long.  The first value is a number whose size is "bytes"
4247
 * bytes long.  The second value is a byte-string whose size is the value
4248
 * of the first number received.  The latter byte-string, and its length,
4249
 * is returned in the SECItem i.
4250
 *
4251
 * Returns SECFailure (-1) on failure.
4252
 * On error, an alert has been sent, and a generic error code has been set.
4253
 *
4254
 * RADICAL CHANGE for NSS 3.11.  All callers of this function make copies
4255
 * of the data returned in the SECItem *i, so making a copy of it here
4256
 * is simply wasteful.  So, This function now just sets SECItem *i to
4257
 * point to the values in the buffer **b.
4258
 */
4259
SECStatus
4260
ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRUint32 bytes,
4261
                              PRUint8 **b, PRUint32 *length)
4262
32.0k
{
4263
32.0k
    PRUint32 count;
4264
32.0k
    SECStatus rv;
4265
4266
32.0k
    PORT_Assert(bytes <= 3);
4267
32.0k
    i->len = 0;
4268
32.0k
    i->data = NULL;
4269
32.0k
    i->type = siBuffer;
4270
32.0k
    rv = ssl3_ConsumeHandshakeNumber(ss, &count, bytes, b, length);
4271
32.0k
    if (rv != SECSuccess) {
4272
63
        return SECFailure;
4273
63
    }
4274
31.9k
    if (count > 0) {
4275
19.5k
        if (count > *length) {
4276
118
            return ssl3_DecodeError(ss);
4277
118
        }
4278
19.3k
        i->data = *b;
4279
19.3k
        i->len = count;
4280
19.3k
        *b += count;
4281
19.3k
        *length -= count;
4282
19.3k
    }
4283
31.8k
    return SECSuccess;
4284
31.9k
}
4285
4286
/* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
4287
 * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
4288
 *
4289
 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4290
SECOidTag
4291
ssl3_HashTypeToOID(SSLHashType hashType)
4292
241k
{
4293
241k
    switch (hashType) {
4294
41.9k
        case ssl_hash_sha1:
4295
41.9k
            return SEC_OID_SHA1;
4296
86.8k
        case ssl_hash_sha256:
4297
86.8k
            return SEC_OID_SHA256;
4298
56.5k
        case ssl_hash_sha384:
4299
56.5k
            return SEC_OID_SHA384;
4300
55.6k
        case ssl_hash_sha512:
4301
55.6k
            return SEC_OID_SHA512;
4302
830
        default:
4303
830
            break;
4304
241k
    }
4305
830
    return SEC_OID_UNKNOWN;
4306
241k
}
4307
4308
SECOidTag
4309
ssl3_AuthTypeToOID(SSLAuthType authType)
4310
194k
{
4311
194k
    switch (authType) {
4312
56.4k
        case ssl_auth_rsa_sign:
4313
56.4k
            return SEC_OID_PKCS1_RSA_ENCRYPTION;
4314
3
        case ssl_auth_rsa_pss:
4315
3
            return SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
4316
82.7k
        case ssl_auth_ecdsa:
4317
82.7k
            return SEC_OID_ANSIX962_EC_PUBLIC_KEY;
4318
55.1k
        case ssl_auth_dsa:
4319
55.1k
            return SEC_OID_ANSIX9_DSA_SIGNATURE;
4320
0
        default:
4321
0
            break;
4322
194k
    }
4323
    /* shouldn't ever get there */
4324
0
    PORT_Assert(0);
4325
0
    return SEC_OID_UNKNOWN;
4326
194k
}
4327
4328
SSLHashType
4329
ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme)
4330
236k
{
4331
236k
    switch (scheme) {
4332
14.0k
        case ssl_sig_rsa_pkcs1_sha1:
4333
27.8k
        case ssl_sig_dsa_sha1:
4334
41.8k
        case ssl_sig_ecdsa_sha1:
4335
41.8k
            return ssl_hash_sha1;
4336
14.2k
        case ssl_sig_rsa_pkcs1_sha256:
4337
54.7k
        case ssl_sig_ecdsa_secp256r1_sha256:
4338
69.8k
        case ssl_sig_rsa_pss_rsae_sha256:
4339
69.8k
        case ssl_sig_rsa_pss_pss_sha256:
4340
83.5k
        case ssl_sig_dsa_sha256:
4341
83.5k
            return ssl_hash_sha256;
4342
13.7k
        case ssl_sig_rsa_pkcs1_sha384:
4343
28.2k
        case ssl_sig_ecdsa_secp384r1_sha384:
4344
42.0k
        case ssl_sig_rsa_pss_rsae_sha384:
4345
42.0k
        case ssl_sig_rsa_pss_pss_sha384:
4346
55.8k
        case ssl_sig_dsa_sha384:
4347
55.8k
            return ssl_hash_sha384;
4348
13.8k
        case ssl_sig_rsa_pkcs1_sha512:
4349
27.7k
        case ssl_sig_ecdsa_secp521r1_sha512:
4350
41.6k
        case ssl_sig_rsa_pss_rsae_sha512:
4351
41.7k
        case ssl_sig_rsa_pss_pss_sha512:
4352
55.4k
        case ssl_sig_dsa_sha512:
4353
55.4k
            return ssl_hash_sha512;
4354
0
        case ssl_sig_rsa_pkcs1_sha1md5:
4355
0
            return ssl_hash_none; /* Special for TLS 1.0/1.1. */
4356
0
        case ssl_sig_none:
4357
0
        case ssl_sig_ed25519:
4358
0
        case ssl_sig_ed448:
4359
0
            break;
4360
236k
    }
4361
0
    PORT_Assert(0);
4362
0
    return ssl_hash_none;
4363
236k
}
4364
4365
static PRBool
4366
ssl_SignatureSchemeMatchesSpkiOid(SSLSignatureScheme scheme, SECOidTag spkiOid)
4367
1.31k
{
4368
1.31k
    SECOidTag authOid = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme));
4369
4370
1.31k
    if (spkiOid == authOid) {
4371
1.30k
        return PR_TRUE;
4372
1.30k
    }
4373
8
    if ((authOid == SEC_OID_PKCS1_RSA_ENCRYPTION) &&
4374
8
        (spkiOid == SEC_OID_X500_RSA_ENCRYPTION)) {
4375
0
        return PR_TRUE;
4376
0
    }
4377
8
    return PR_FALSE;
4378
8
}
4379
4380
/* Validate that the signature scheme works for the given key type. */
4381
PRBool
4382
ssl_SignatureSchemeValid(SSLSignatureScheme scheme, SECOidTag spkiOid,
4383
                         PRBool isTls13)
4384
12.0k
{
4385
12.0k
    if (!ssl_IsSupportedSignatureScheme(scheme)) {
4386
10.0k
        return PR_FALSE;
4387
10.0k
    }
4388
    /* if we are purposefully passed SEC_OID_UNKNOWN, it means
4389
     * we not checking the scheme against a potential key, so skip
4390
     * the call */
4391
2.02k
    if ((spkiOid != SEC_OID_UNKNOWN) &&
4392
2.02k
        !ssl_SignatureSchemeMatchesSpkiOid(scheme, spkiOid)) {
4393
8
        return PR_FALSE;
4394
8
    }
4395
2.02k
    if (isTls13) {
4396
0
        if (ssl_SignatureSchemeToHashType(scheme) == ssl_hash_sha1) {
4397
0
            return PR_FALSE;
4398
0
        }
4399
0
        if (ssl_IsRsaPkcs1SignatureScheme(scheme)) {
4400
0
            return PR_FALSE;
4401
0
        }
4402
0
        if (ssl_IsDsaSignatureScheme(scheme)) {
4403
0
            return PR_FALSE;
4404
0
        }
4405
        /* With TLS 1.3, EC keys should have been selected based on calling
4406
         * ssl_SignatureSchemeFromSpki(), reject them otherwise. */
4407
0
        return spkiOid != SEC_OID_ANSIX962_EC_PUBLIC_KEY;
4408
0
    }
4409
2.02k
    return PR_TRUE;
4410
2.02k
}
4411
4412
static SECStatus
4413
ssl_SignatureSchemeFromPssSpki(const CERTSubjectPublicKeyInfo *spki,
4414
                               SSLSignatureScheme *scheme)
4415
2
{
4416
2
    SECKEYRSAPSSParams pssParam = { 0 };
4417
2
    PORTCheapArenaPool arena;
4418
2
    SECStatus rv;
4419
4420
    /* The key doesn't have parameters, boo. */
4421
2
    if (!spki->algorithm.parameters.len) {
4422
0
        *scheme = ssl_sig_none;
4423
0
        return SECSuccess;
4424
0
    }
4425
4426
2
    PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE);
4427
2
    rv = SEC_QuickDERDecodeItem(&arena.arena, &pssParam,
4428
2
                                SEC_ASN1_GET(SECKEY_RSAPSSParamsTemplate),
4429
2
                                &spki->algorithm.parameters);
4430
2
    if (rv != SECSuccess) {
4431
1
        goto loser;
4432
1
    }
4433
    /* Not having hashAlg means SHA-1 and we don't accept that. */
4434
1
    if (!pssParam.hashAlg) {
4435
1
        goto loser;
4436
1
    }
4437
0
    switch (SECOID_GetAlgorithmTag(pssParam.hashAlg)) {
4438
0
        case SEC_OID_SHA256:
4439
0
            *scheme = ssl_sig_rsa_pss_pss_sha256;
4440
0
            break;
4441
0
        case SEC_OID_SHA384:
4442
0
            *scheme = ssl_sig_rsa_pss_pss_sha384;
4443
0
            break;
4444
0
        case SEC_OID_SHA512:
4445
0
            *scheme = ssl_sig_rsa_pss_pss_sha512;
4446
0
            break;
4447
0
        default:
4448
0
            goto loser;
4449
0
    }
4450
4451
0
    PORT_DestroyCheapArena(&arena);
4452
0
    return SECSuccess;
4453
4454
2
loser:
4455
2
    PORT_DestroyCheapArena(&arena);
4456
2
    PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4457
2
    return SECFailure;
4458
0
}
4459
4460
static SECStatus
4461
ssl_SignatureSchemeFromEcSpki(const CERTSubjectPublicKeyInfo *spki,
4462
                              SSLSignatureScheme *scheme)
4463
0
{
4464
0
    const sslNamedGroupDef *group;
4465
0
    SECKEYPublicKey *key;
4466
4467
0
    key = SECKEY_ExtractPublicKey(spki);
4468
0
    if (!key) {
4469
0
        PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4470
0
        return SECFailure;
4471
0
    }
4472
0
    group = ssl_ECPubKey2NamedGroup(key);
4473
0
    SECKEY_DestroyPublicKey(key);
4474
0
    if (!group) {
4475
0
        PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4476
0
        return SECFailure;
4477
0
    }
4478
0
    switch (group->name) {
4479
0
        case ssl_grp_ec_secp256r1:
4480
0
            *scheme = ssl_sig_ecdsa_secp256r1_sha256;
4481
0
            return SECSuccess;
4482
0
        case ssl_grp_ec_secp384r1:
4483
0
            *scheme = ssl_sig_ecdsa_secp384r1_sha384;
4484
0
            return SECSuccess;
4485
0
        case ssl_grp_ec_secp521r1:
4486
0
            *scheme = ssl_sig_ecdsa_secp521r1_sha512;
4487
0
            return SECSuccess;
4488
0
        default:
4489
0
            break;
4490
0
    }
4491
0
    PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4492
0
    return SECFailure;
4493
0
}
4494
4495
/* Newer signature schemes are designed so that a single SPKI can be used with
4496
 * that scheme.  This determines that scheme from the SPKI. If the SPKI doesn't
4497
 * have a single scheme, |*scheme| is set to ssl_sig_none. */
4498
SECStatus
4499
ssl_SignatureSchemeFromSpki(const CERTSubjectPublicKeyInfo *spki,
4500
                            PRBool isTls13, SSLSignatureScheme *scheme)
4501
1.31k
{
4502
1.31k
    SECOidTag spkiOid = SECOID_GetAlgorithmTag(&spki->algorithm);
4503
4504
1.31k
    if (spkiOid == SEC_OID_PKCS1_RSA_PSS_SIGNATURE) {
4505
2
        return ssl_SignatureSchemeFromPssSpki(spki, scheme);
4506
2
    }
4507
4508
    /* Only do this lookup for TLS 1.3, where the scheme can be determined from
4509
     * the SPKI alone because the ECDSA key size determines the hash. Earlier
4510
     * TLS versions allow the same EC key to be used with different hashes. */
4511
1.31k
    if (isTls13 && spkiOid == SEC_OID_ANSIX962_EC_PUBLIC_KEY) {
4512
0
        return ssl_SignatureSchemeFromEcSpki(spki, scheme);
4513
0
    }
4514
4515
1.31k
    *scheme = ssl_sig_none;
4516
1.31k
    return SECSuccess;
4517
1.31k
}
4518
4519
/* Check that a signature scheme is enabled by configuration. */
4520
PRBool
4521
ssl_SignatureSchemeEnabled(const sslSocket *ss, SSLSignatureScheme scheme)
4522
1.30k
{
4523
1.30k
    unsigned int i;
4524
6.73k
    for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
4525
6.73k
        if (scheme == ss->ssl3.signatureSchemes[i]) {
4526
1.30k
            return PR_TRUE;
4527
1.30k
        }
4528
6.73k
    }
4529
0
    return PR_FALSE;
4530
1.30k
}
4531
4532
static PRBool
4533
ssl_SignatureKeyMatchesSpkiOid(const ssl3KEADef *keaDef, SECOidTag spkiOid)
4534
1.31k
{
4535
1.31k
    switch (spkiOid) {
4536
0
        case SEC_OID_X500_RSA_ENCRYPTION:
4537
852
        case SEC_OID_PKCS1_RSA_ENCRYPTION:
4538
852
        case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
4539
852
            return keaDef->signKeyType == rsaKey;
4540
3
        case SEC_OID_ANSIX9_DSA_SIGNATURE:
4541
3
            return keaDef->signKeyType == dsaKey;
4542
458
        case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
4543
458
            return keaDef->signKeyType == ecKey;
4544
1
        default:
4545
1
            break;
4546
1.31k
    }
4547
1
    return PR_FALSE;
4548
1.31k
}
4549
4550
/* ssl3_CheckSignatureSchemeConsistency checks that the signature algorithm
4551
 * identifier in |scheme| is consistent with the public key in |spki|. It also
4552
 * checks the hash algorithm against the configured signature algorithms.  If
4553
 * all the tests pass, SECSuccess is returned. Otherwise, PORT_SetError is
4554
 * called and SECFailure is returned. */
4555
SECStatus
4556
ssl_CheckSignatureSchemeConsistency(sslSocket *ss, SSLSignatureScheme scheme,
4557
                                    CERTSubjectPublicKeyInfo *spki)
4558
1.31k
{
4559
1.31k
    SSLSignatureScheme spkiScheme;
4560
1.31k
    PRBool isTLS13 = ss->version == SSL_LIBRARY_VERSION_TLS_1_3;
4561
1.31k
    SECOidTag spkiOid;
4562
1.31k
    SECStatus rv;
4563
4564
1.31k
    rv = ssl_SignatureSchemeFromSpki(spki, isTLS13, &spkiScheme);
4565
1.31k
    if (rv != SECSuccess) {
4566
2
        return SECFailure;
4567
2
    }
4568
1.31k
    if (spkiScheme != ssl_sig_none) {
4569
        /* The SPKI in the certificate can only be used for a single scheme. */
4570
0
        if (spkiScheme != scheme ||
4571
0
            !ssl_SignatureSchemeEnabled(ss, scheme)) {
4572
0
            PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4573
0
            return SECFailure;
4574
0
        }
4575
0
        return SECSuccess;
4576
0
    }
4577
4578
1.31k
    spkiOid = SECOID_GetAlgorithmTag(&spki->algorithm);
4579
4580
    /* If we're a client, check that the signature algorithm matches the signing
4581
     * key type of the cipher suite. */
4582
1.31k
    if (!isTLS13 && !ss->sec.isServer) {
4583
1.31k
        if (!ssl_SignatureKeyMatchesSpkiOid(ss->ssl3.hs.kea_def, spkiOid)) {
4584
2
            PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4585
2
            return SECFailure;
4586
2
        }
4587
1.31k
    }
4588
4589
    /* Verify that the signature scheme matches the signing key. */
4590
1.31k
    if ((spkiOid == SEC_OID_UNKNOWN) ||
4591
1.31k
        !ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13)) {
4592
8
        PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4593
8
        return SECFailure;
4594
8
    }
4595
4596
1.30k
    if (!ssl_SignatureSchemeEnabled(ss, scheme)) {
4597
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
4598
0
        return SECFailure;
4599
0
    }
4600
4601
1.30k
    return SECSuccess;
4602
1.30k
}
4603
4604
PRBool
4605
ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme)
4606
13.3k
{
4607
13.3k
    switch (scheme) {
4608
251
        case ssl_sig_rsa_pkcs1_sha1:
4609
641
        case ssl_sig_rsa_pkcs1_sha256:
4610
690
        case ssl_sig_rsa_pkcs1_sha384:
4611
773
        case ssl_sig_rsa_pkcs1_sha512:
4612
1.67k
        case ssl_sig_rsa_pss_rsae_sha256:
4613
1.71k
        case ssl_sig_rsa_pss_rsae_sha384:
4614
1.87k
        case ssl_sig_rsa_pss_rsae_sha512:
4615
1.89k
        case ssl_sig_rsa_pss_pss_sha256:
4616
1.91k
        case ssl_sig_rsa_pss_pss_sha384:
4617
1.96k
        case ssl_sig_rsa_pss_pss_sha512:
4618
2.23k
        case ssl_sig_ecdsa_secp256r1_sha256:
4619
2.76k
        case ssl_sig_ecdsa_secp384r1_sha384:
4620
2.92k
        case ssl_sig_ecdsa_secp521r1_sha512:
4621
3.04k
        case ssl_sig_dsa_sha1:
4622
3.09k
        case ssl_sig_dsa_sha256:
4623
3.14k
        case ssl_sig_dsa_sha384:
4624
3.18k
        case ssl_sig_dsa_sha512:
4625
3.34k
        case ssl_sig_ecdsa_sha1:
4626
3.34k
            return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy);
4627
0
            break;
4628
4629
0
        case ssl_sig_rsa_pkcs1_sha1md5:
4630
488
        case ssl_sig_none:
4631
493
        case ssl_sig_ed25519:
4632
765
        case ssl_sig_ed448:
4633
765
            return PR_FALSE;
4634
13.3k
    }
4635
9.28k
    return PR_FALSE;
4636
13.3k
}
4637
4638
PRBool
4639
ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme)
4640
469k
{
4641
469k
    switch (scheme) {
4642
28.7k
        case ssl_sig_rsa_pss_rsae_sha256:
4643
56.2k
        case ssl_sig_rsa_pss_rsae_sha384:
4644
83.8k
        case ssl_sig_rsa_pss_rsae_sha512:
4645
83.9k
        case ssl_sig_rsa_pss_pss_sha256:
4646
83.9k
        case ssl_sig_rsa_pss_pss_sha384:
4647
83.9k
        case ssl_sig_rsa_pss_pss_sha512:
4648
83.9k
            return PR_TRUE;
4649
4650
385k
        default:
4651
385k
            return PR_FALSE;
4652
469k
    }
4653
0
    return PR_FALSE;
4654
469k
}
4655
4656
PRBool
4657
ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme)
4658
0
{
4659
0
    switch (scheme) {
4660
0
        case ssl_sig_rsa_pss_rsae_sha256:
4661
0
        case ssl_sig_rsa_pss_rsae_sha384:
4662
0
        case ssl_sig_rsa_pss_rsae_sha512:
4663
0
            return PR_TRUE;
4664
4665
0
        default:
4666
0
            return PR_FALSE;
4667
0
    }
4668
0
    return PR_FALSE;
4669
0
}
4670
4671
PRBool
4672
ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme)
4673
26.3k
{
4674
26.3k
    switch (scheme) {
4675
0
        case ssl_sig_rsa_pkcs1_sha256:
4676
0
        case ssl_sig_rsa_pkcs1_sha384:
4677
0
        case ssl_sig_rsa_pkcs1_sha512:
4678
0
        case ssl_sig_rsa_pkcs1_sha1:
4679
0
            return PR_TRUE;
4680
4681
26.3k
        default:
4682
26.3k
            return PR_FALSE;
4683
26.3k
    }
4684
0
    return PR_FALSE;
4685
26.3k
}
4686
4687
PRBool
4688
ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme)
4689
190k
{
4690
190k
    switch (scheme) {
4691
13.7k
        case ssl_sig_dsa_sha256:
4692
27.4k
        case ssl_sig_dsa_sha384:
4693
41.1k
        case ssl_sig_dsa_sha512:
4694
54.8k
        case ssl_sig_dsa_sha1:
4695
54.8k
            return PR_TRUE;
4696
4697
136k
        default:
4698
136k
            return PR_FALSE;
4699
190k
    }
4700
0
    return PR_FALSE;
4701
190k
}
4702
4703
SSLAuthType
4704
ssl_SignatureSchemeToAuthType(SSLSignatureScheme scheme)
4705
196k
{
4706
196k
    switch (scheme) {
4707
14.1k
        case ssl_sig_rsa_pkcs1_sha1:
4708
14.7k
        case ssl_sig_rsa_pkcs1_sha1md5:
4709
29.2k
        case ssl_sig_rsa_pkcs1_sha256:
4710
43.0k
        case ssl_sig_rsa_pkcs1_sha384:
4711
56.8k
        case ssl_sig_rsa_pkcs1_sha512:
4712
        /* We report based on the key type for PSS signatures. */
4713
57.7k
        case ssl_sig_rsa_pss_rsae_sha256:
4714
57.7k
        case ssl_sig_rsa_pss_rsae_sha384:
4715
57.9k
        case ssl_sig_rsa_pss_rsae_sha512:
4716
57.9k
            return ssl_auth_rsa_sign;
4717
1
        case ssl_sig_rsa_pss_pss_sha256:
4718
2
        case ssl_sig_rsa_pss_pss_sha384:
4719
3
        case ssl_sig_rsa_pss_pss_sha512:
4720
3
            return ssl_auth_rsa_pss;
4721
40.5k
        case ssl_sig_ecdsa_secp256r1_sha256:
4722
55.3k
        case ssl_sig_ecdsa_secp384r1_sha384:
4723
69.2k
        case ssl_sig_ecdsa_secp521r1_sha512:
4724
83.4k
        case ssl_sig_ecdsa_sha1:
4725
83.4k
            return ssl_auth_ecdsa;
4726
13.8k
        case ssl_sig_dsa_sha1:
4727
27.5k
        case ssl_sig_dsa_sha256:
4728
41.3k
        case ssl_sig_dsa_sha384:
4729
55.1k
        case ssl_sig_dsa_sha512:
4730
55.1k
            return ssl_auth_dsa;
4731
4732
0
        default:
4733
0
            PORT_Assert(0);
4734
196k
    }
4735
0
    return ssl_auth_null;
4736
196k
}
4737
4738
/* ssl_ConsumeSignatureScheme reads a SSLSignatureScheme (formerly
4739
 * SignatureAndHashAlgorithm) structure from |b| and puts the resulting value
4740
 * into |out|. |b| and |length| are updated accordingly.
4741
 *
4742
 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4743
SECStatus
4744
ssl_ConsumeSignatureScheme(sslSocket *ss, PRUint8 **b,
4745
                           PRUint32 *length, SSLSignatureScheme *out)
4746
1.31k
{
4747
1.31k
    PRUint32 tmp;
4748
1.31k
    SECStatus rv;
4749
4750
1.31k
    rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
4751
1.31k
    if (rv != SECSuccess) {
4752
1
        return SECFailure; /* Alert sent, Error code set already. */
4753
1
    }
4754
1.31k
    if (!ssl_IsSupportedSignatureScheme((SSLSignatureScheme)tmp)) {
4755
1
        SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
4756
1
        PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
4757
1
        return SECFailure;
4758
1
    }
4759
1.31k
    *out = (SSLSignatureScheme)tmp;
4760
1.31k
    return SECSuccess;
4761
1.31k
}
4762
4763
/**************************************************************************
4764
 * end of Consume Handshake functions.
4765
 **************************************************************************/
4766
4767
static SECStatus
4768
ssl3_ComputeHandshakeHash(unsigned char *buf, unsigned int len,
4769
                          SSLHashType hashAlg, SSL3Hashes *hashes)
4770
2.94k
{
4771
2.94k
    SECStatus rv = SECFailure;
4772
2.94k
    PK11Context *hashContext = PK11_CreateDigestContext(
4773
2.94k
        ssl3_HashTypeToOID(hashAlg));
4774
4775
2.94k
    if (!hashContext) {
4776
0
        return rv;
4777
0
    }
4778
2.94k
    rv = PK11_DigestBegin(hashContext);
4779
2.94k
    if (rv == SECSuccess) {
4780
2.94k
        rv = PK11_DigestOp(hashContext, buf, len);
4781
2.94k
    }
4782
2.94k
    if (rv == SECSuccess) {
4783
2.94k
        rv = PK11_DigestFinal(hashContext, hashes->u.raw, &hashes->len,
4784
2.94k
                              sizeof(hashes->u.raw));
4785
2.94k
    }
4786
2.94k
    if (rv == SECSuccess) {
4787
2.94k
        hashes->hashAlg = hashAlg;
4788
2.94k
    }
4789
2.94k
    PK11_DestroyContext(hashContext, PR_TRUE);
4790
2.94k
    return rv;
4791
2.94k
}
4792
4793
/* Extract the hashes of handshake messages to this point.
4794
 * Called from ssl3_SendCertificateVerify
4795
 *             ssl3_SendFinished
4796
 *             ssl3_HandleHandshakeMessage
4797
 *
4798
 * Caller must hold the SSL3HandshakeLock.
4799
 * Caller must hold a read or write lock on the Spec R/W lock.
4800
 *  (There is presently no way to assert on a Read lock.)
4801
 */
4802
SECStatus
4803
ssl3_ComputeHandshakeHashes(sslSocket *ss,
4804
                            ssl3CipherSpec *spec, /* uses ->master_secret */
4805
                            SSL3Hashes *hashes,   /* output goes here. */
4806
                            PRUint32 sender)
4807
8.92k
{
4808
8.92k
    SECStatus rv = SECSuccess;
4809
8.92k
    PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
4810
8.92k
    unsigned int outLength;
4811
8.92k
    PRUint8 md5_inner[MAX_MAC_LENGTH];
4812
8.92k
    PRUint8 sha_inner[MAX_MAC_LENGTH];
4813
4814
8.92k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4815
8.92k
    if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
4816
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4817
0
        return SECFailure;
4818
0
    }
4819
4820
8.92k
    hashes->hashAlg = ssl_hash_none;
4821
4822
8.92k
    if (ss->ssl3.hs.hashType == handshake_hash_single) {
4823
0
        PK11Context *h;
4824
0
        unsigned int stateLen;
4825
0
        unsigned char stackBuf[1024];
4826
0
        unsigned char *stateBuf = NULL;
4827
4828
0
        h = ss->ssl3.hs.sha;
4829
0
        stateBuf = PK11_SaveContextAlloc(h, stackBuf,
4830
0
                                         sizeof(stackBuf), &stateLen);
4831
0
        if (stateBuf == NULL) {
4832
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4833
0
            rv = SECFailure;
4834
0
            goto tls12_loser;
4835
0
        }
4836
0
        rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
4837
0
                               sizeof(hashes->u.raw));
4838
0
        if (rv != SECSuccess) {
4839
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4840
0
            rv = SECFailure;
4841
0
            goto tls12_loser;
4842
0
        }
4843
4844
0
        hashes->hashAlg = ssl3_GetSuitePrfHash(ss);
4845
4846
0
    tls12_loser:
4847
0
        if (stateBuf) {
4848
0
            if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
4849
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4850
0
                rv = SECFailure;
4851
0
            }
4852
0
            if (stateBuf != stackBuf) {
4853
0
                PORT_ZFree(stateBuf, stateLen);
4854
0
            }
4855
0
        }
4856
8.92k
    } else if (ss->ssl3.hs.hashType == handshake_hash_record) {
4857
2.94k
        rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
4858
2.94k
                                       ss->ssl3.hs.messages.len,
4859
2.94k
                                       ssl3_GetSuitePrfHash(ss),
4860
2.94k
                                       hashes);
4861
5.98k
    } else {
4862
5.98k
        PK11Context *md5;
4863
5.98k
        PK11Context *sha = NULL;
4864
5.98k
        unsigned char *md5StateBuf = NULL;
4865
5.98k
        unsigned char *shaStateBuf = NULL;
4866
5.98k
        unsigned int md5StateLen, shaStateLen;
4867
5.98k
        unsigned char md5StackBuf[256];
4868
5.98k
        unsigned char shaStackBuf[512];
4869
5.98k
        const int md5Pad = ssl_GetMacDefByAlg(ssl_mac_md5)->pad_size;
4870
5.98k
        const int shaPad = ssl_GetMacDefByAlg(ssl_mac_sha)->pad_size;
4871
4872
5.98k
        md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
4873
5.98k
                                            sizeof md5StackBuf, &md5StateLen);
4874
5.98k
        if (md5StateBuf == NULL) {
4875
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4876
0
            rv = SECFailure;
4877
0
            goto loser;
4878
0
        }
4879
5.98k
        md5 = ss->ssl3.hs.md5;
4880
4881
5.98k
        shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
4882
5.98k
                                            sizeof shaStackBuf, &shaStateLen);
4883
5.98k
        if (shaStateBuf == NULL) {
4884
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4885
0
            rv = SECFailure;
4886
0
            goto loser;
4887
0
        }
4888
5.98k
        sha = ss->ssl3.hs.sha;
4889
4890
5.98k
        if (!isTLS) {
4891
            /* compute hashes for SSL3. */
4892
0
            unsigned char s[4];
4893
4894
0
            if (!spec->masterSecret) {
4895
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4896
0
                rv = SECFailure;
4897
0
                goto loser;
4898
0
            }
4899
4900
0
            s[0] = (unsigned char)(sender >> 24);
4901
0
            s[1] = (unsigned char)(sender >> 16);
4902
0
            s[2] = (unsigned char)(sender >> 8);
4903
0
            s[3] = (unsigned char)sender;
4904
4905
0
            if (sender != 0) {
4906
0
                rv |= PK11_DigestOp(md5, s, 4);
4907
0
                PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
4908
0
            }
4909
4910
0
            PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, md5Pad));
4911
4912
0
            rv |= PK11_DigestKey(md5, spec->masterSecret);
4913
0
            rv |= PK11_DigestOp(md5, mac_pad_1, md5Pad);
4914
0
            rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
4915
0
            PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4916
0
            if (rv != SECSuccess) {
4917
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4918
0
                rv = SECFailure;
4919
0
                goto loser;
4920
0
            }
4921
4922
0
            PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
4923
4924
0
            if (sender != 0) {
4925
0
                rv |= PK11_DigestOp(sha, s, 4);
4926
0
                PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
4927
0
            }
4928
4929
0
            PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, shaPad));
4930
4931
0
            rv |= PK11_DigestKey(sha, spec->masterSecret);
4932
0
            rv |= PK11_DigestOp(sha, mac_pad_1, shaPad);
4933
0
            rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
4934
0
            PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4935
0
            if (rv != SECSuccess) {
4936
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4937
0
                rv = SECFailure;
4938
0
                goto loser;
4939
0
            }
4940
4941
0
            PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
4942
4943
0
            PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, md5Pad));
4944
0
            PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
4945
4946
0
            rv |= PK11_DigestBegin(md5);
4947
0
            rv |= PK11_DigestKey(md5, spec->masterSecret);
4948
0
            rv |= PK11_DigestOp(md5, mac_pad_2, md5Pad);
4949
0
            rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
4950
0
        }
4951
5.98k
        rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH);
4952
5.98k
        PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4953
5.98k
        if (rv != SECSuccess) {
4954
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4955
0
            rv = SECFailure;
4956
0
            goto loser;
4957
0
        }
4958
4959
5.98k
        PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
4960
4961
5.98k
        if (!isTLS) {
4962
0
            PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, shaPad));
4963
0
            PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
4964
4965
0
            rv |= PK11_DigestBegin(sha);
4966
0
            rv |= PK11_DigestKey(sha, spec->masterSecret);
4967
0
            rv |= PK11_DigestOp(sha, mac_pad_2, shaPad);
4968
0
            rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
4969
0
        }
4970
5.98k
        rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH);
4971
5.98k
        PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4972
5.98k
        if (rv != SECSuccess) {
4973
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4974
0
            rv = SECFailure;
4975
0
            goto loser;
4976
0
        }
4977
4978
5.98k
        PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
4979
4980
5.98k
        hashes->len = MD5_LENGTH + SHA1_LENGTH;
4981
4982
5.98k
    loser:
4983
5.98k
        if (md5StateBuf) {
4984
5.98k
            if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) !=
4985
5.98k
                SECSuccess) {
4986
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4987
0
                rv = SECFailure;
4988
0
            }
4989
5.98k
            if (md5StateBuf != md5StackBuf) {
4990
0
                PORT_ZFree(md5StateBuf, md5StateLen);
4991
0
            }
4992
5.98k
        }
4993
5.98k
        if (shaStateBuf) {
4994
5.98k
            if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) !=
4995
5.98k
                SECSuccess) {
4996
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4997
0
                rv = SECFailure;
4998
0
            }
4999
5.98k
            if (shaStateBuf != shaStackBuf) {
5000
0
                PORT_ZFree(shaStateBuf, shaStateLen);
5001
0
            }
5002
5.98k
        }
5003
5.98k
    }
5004
8.92k
    return rv;
5005
8.92k
}
5006
5007
/**************************************************************************
5008
 * end of Handshake Hash functions.
5009
 * Begin Send and Handle functions for handshakes.
5010
 **************************************************************************/
5011
5012
#ifdef TRACE
5013
#define CHTYPE(t)          \
5014
0
    case client_hello_##t: \
5015
0
        return #t;
5016
5017
static const char *
5018
ssl_ClientHelloTypeName(sslClientHelloType type)
5019
0
{
5020
0
    switch (type) {
5021
0
        CHTYPE(initial);
5022
0
        CHTYPE(retry);
5023
0
        CHTYPE(retransmit);    /* DTLS only */
5024
0
        CHTYPE(renegotiation); /* TLS <= 1.2 only */
5025
0
    }
5026
0
    PORT_Assert(0);
5027
0
    return NULL;
5028
0
}
5029
#undef CHTYPE
5030
#endif
5031
5032
PR_STATIC_ASSERT(SSL3_SESSIONID_BYTES == SSL3_RANDOM_LENGTH);
5033
static void
5034
ssl_MakeFakeSid(sslSocket *ss, PRUint8 *buf)
5035
0
{
5036
0
    PRUint8 x = 0x5a;
5037
0
    int i;
5038
0
    for (i = 0; i < SSL3_SESSIONID_BYTES; ++i) {
5039
0
        x += ss->ssl3.hs.client_random[i];
5040
0
        buf[i] = x;
5041
0
    }
5042
0
}
5043
5044
/* Set the version fields of the cipher spec for a ClientHello. */
5045
static void
5046
ssl_SetClientHelloSpecVersion(sslSocket *ss, ssl3CipherSpec *spec)
5047
9.52k
{
5048
9.52k
    ssl_GetSpecWriteLock(ss);
5049
9.52k
    PORT_Assert(spec->cipherDef->cipher == cipher_null);
5050
    /* This is - a best guess - but it doesn't matter here. */
5051
9.52k
    spec->version = ss->vrange.max;
5052
9.52k
    if (IS_DTLS(ss)) {
5053
0
        spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_0_WIRE;
5054
9.52k
    } else {
5055
        /* For new connections, cap the record layer version number of TLS
5056
         * ClientHello to { 3, 1 } (TLS 1.0). Some TLS 1.0 servers (which seem
5057
         * to use F5 BIG-IP) ignore ClientHello.client_version and use the
5058
         * record layer version number (TLSPlaintext.version) instead when
5059
         * negotiating protocol versions. In addition, if the record layer
5060
         * version number of ClientHello is { 3, 2 } (TLS 1.1) or higher, these
5061
         * servers reset the TCP connections. Lastly, some F5 BIG-IP servers
5062
         * hang if a record containing a ClientHello has a version greater than
5063
         * { 3, 1 } and a length greater than 255. Set this flag to work around
5064
         * such servers.
5065
         *
5066
         * The final version is set when a version is negotiated.
5067
         */
5068
9.52k
        spec->recordVersion = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0,
5069
9.52k
                                     ss->vrange.max);
5070
9.52k
    }
5071
9.52k
    ssl_ReleaseSpecWriteLock(ss);
5072
9.52k
}
5073
5074
SECStatus
5075
ssl3_InsertChHeaderSize(const sslSocket *ss, sslBuffer *preamble, const sslBuffer *extensions)
5076
27.4k
{
5077
27.4k
    SECStatus rv;
5078
27.4k
    unsigned int msgLen = preamble->len;
5079
27.4k
    msgLen += extensions->len ? (2 + extensions->len) : 0;
5080
27.4k
    unsigned int headerLen = IS_DTLS(ss) ? 12 : 4;
5081
5082
    /* Record the message length. */
5083
27.4k
    rv = sslBuffer_InsertNumber(preamble, 1, msgLen - headerLen, 3);
5084
27.4k
    if (rv != SECSuccess) {
5085
0
        return SECFailure; /* code set */
5086
0
    }
5087
27.4k
    if (IS_DTLS(ss)) {
5088
        /* Record the (unfragmented) fragment length. */
5089
0
        unsigned int offset = 1 /* ch */ + 3 /* len */ +
5090
0
                              2 /* seq */ + 3 /* fragment offset */;
5091
0
        rv = sslBuffer_InsertNumber(preamble, offset, msgLen - headerLen, 3);
5092
0
        if (rv != SECSuccess) {
5093
0
            return SECFailure; /* code set */
5094
0
        }
5095
0
    }
5096
5097
27.4k
    return SECSuccess;
5098
27.4k
}
5099
5100
static SECStatus
5101
ssl3_AppendCipherSuites(sslSocket *ss, PRBool fallbackSCSV, sslBuffer *buf)
5102
13.7k
{
5103
13.7k
    SECStatus rv;
5104
13.7k
    unsigned int offset;
5105
13.7k
    unsigned int i;
5106
13.7k
    unsigned int saveLen;
5107
5108
13.7k
    rv = sslBuffer_Skip(buf, 2, &offset);
5109
13.7k
    if (rv != SECSuccess) {
5110
0
        return SECFailure;
5111
0
    }
5112
5113
13.7k
    if (ss->ssl3.hs.sendingSCSV) {
5114
        /* Add the actual SCSV */
5115
0
        rv = sslBuffer_AppendNumber(buf, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
5116
0
                                    sizeof(ssl3CipherSuite));
5117
0
        if (rv != SECSuccess) {
5118
0
            return SECFailure;
5119
0
        }
5120
0
    }
5121
13.7k
    if (fallbackSCSV) {
5122
0
        rv = sslBuffer_AppendNumber(buf, TLS_FALLBACK_SCSV,
5123
0
                                    sizeof(ssl3CipherSuite));
5124
0
        if (rv != SECSuccess) {
5125
0
            return SECFailure;
5126
0
        }
5127
0
    }
5128
5129
13.7k
    saveLen = SSL_BUFFER_LEN(buf);
5130
    /* CipherSuites are appended to Hello message here */
5131
987k
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
5132
973k
        ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
5133
973k
        if (ssl3_config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) {
5134
973k
            rv = sslBuffer_AppendNumber(buf, suite->cipher_suite,
5135
973k
                                        sizeof(ssl3CipherSuite));
5136
973k
            if (rv != SECSuccess) {
5137
0
                return SECFailure;
5138
0
            }
5139
973k
        }
5140
973k
    }
5141
5142
    /* GREASE CipherSuites:
5143
     * A client MAY select one or more GREASE cipher suite values and advertise
5144
     * them in the "cipher_suites" field [RFC8701, Section 3.1]. */
5145
13.7k
    if (ss->opt.enableGrease && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
5146
0
        rv = sslBuffer_AppendNumber(buf, ss->ssl3.hs.grease->idx[grease_cipher],
5147
0
                                    sizeof(ssl3CipherSuite));
5148
0
        if (rv != SECSuccess) {
5149
0
            return SECFailure;
5150
0
        }
5151
0
    }
5152
5153
13.7k
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange) ||
5154
13.7k
        (SSL_BUFFER_LEN(buf) - saveLen) == 0) {
5155
0
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
5156
0
        return SECFailure;
5157
0
    }
5158
5159
13.7k
    return sslBuffer_InsertLength(buf, offset, 2);
5160
13.7k
}
5161
5162
SECStatus
5163
ssl3_CreateClientHelloPreamble(sslSocket *ss, const sslSessionID *sid,
5164
                               PRBool realSid, PRUint16 version, PRBool isEchInner,
5165
                               const sslBuffer *extensions, sslBuffer *preamble)
5166
13.7k
{
5167
13.7k
    SECStatus rv;
5168
13.7k
    sslBuffer constructed = SSL_BUFFER_EMPTY;
5169
13.7k
    const PRUint8 *client_random = isEchInner ? ss->ssl3.hs.client_inner_random : ss->ssl3.hs.client_random;
5170
13.7k
    PORT_Assert(sid);
5171
13.7k
    PRBool fallbackSCSV = ss->opt.enableFallbackSCSV && !isEchInner &&
5172
13.7k
                          (!realSid || version < sid->version);
5173
5174
13.7k
    rv = sslBuffer_AppendNumber(&constructed, ssl_hs_client_hello, 1);
5175
13.7k
    if (rv != SECSuccess) {
5176
0
        goto loser;
5177
0
    }
5178
5179
13.7k
    rv = sslBuffer_Skip(&constructed, 3, NULL);
5180
13.7k
    if (rv != SECSuccess) {
5181
0
        goto loser;
5182
0
    }
5183
5184
13.7k
    if (IS_DTLS(ss)) {
5185
        /* Note that we make an unfragmented message here. We fragment in the
5186
         * transmission code, if necessary */
5187
0
        rv = sslBuffer_AppendNumber(&constructed, ss->ssl3.hs.sendMessageSeq, 2);
5188
0
        if (rv != SECSuccess) {
5189
0
            goto loser;
5190
0
        }
5191
0
        ss->ssl3.hs.sendMessageSeq++;
5192
5193
        /* 0 is the fragment offset, because it's not fragmented yet */
5194
0
        rv = sslBuffer_AppendNumber(&constructed, 0, 3);
5195
0
        if (rv != SECSuccess) {
5196
0
            goto loser;
5197
0
        }
5198
5199
        /* Fragment length -- set to the packet length because not fragmented */
5200
0
        rv = sslBuffer_Skip(&constructed, 3, NULL);
5201
0
        if (rv != SECSuccess) {
5202
0
            goto loser;
5203
0
        }
5204
0
    }
5205
5206
13.7k
    if (ss->firstHsDone) {
5207
        /* The client hello version must stay unchanged to work around
5208
         * the Windows SChannel bug described in ssl3_SendClientHello. */
5209
4.13k
        PORT_Assert(version == ss->clientHelloVersion);
5210
4.13k
    }
5211
5212
13.7k
    ss->clientHelloVersion = PR_MIN(version, SSL_LIBRARY_VERSION_TLS_1_2);
5213
13.7k
    if (IS_DTLS(ss)) {
5214
0
        PRUint16 dtlsVersion = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
5215
0
        rv = sslBuffer_AppendNumber(&constructed, dtlsVersion, 2);
5216
13.7k
    } else {
5217
13.7k
        rv = sslBuffer_AppendNumber(&constructed, ss->clientHelloVersion, 2);
5218
13.7k
    }
5219
13.7k
    if (rv != SECSuccess) {
5220
0
        goto loser;
5221
0
    }
5222
5223
13.7k
    rv = sslBuffer_Append(&constructed, client_random, SSL3_RANDOM_LENGTH);
5224
13.7k
    if (rv != SECSuccess) {
5225
0
        goto loser;
5226
0
    }
5227
5228
13.7k
    if (sid->version < SSL_LIBRARY_VERSION_TLS_1_3 && !isEchInner) {
5229
4.13k
        rv = sslBuffer_AppendVariable(&constructed, sid->u.ssl3.sessionID,
5230
4.13k
                                      sid->u.ssl3.sessionIDLength, 1);
5231
9.57k
    } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) {
5232
        /* We're faking session resumption, so rather than create new
5233
         * randomness, just mix up the client random a little. */
5234
0
        PRUint8 buf[SSL3_SESSIONID_BYTES];
5235
0
        ssl_MakeFakeSid(ss, buf);
5236
0
        rv = sslBuffer_AppendVariable(&constructed, buf, SSL3_SESSIONID_BYTES, 1);
5237
9.57k
    } else {
5238
9.57k
        rv = sslBuffer_AppendNumber(&constructed, 0, 1);
5239
9.57k
    }
5240
13.7k
    if (rv != SECSuccess) {
5241
0
        goto loser;
5242
0
    }
5243
5244
13.7k
    if (IS_DTLS(ss)) {
5245
        /* This cookieLen applies to the cookie that appears in the DTLS
5246
         * ClientHello, which isn't used in DTLS 1.3. */
5247
0
        rv = sslBuffer_AppendVariable(&constructed, ss->ssl3.hs.cookie.data,
5248
0
                                      ss->ssl3.hs.helloRetry ? 0 : ss->ssl3.hs.cookie.len,
5249
0
                                      1);
5250
0
        if (rv != SECSuccess) {
5251
0
            goto loser;
5252
0
        }
5253
0
    }
5254
5255
13.7k
    rv = ssl3_AppendCipherSuites(ss, fallbackSCSV, &constructed);
5256
13.7k
    if (rv != SECSuccess) {
5257
0
        goto loser;
5258
0
    }
5259
5260
    /* Compression methods: count is always 1, null compression. */
5261
13.7k
    rv = sslBuffer_AppendNumber(&constructed, 1, 1);
5262
13.7k
    if (rv != SECSuccess) {
5263
0
        goto loser;
5264
0
    }
5265
13.7k
    rv = sslBuffer_AppendNumber(&constructed, ssl_compression_null, 1);
5266
13.7k
    if (rv != SECSuccess) {
5267
0
        goto loser;
5268
0
    }
5269
5270
13.7k
    rv = ssl3_InsertChHeaderSize(ss, &constructed, extensions);
5271
13.7k
    if (rv != SECSuccess) {
5272
0
        goto loser;
5273
0
    }
5274
5275
13.7k
    *preamble = constructed;
5276
13.7k
    return SECSuccess;
5277
0
loser:
5278
0
    sslBuffer_Clear(&constructed);
5279
0
    return SECFailure;
5280
13.7k
}
5281
5282
/* Called from ssl3_HandleHelloRequest(),
5283
 *             ssl3_RedoHandshake()
5284
 *             ssl_BeginClientHandshake (when resuming ssl3 session)
5285
 *             dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
5286
 *
5287
 * The |type| argument indicates what is going on here:
5288
 * - client_hello_initial is set for the very first ClientHello
5289
 * - client_hello_retry indicates that this is a second attempt after receiving
5290
 *   a HelloRetryRequest (in TLS 1.3)
5291
 * - client_hello_retransmit is used in DTLS when resending
5292
 * - client_hello_renegotiation is used to renegotiate (in TLS <1.3)
5293
 */
5294
SECStatus
5295
ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type)
5296
13.7k
{
5297
13.7k
    sslSessionID *sid;
5298
13.7k
    SECStatus rv;
5299
13.7k
    PRBool isTLS = PR_FALSE;
5300
13.7k
    PRBool requestingResume = PR_FALSE;
5301
13.7k
    PRBool unlockNeeded = PR_FALSE;
5302
13.7k
    sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
5303
13.7k
    PRUint16 version = ss->vrange.max;
5304
13.7k
    PRInt32 flags;
5305
13.7k
    sslBuffer chBuf = SSL_BUFFER_EMPTY;
5306
5307
13.7k
    SSL_TRC(3, ("%d: SSL3[%d]: send %s ClientHello handshake", SSL_GETPID(),
5308
13.7k
                ss->fd, ssl_ClientHelloTypeName(type)));
5309
5310
13.7k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5311
13.7k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5312
5313
    /* shouldn't get here if SSL3 is disabled, but ... */
5314
13.7k
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
5315
0
        PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
5316
0
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
5317
0
        return SECFailure;
5318
0
    }
5319
5320
    /* If we are responding to a HelloRetryRequest, don't reinitialize. We need
5321
     * to maintain the handshake hashes. */
5322
13.7k
    if (!ss->ssl3.hs.helloRetry) {
5323
13.6k
        ssl3_RestartHandshakeHashes(ss);
5324
13.6k
    }
5325
13.7k
    PORT_Assert(!ss->ssl3.hs.helloRetry || type == client_hello_retry);
5326
5327
13.7k
    if (type == client_hello_initial) {
5328
9.52k
        ssl_SetClientHelloSpecVersion(ss, ss->ssl3.cwSpec);
5329
9.52k
    }
5330
    /* These must be reset every handshake. */
5331
13.7k
    ssl3_ResetExtensionData(&ss->xtnData, ss);
5332
13.7k
    ss->ssl3.hs.sendingSCSV = PR_FALSE;
5333
13.7k
    ss->ssl3.hs.preliminaryInfo = 0;
5334
13.7k
    PORT_Assert(IS_DTLS(ss) || type != client_hello_retransmit);
5335
13.7k
    SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
5336
13.7k
    ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
5337
5338
    /* How many suites does our PKCS11 support (regardless of policy)? */
5339
13.7k
    if (ssl3_config_match_init(ss) == 0) {
5340
0
        return SECFailure; /* ssl3_config_match_init has set error code. */
5341
0
    }
5342
5343
    /*
5344
     * During a renegotiation, ss->clientHelloVersion will be used again to
5345
     * work around a Windows SChannel bug. Ensure that it is still enabled.
5346
     */
5347
13.7k
    if (ss->firstHsDone) {
5348
4.13k
        PORT_Assert(type != client_hello_initial);
5349
4.13k
        if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
5350
0
            PORT_SetError(SSL_ERROR_SSL_DISABLED);
5351
0
            return SECFailure;
5352
0
        }
5353
5354
4.13k
        if (ss->clientHelloVersion < ss->vrange.min ||
5355
4.13k
            ss->clientHelloVersion > ss->vrange.max) {
5356
0
            PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
5357
0
            return SECFailure;
5358
0
        }
5359
4.13k
    }
5360
5361
    /* Check if we have a ss->sec.ci.sid.
5362
     * Check that it's not expired.
5363
     * If we have an sid and it comes from an external cache, we use it. */
5364
13.7k
    if (ss->sec.ci.sid && ss->sec.ci.sid->cached == in_external_cache) {
5365
0
        PORT_Assert(!ss->sec.isServer);
5366
0
        sid = ssl_ReferenceSID(ss->sec.ci.sid);
5367
0
        SSL_TRC(3, ("%d: SSL3[%d]: using external resumption token in ClientHello",
5368
0
                    SSL_GETPID(), ss->fd));
5369
13.7k
    } else if (ss->sec.ci.sid && ss->statelessResume && type == client_hello_retry) {
5370
        /* If we are sending a second ClientHello, reuse the same SID
5371
         * as the original one. */
5372
0
        sid = ssl_ReferenceSID(ss->sec.ci.sid);
5373
13.7k
    } else if (!ss->opt.noCache) {
5374
        /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
5375
         * handles expired entries and other details.
5376
         * XXX If we've been called from ssl_BeginClientHandshake, then
5377
         * this lookup is duplicative and wasteful.
5378
         */
5379
6.30k
        sid = ssl_LookupSID(ssl_Time(ss), &ss->sec.ci.peer,
5380
6.30k
                            ss->sec.ci.port, ss->peerID, ss->url);
5381
7.40k
    } else {
5382
7.40k
        sid = NULL;
5383
7.40k
    }
5384
5385
    /* We can't resume based on a different token. If the sid exists,
5386
     * make sure the token that holds the master secret still exists ...
5387
     * If we previously did client-auth, make sure that the token that holds
5388
     * the private key still exists, is logged in, hasn't been removed, etc.
5389
     */
5390
13.7k
    if (sid) {
5391
0
        PRBool sidOK = PR_TRUE;
5392
5393
0
        if (sid->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
5394
0
            if (!tls13_ResumptionCompatible(ss, sid->u.ssl3.cipherSuite)) {
5395
0
                sidOK = PR_FALSE;
5396
0
            }
5397
0
        } else {
5398
            /* Check that the cipher suite we need is enabled. */
5399
0
            const ssl3CipherSuiteCfg *suite =
5400
0
                ssl_LookupCipherSuiteCfg(sid->u.ssl3.cipherSuite,
5401
0
                                         ss->cipherSuites);
5402
0
            SSLVersionRange vrange = { sid->version, sid->version };
5403
0
            if (!suite || !ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
5404
0
                sidOK = PR_FALSE;
5405
0
            }
5406
5407
            /* Check that no (valid) ECHConfigs are setup in combination with a
5408
             * (resumable) TLS < 1.3 session id. */
5409
0
            if (!PR_CLIST_IS_EMPTY(&ss->echConfigs)) {
5410
                /* If there are ECH configs, the client must not resume but
5411
                 * offer ECH. */
5412
0
                sidOK = PR_FALSE;
5413
0
            }
5414
0
        }
5415
5416
        /* Check that we can recover the master secret. */
5417
0
        if (sidOK) {
5418
0
            PK11SlotInfo *slot = NULL;
5419
0
            if (sid->u.ssl3.masterValid) {
5420
0
                slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
5421
0
                                         sid->u.ssl3.masterSlotID);
5422
0
            }
5423
0
            if (slot == NULL) {
5424
0
                sidOK = PR_FALSE;
5425
0
            } else {
5426
0
                PK11SymKey *wrapKey = NULL;
5427
0
                if (!PK11_IsPresent(slot) ||
5428
0
                    ((wrapKey = PK11_GetWrapKey(slot,
5429
0
                                                sid->u.ssl3.masterWrapIndex,
5430
0
                                                sid->u.ssl3.masterWrapMech,
5431
0
                                                sid->u.ssl3.masterWrapSeries,
5432
0
                                                ss->pkcs11PinArg)) == NULL)) {
5433
0
                    sidOK = PR_FALSE;
5434
0
                }
5435
0
                if (wrapKey)
5436
0
                    PK11_FreeSymKey(wrapKey);
5437
0
                PK11_FreeSlot(slot);
5438
0
                slot = NULL;
5439
0
            }
5440
0
        }
5441
        /* If we previously did client-auth, make sure that the token that
5442
        ** holds the private key still exists, is logged in, hasn't been
5443
        ** removed, etc.
5444
        */
5445
0
        if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
5446
0
            sidOK = PR_FALSE;
5447
0
        }
5448
5449
0
        if (sidOK) {
5450
            /* Set version based on the sid. */
5451
0
            if (ss->firstHsDone) {
5452
                /*
5453
                 * Windows SChannel compares the client_version inside the RSA
5454
                 * EncryptedPreMasterSecret of a renegotiation with the
5455
                 * client_version of the initial ClientHello rather than the
5456
                 * ClientHello in the renegotiation. To work around this bug, we
5457
                 * continue to use the client_version used in the initial
5458
                 * ClientHello when renegotiating.
5459
                 *
5460
                 * The client_version of the initial ClientHello is still
5461
                 * available in ss->clientHelloVersion. Ensure that
5462
                 * sid->version is bounded within
5463
                 * [ss->vrange.min, ss->clientHelloVersion], otherwise we
5464
                 * can't use sid.
5465
                 */
5466
0
                if (sid->version >= ss->vrange.min &&
5467
0
                    sid->version <= ss->clientHelloVersion) {
5468
0
                    version = ss->clientHelloVersion;
5469
0
                } else {
5470
0
                    sidOK = PR_FALSE;
5471
0
                }
5472
0
            } else {
5473
                /*
5474
                 * Check sid->version is OK first.
5475
                 * Previously, we would cap the version based on sid->version,
5476
                 * but that prevents negotiation of a higher version if the
5477
                 * previous session was reduced (e.g., with version fallback)
5478
                 */
5479
0
                if (sid->version < ss->vrange.min ||
5480
0
                    sid->version > ss->vrange.max) {
5481
0
                    sidOK = PR_FALSE;
5482
0
                }
5483
0
            }
5484
0
        }
5485
5486
0
        if (!sidOK) {
5487
0
            SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_not_ok);
5488
0
            ssl_UncacheSessionID(ss);
5489
0
            ssl_FreeSID(sid);
5490
0
            sid = NULL;
5491
0
        }
5492
0
    }
5493
5494
13.7k
    if (sid) {
5495
0
        requestingResume = PR_TRUE;
5496
0
        SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_hits);
5497
5498
0
        PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
5499
0
                      sid->u.ssl3.sessionIDLength));
5500
5501
0
        ss->ssl3.policy = sid->u.ssl3.policy;
5502
13.7k
    } else {
5503
13.7k
        SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_misses);
5504
5505
        /*
5506
         * Windows SChannel compares the client_version inside the RSA
5507
         * EncryptedPreMasterSecret of a renegotiation with the
5508
         * client_version of the initial ClientHello rather than the
5509
         * ClientHello in the renegotiation. To work around this bug, we
5510
         * continue to use the client_version used in the initial
5511
         * ClientHello when renegotiating.
5512
         */
5513
13.7k
        if (ss->firstHsDone) {
5514
4.13k
            version = ss->clientHelloVersion;
5515
4.13k
        }
5516
5517
13.7k
        sid = ssl3_NewSessionID(ss, PR_FALSE);
5518
13.7k
        if (!sid) {
5519
0
            return SECFailure; /* memory error is set */
5520
0
        }
5521
        /* ss->version isn't set yet, but the sid needs a sane value. */
5522
13.7k
        sid->version = version;
5523
13.7k
    }
5524
5525
13.7k
    isTLS = (version > SSL_LIBRARY_VERSION_3_0);
5526
13.7k
    ssl_GetSpecWriteLock(ss);
5527
13.7k
    if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
5528
        /* SSL records are not being MACed. */
5529
9.57k
        ss->ssl3.cwSpec->version = version;
5530
9.57k
    }
5531
13.7k
    ssl_ReleaseSpecWriteLock(ss);
5532
5533
13.7k
    ssl_FreeSID(ss->sec.ci.sid); /* release the old sid */
5534
13.7k
    ss->sec.ci.sid = sid;
5535
5536
    /* HACK for SCSV in SSL 3.0.  On initial handshake, prepend SCSV,
5537
     * only if TLS is disabled.
5538
     */
5539
13.7k
    if (!ss->firstHsDone && !isTLS) {
5540
        /* Must set this before calling Hello Extension Senders,
5541
         * to suppress sending of empty RI extension.
5542
         */
5543
0
        ss->ssl3.hs.sendingSCSV = PR_TRUE;
5544
0
    }
5545
5546
    /* When we attempt session resumption (only), we must lock the sid to
5547
     * prevent races with other resumption connections that receive a
5548
     * NewSessionTicket that will cause the ticket in the sid to be replaced.
5549
     * Once we've copied the session ticket into our ClientHello message, it
5550
     * is OK for the ticket to change, so we just need to make sure we hold
5551
     * the lock across the calls to ssl_ConstructExtensions.
5552
     */
5553
13.7k
    if (sid->u.ssl3.lock) {
5554
0
        unlockNeeded = PR_TRUE;
5555
0
        PR_RWLock_Rlock(sid->u.ssl3.lock);
5556
0
    }
5557
5558
    /* Generate a new random if this is the first attempt or renegotiation. */
5559
13.7k
    if (type == client_hello_initial ||
5560
13.7k
        type == client_hello_renegotiation) {
5561
13.6k
        rv = ssl3_GetNewRandom(ss->ssl3.hs.client_random);
5562
13.6k
        if (rv != SECSuccess) {
5563
0
            goto loser; /* err set by GetNewRandom. */
5564
0
        }
5565
13.6k
    }
5566
5567
13.7k
    if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
5568
13.7k
        rv = tls13_SetupClientHello(ss, type);
5569
13.7k
        if (rv != SECSuccess) {
5570
0
            goto loser;
5571
0
        }
5572
13.7k
    }
5573
5574
    /* Setup TLS ClientHello Extension Permutation? */
5575
13.7k
    if (type == client_hello_initial &&
5576
13.7k
        ss->vrange.max > SSL_LIBRARY_VERSION_3_0 &&
5577
13.7k
        ss->opt.enableChXtnPermutation) {
5578
0
        rv = tls_ClientHelloExtensionPermutationSetup(ss);
5579
0
        if (rv != SECSuccess) {
5580
0
            goto loser;
5581
0
        }
5582
0
    }
5583
5584
13.7k
    if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
5585
13.7k
        rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_client_hello);
5586
13.7k
        if (rv != SECSuccess) {
5587
0
            goto loser;
5588
0
        }
5589
13.7k
    }
5590
5591
13.7k
    if (IS_DTLS(ss)) {
5592
0
        ssl3_DisableNonDTLSSuites(ss);
5593
0
    }
5594
5595
13.7k
    rv = ssl3_CreateClientHelloPreamble(ss, sid, requestingResume, version,
5596
13.7k
                                        PR_FALSE, &extensionBuf, &chBuf);
5597
13.7k
    if (rv != SECSuccess) {
5598
0
        goto loser; /* err set by ssl3_CreateClientHelloPreamble. */
5599
0
    }
5600
5601
13.7k
    if (!ss->ssl3.hs.echHpkeCtx) {
5602
13.7k
        if (extensionBuf.len) {
5603
13.7k
            rv = tls13_MaybeGreaseEch(ss, &chBuf, &extensionBuf);
5604
13.7k
            if (rv != SECSuccess) {
5605
0
                goto loser; /* err set by tls13_MaybeGreaseEch. */
5606
0
            }
5607
13.7k
            rv = ssl_InsertPaddingExtension(ss, chBuf.len, &extensionBuf);
5608
13.7k
            if (rv != SECSuccess) {
5609
0
                goto loser; /* err set by ssl_InsertPaddingExtension. */
5610
0
            }
5611
5612
13.7k
            rv = ssl3_InsertChHeaderSize(ss, &chBuf, &extensionBuf);
5613
13.7k
            if (rv != SECSuccess) {
5614
0
                goto loser; /* err set by ssl3_InsertChHeaderSize. */
5615
0
            }
5616
5617
            /* If we are sending a PSK binder, replace the dummy value. */
5618
13.7k
            if (ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)) {
5619
0
                rv = tls13_WriteExtensionsWithBinder(ss, &extensionBuf, &chBuf);
5620
13.7k
            } else {
5621
13.7k
                rv = sslBuffer_AppendNumber(&chBuf, extensionBuf.len, 2);
5622
13.7k
                if (rv != SECSuccess) {
5623
0
                    goto loser;
5624
0
                }
5625
13.7k
                rv = sslBuffer_AppendBuffer(&chBuf, &extensionBuf);
5626
13.7k
            }
5627
13.7k
            if (rv != SECSuccess) {
5628
0
                goto loser; /* err set by sslBuffer_Append*. */
5629
0
            }
5630
13.7k
        }
5631
5632
        /* If we already have a message in place, we need to enqueue it.
5633
         * This empties the buffer. This is a convenient place to call
5634
         * dtls_StageHandshakeMessage to mark the message boundary.  */
5635
13.7k
        if (IS_DTLS(ss)) {
5636
0
            rv = dtls_StageHandshakeMessage(ss);
5637
0
            if (rv != SECSuccess) {
5638
0
                goto loser;
5639
0
            }
5640
0
        }
5641
5642
        /* As here the function takes the full message and hashes it in one go,
5643
         * For DTLS1.3, we skip hashing the unnecessary header fields.
5644
         * See ssl3_AppendHandshakeHeader. */
5645
13.7k
        if (IS_DTLS(ss) && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
5646
0
            rv = ssl3_AppendHandshakeSuppressHash(ss, chBuf.buf, chBuf.len);
5647
0
            if (rv != SECSuccess) {
5648
0
                goto loser; /* code set */
5649
0
            }
5650
0
            if (!ss->firstHsDone) {
5651
0
                PORT_Assert(ss->ssl3.hs.dtls13ClientMessageBuffer.len == 0);
5652
0
                sslBuffer_Clear(&ss->ssl3.hs.dtls13ClientMessageBuffer);
5653
                /* Here instead of computing the hash, we copy the data to a buffer.*/
5654
0
                rv = sslBuffer_Append(&ss->ssl3.hs.dtls13ClientMessageBuffer, chBuf.buf, chBuf.len);
5655
0
            }
5656
13.7k
        } else {
5657
13.7k
            rv = ssl3_AppendHandshake(ss, chBuf.buf, chBuf.len);
5658
13.7k
        }
5659
5660
13.7k
    } else {
5661
0
        PORT_Assert(!IS_DTLS(ss));
5662
0
        rv = tls13_ConstructClientHelloWithEch(ss, sid, !requestingResume, &chBuf, &extensionBuf);
5663
0
        if (rv != SECSuccess) {
5664
0
            goto loser; /* code set */
5665
0
        }
5666
0
        rv = ssl3_UpdateDefaultHandshakeHashes(ss, chBuf.buf, chBuf.len);
5667
0
        if (rv != SECSuccess) {
5668
0
            goto loser; /* code set */
5669
0
        }
5670
5671
0
        if (IS_DTLS(ss)) {
5672
0
            rv = dtls_StageHandshakeMessage(ss);
5673
0
            if (rv != SECSuccess) {
5674
0
                goto loser;
5675
0
            }
5676
0
        }
5677
        /* By default, all messagess are added to both the inner and
5678
         * outer transcripts. For CH (or CH2 if HRR), that's problematic. */
5679
0
        rv = ssl3_AppendHandshakeSuppressHash(ss, chBuf.buf, chBuf.len);
5680
0
    }
5681
13.7k
    if (rv != SECSuccess) {
5682
0
        goto loser;
5683
0
    }
5684
5685
13.7k
    if (unlockNeeded) {
5686
        /* Note: goto loser can't be used past this point. */
5687
0
        PR_RWLock_Unlock(sid->u.ssl3.lock);
5688
0
    }
5689
5690
13.7k
    if (ss->xtnData.sentSessionTicketInClientHello) {
5691
0
        SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes);
5692
0
    }
5693
5694
13.7k
    if (ss->ssl3.hs.sendingSCSV) {
5695
        /* Since we sent the SCSV, pretend we sent empty RI extension. */
5696
0
        TLSExtensionData *xtnData = &ss->xtnData;
5697
0
        xtnData->advertised[xtnData->numAdvertised++] =
5698
0
            ssl_renegotiation_info_xtn;
5699
0
    }
5700
5701
13.7k
    flags = 0;
5702
13.7k
    rv = ssl3_FlushHandshake(ss, flags);
5703
13.7k
    if (rv != SECSuccess) {
5704
0
        return rv; /* error code set by ssl3_FlushHandshake */
5705
0
    }
5706
5707
13.7k
    if (version >= SSL_LIBRARY_VERSION_TLS_1_3) {
5708
9.57k
        rv = tls13_MaybeDo0RTTHandshake(ss);
5709
9.57k
        if (rv != SECSuccess) {
5710
0
            return SECFailure; /* error code set already. */
5711
0
        }
5712
9.57k
    }
5713
5714
13.7k
    ss->ssl3.hs.ws = wait_server_hello;
5715
13.7k
    sslBuffer_Clear(&chBuf);
5716
13.7k
    sslBuffer_Clear(&extensionBuf);
5717
13.7k
    return SECSuccess;
5718
5719
0
loser:
5720
0
    if (unlockNeeded) {
5721
0
        PR_RWLock_Unlock(sid->u.ssl3.lock);
5722
0
    }
5723
0
    sslBuffer_Clear(&chBuf);
5724
0
    sslBuffer_Clear(&extensionBuf);
5725
0
    return SECFailure;
5726
13.7k
}
5727
5728
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
5729
 * complete ssl3 Hello Request.
5730
 * Caller must hold Handshake and RecvBuf locks.
5731
 */
5732
static SECStatus
5733
ssl3_HandleHelloRequest(sslSocket *ss)
5734
6.90k
{
5735
6.90k
    sslSessionID *sid = ss->sec.ci.sid;
5736
6.90k
    SECStatus rv;
5737
5738
6.90k
    SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
5739
6.90k
                SSL_GETPID(), ss->fd));
5740
5741
6.90k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
5742
6.90k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5743
6.90k
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
5744
5745
6.90k
    if (ss->ssl3.hs.ws == wait_server_hello)
5746
2.73k
        return SECSuccess;
5747
4.16k
    if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
5748
35
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
5749
35
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
5750
35
        return SECFailure;
5751
35
    }
5752
4.13k
    if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
5753
0
        (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation);
5754
0
        PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
5755
0
        return SECFailure;
5756
0
    }
5757
5758
4.13k
    if (sid) {
5759
4.13k
        ssl_UncacheSessionID(ss);
5760
4.13k
        ssl_FreeSID(sid);
5761
4.13k
        ss->sec.ci.sid = NULL;
5762
4.13k
    }
5763
5764
4.13k
    if (IS_DTLS(ss)) {
5765
0
        dtls_RehandshakeCleanup(ss);
5766
0
    }
5767
5768
4.13k
    ssl_GetXmitBufLock(ss);
5769
4.13k
    rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
5770
4.13k
    ssl_ReleaseXmitBufLock(ss);
5771
5772
4.13k
    return rv;
5773
4.13k
}
5774
5775
static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
5776
    CKM_DES3_ECB,
5777
    CKM_CAST5_ECB,
5778
    CKM_DES_ECB,
5779
    CKM_KEY_WRAP_LYNKS,
5780
    CKM_IDEA_ECB,
5781
    CKM_CAST3_ECB,
5782
    CKM_CAST_ECB,
5783
    CKM_RC5_ECB,
5784
    CKM_RC2_ECB,
5785
    CKM_CDMF_ECB,
5786
    CKM_SKIPJACK_WRAP,
5787
    CKM_SKIPJACK_CBC64,
5788
    CKM_AES_ECB,
5789
    CKM_CAMELLIA_ECB,
5790
    CKM_SEED_ECB
5791
};
5792
5793
static SECStatus
5794
ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech, unsigned int *wrapMechIndex)
5795
0
{
5796
0
    unsigned int i;
5797
0
    for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
5798
0
        if (wrapMechanismList[i] == mech) {
5799
0
            *wrapMechIndex = i;
5800
0
            return SECSuccess;
5801
0
        }
5802
0
    }
5803
0
    PORT_Assert(0);
5804
0
    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5805
0
    return SECFailure;
5806
0
}
5807
5808
/* Each process sharing the server session ID cache has its own array of SymKey
5809
 * pointers for the symmetric wrapping keys that are used to wrap the master
5810
 * secrets.  There is one key for each authentication type.  These Symkeys
5811
 * correspond to the wrapped SymKeys kept in the server session cache.
5812
 */
5813
const SSLAuthType ssl_wrap_key_auth_type[SSL_NUM_WRAP_KEYS] = {
5814
    ssl_auth_rsa_decrypt,
5815
    ssl_auth_rsa_sign,
5816
    ssl_auth_rsa_pss,
5817
    ssl_auth_ecdsa,
5818
    ssl_auth_ecdh_rsa,
5819
    ssl_auth_ecdh_ecdsa
5820
};
5821
5822
static SECStatus
5823
ssl_FindIndexByWrapKey(const sslServerCert *serverCert, unsigned int *wrapKeyIndex)
5824
0
{
5825
0
    unsigned int i;
5826
0
    for (i = 0; i < SSL_NUM_WRAP_KEYS; ++i) {
5827
0
        if (SSL_CERT_IS(serverCert, ssl_wrap_key_auth_type[i])) {
5828
0
            *wrapKeyIndex = i;
5829
0
            return SECSuccess;
5830
0
        }
5831
0
    }
5832
    /* Can't assert here because we still get people using DSA certificates. */
5833
0
    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5834
0
    return SECFailure;
5835
0
}
5836
5837
static PK11SymKey *
5838
ssl_UnwrapSymWrappingKey(
5839
    SSLWrappedSymWrappingKey *pWswk,
5840
    SECKEYPrivateKey *svrPrivKey,
5841
    unsigned int wrapKeyIndex,
5842
    CK_MECHANISM_TYPE masterWrapMech,
5843
    void *pwArg)
5844
0
{
5845
0
    PK11SymKey *unwrappedWrappingKey = NULL;
5846
0
    SECItem wrappedKey;
5847
0
    PK11SymKey *Ks;
5848
0
    SECKEYPublicKey pubWrapKey;
5849
0
    ECCWrappedKeyInfo *ecWrapped;
5850
5851
    /* found the wrapping key on disk. */
5852
0
    PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
5853
0
    PORT_Assert(pWswk->wrapKeyIndex == wrapKeyIndex);
5854
0
    if (pWswk->symWrapMechanism != masterWrapMech ||
5855
0
        pWswk->wrapKeyIndex != wrapKeyIndex) {
5856
0
        goto loser;
5857
0
    }
5858
0
    wrappedKey.type = siBuffer;
5859
0
    wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
5860
0
    wrappedKey.len = pWswk->wrappedSymKeyLen;
5861
0
    PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
5862
5863
0
    switch (ssl_wrap_key_auth_type[wrapKeyIndex]) {
5864
5865
0
        case ssl_auth_rsa_decrypt:
5866
0
        case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
5867
0
            unwrappedWrappingKey =
5868
0
                PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
5869
0
                                     masterWrapMech, CKA_UNWRAP, 0);
5870
0
            break;
5871
5872
0
        case ssl_auth_ecdsa:
5873
0
        case ssl_auth_ecdh_rsa:
5874
0
        case ssl_auth_ecdh_ecdsa:
5875
            /*
5876
             * For ssl_auth_ecd*, we first create an EC public key based on
5877
             * data stored with the wrappedSymmetricWrappingkey. Next,
5878
             * we do an ECDH computation involving this public key and
5879
             * the SSL server's (long-term) EC private key. The resulting
5880
             * shared secret is treated the same way as Fortezza's Ks, i.e.,
5881
             * it is used to recover the symmetric wrapping key.
5882
             *
5883
             * The data in wrappedSymmetricWrappingkey is laid out as defined
5884
             * in the ECCWrappedKeyInfo structure.
5885
             */
5886
0
            ecWrapped = (ECCWrappedKeyInfo *)pWswk->wrappedSymmetricWrappingkey;
5887
5888
0
            PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5889
0
                            ecWrapped->wrappedKeyLen <=
5890
0
                        MAX_EC_WRAPPED_KEY_BUFLEN);
5891
5892
0
            if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5893
0
                    ecWrapped->wrappedKeyLen >
5894
0
                MAX_EC_WRAPPED_KEY_BUFLEN) {
5895
0
                PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5896
0
                goto loser;
5897
0
            }
5898
5899
0
            pubWrapKey.keyType = ecKey;
5900
0
            pubWrapKey.u.ec.size = ecWrapped->size;
5901
0
            pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
5902
0
            pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
5903
0
            pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
5904
0
            pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
5905
0
                                               ecWrapped->encodedParamLen;
5906
5907
0
            wrappedKey.len = ecWrapped->wrappedKeyLen;
5908
0
            wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
5909
0
                              ecWrapped->pubValueLen;
5910
5911
            /* Derive Ks using ECDH */
5912
0
            Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
5913
0
                                       NULL, CKM_ECDH1_DERIVE, masterWrapMech,
5914
0
                                       CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5915
0
            if (Ks == NULL) {
5916
0
                goto loser;
5917
0
            }
5918
5919
            /*  Use Ks to unwrap the wrapping key */
5920
0
            unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL,
5921
0
                                                     &wrappedKey, masterWrapMech,
5922
0
                                                     CKA_UNWRAP, 0);
5923
0
            PK11_FreeSymKey(Ks);
5924
5925
0
            break;
5926
5927
0
        default:
5928
0
            PORT_Assert(0);
5929
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5930
0
            goto loser;
5931
0
    }
5932
0
loser:
5933
0
    return unwrappedWrappingKey;
5934
0
}
5935
5936
typedef struct {
5937
    PK11SymKey *symWrapKey[SSL_NUM_WRAP_KEYS];
5938
} ssl3SymWrapKey;
5939
5940
static PZLock *symWrapKeysLock = NULL;
5941
static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS];
5942
5943
SECStatus
5944
ssl_FreeSymWrapKeysLock(void)
5945
9.52k
{
5946
9.52k
    if (symWrapKeysLock) {
5947
9.52k
        PZ_DestroyLock(symWrapKeysLock);
5948
9.52k
        symWrapKeysLock = NULL;
5949
9.52k
        return SECSuccess;
5950
9.52k
    }
5951
0
    PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
5952
0
    return SECFailure;
5953
9.52k
}
5954
5955
SECStatus
5956
SSL3_ShutdownServerCache(void)
5957
0
{
5958
0
    int i, j;
5959
5960
0
    if (!symWrapKeysLock)
5961
0
        return SECSuccess; /* lock was never initialized */
5962
0
    PZ_Lock(symWrapKeysLock);
5963
    /* get rid of all symWrapKeys */
5964
0
    for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
5965
0
        for (j = 0; j < SSL_NUM_WRAP_KEYS; ++j) {
5966
0
            PK11SymKey **pSymWrapKey;
5967
0
            pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
5968
0
            if (*pSymWrapKey) {
5969
0
                PK11_FreeSymKey(*pSymWrapKey);
5970
0
                *pSymWrapKey = NULL;
5971
0
            }
5972
0
        }
5973
0
    }
5974
5975
0
    PZ_Unlock(symWrapKeysLock);
5976
0
    ssl_FreeSessionCacheLocks();
5977
0
    return SECSuccess;
5978
0
}
5979
5980
SECStatus
5981
ssl_InitSymWrapKeysLock(void)
5982
9.52k
{
5983
9.52k
    symWrapKeysLock = PZ_NewLock(nssILockOther);
5984
9.52k
    return symWrapKeysLock ? SECSuccess : SECFailure;
5985
9.52k
}
5986
5987
/* Try to get wrapping key for mechanism from in-memory array.
5988
 * If that fails, look for one on disk.
5989
 * If that fails, generate a new one, put the new one on disk,
5990
 * Put the new key in the in-memory array.
5991
 *
5992
 * Note that this function performs some fairly inadvisable functions with
5993
 * certificate private keys.  ECDSA keys are used with ECDH; similarly, RSA
5994
 * signing keys are used to encrypt.  Bug 1248320.
5995
 */
5996
PK11SymKey *
5997
ssl3_GetWrappingKey(sslSocket *ss,
5998
                    PK11SlotInfo *masterSecretSlot,
5999
                    CK_MECHANISM_TYPE masterWrapMech,
6000
                    void *pwArg)
6001
0
{
6002
0
    SSLAuthType authType;
6003
0
    SECKEYPrivateKey *svrPrivKey;
6004
0
    SECKEYPublicKey *svrPubKey = NULL;
6005
0
    PK11SymKey *unwrappedWrappingKey = NULL;
6006
0
    PK11SymKey **pSymWrapKey;
6007
0
    CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM;
6008
0
    int length;
6009
0
    unsigned int wrapMechIndex;
6010
0
    unsigned int wrapKeyIndex;
6011
0
    SECStatus rv;
6012
0
    SECItem wrappedKey;
6013
0
    SSLWrappedSymWrappingKey wswk;
6014
0
    PK11SymKey *Ks = NULL;
6015
0
    SECKEYPublicKey *pubWrapKey = NULL;
6016
0
    SECKEYPrivateKey *privWrapKey = NULL;
6017
0
    ECCWrappedKeyInfo *ecWrapped;
6018
0
    const sslServerCert *serverCert = ss->sec.serverCert;
6019
6020
0
    PORT_Assert(serverCert);
6021
0
    PORT_Assert(serverCert->serverKeyPair);
6022
0
    PORT_Assert(serverCert->serverKeyPair->privKey);
6023
0
    PORT_Assert(serverCert->serverKeyPair->pubKey);
6024
0
    if (!serverCert || !serverCert->serverKeyPair ||
6025
0
        !serverCert->serverKeyPair->privKey ||
6026
0
        !serverCert->serverKeyPair->pubKey) {
6027
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6028
0
        return NULL; /* hmm */
6029
0
    }
6030
6031
0
    rv = ssl_FindIndexByWrapKey(serverCert, &wrapKeyIndex);
6032
0
    if (rv != SECSuccess)
6033
0
        return NULL; /* unusable wrapping key. */
6034
6035
0
    rv = ssl_FindIndexByWrapMechanism(masterWrapMech, &wrapMechIndex);
6036
0
    if (rv != SECSuccess)
6037
0
        return NULL; /* invalid masterWrapMech. */
6038
6039
0
    authType = ssl_wrap_key_auth_type[wrapKeyIndex];
6040
0
    svrPrivKey = serverCert->serverKeyPair->privKey;
6041
0
    pSymWrapKey = &symWrapKeys[wrapMechIndex].symWrapKey[wrapKeyIndex];
6042
6043
0
    ssl_InitSessionCacheLocks(PR_TRUE);
6044
6045
0
    PZ_Lock(symWrapKeysLock);
6046
6047
0
    unwrappedWrappingKey = *pSymWrapKey;
6048
0
    if (unwrappedWrappingKey != NULL) {
6049
0
        if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
6050
0
            unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
6051
0
            goto done;
6052
0
        }
6053
        /* slot series has changed, so this key is no good any more. */
6054
0
        PK11_FreeSymKey(unwrappedWrappingKey);
6055
0
        *pSymWrapKey = unwrappedWrappingKey = NULL;
6056
0
    }
6057
6058
    /* Try to get wrapped SymWrapping key out of the (disk) cache. */
6059
    /* Following call fills in wswk on success. */
6060
0
    rv = ssl_GetWrappingKey(wrapMechIndex, wrapKeyIndex, &wswk);
6061
0
    if (rv == SECSuccess) {
6062
        /* found the wrapped sym wrapping key on disk. */
6063
0
        unwrappedWrappingKey =
6064
0
            ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
6065
0
                                     masterWrapMech, pwArg);
6066
0
        if (unwrappedWrappingKey) {
6067
0
            goto install;
6068
0
        }
6069
0
    }
6070
6071
0
    if (!masterSecretSlot) /* caller doesn't want to create a new one. */
6072
0
        goto loser;
6073
6074
0
    length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
6075
    /* Zero length means fixed key length algorithm, or error.
6076
     * It's ambiguous.
6077
     */
6078
0
    unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
6079
0
                                       length, pwArg);
6080
0
    if (!unwrappedWrappingKey) {
6081
0
        goto loser;
6082
0
    }
6083
6084
    /* Prepare the buffer to receive the wrappedWrappingKey,
6085
     * the symmetric wrapping key wrapped using the server's pub key.
6086
     */
6087
0
    PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */
6088
6089
0
    svrPubKey = serverCert->serverKeyPair->pubKey;
6090
0
    wrappedKey.type = siBuffer;
6091
0
    wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey);
6092
0
    wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
6093
6094
0
    PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
6095
0
    if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
6096
0
        goto loser;
6097
6098
    /* wrap symmetric wrapping key in server's public key. */
6099
0
    switch (authType) {
6100
0
        case ssl_auth_rsa_decrypt:
6101
0
        case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
6102
0
        case ssl_auth_rsa_pss:
6103
0
            asymWrapMechanism = CKM_RSA_PKCS;
6104
0
            rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
6105
0
                                    unwrappedWrappingKey, &wrappedKey);
6106
0
            break;
6107
6108
0
        case ssl_auth_ecdsa:
6109
0
        case ssl_auth_ecdh_rsa:
6110
0
        case ssl_auth_ecdh_ecdsa:
6111
            /*
6112
             * We generate an ephemeral EC key pair. Perform an ECDH
6113
             * computation involving this ephemeral EC public key and
6114
             * the SSL server's (long-term) EC private key. The resulting
6115
             * shared secret is treated in the same way as Fortezza's Ks,
6116
             * i.e., it is used to wrap the wrapping key. To facilitate
6117
             * unwrapping in ssl_UnwrapWrappingKey, we also store all
6118
             * relevant info about the ephemeral EC public key in
6119
             * wswk.wrappedSymmetricWrappingkey and lay it out as
6120
             * described in the ECCWrappedKeyInfo structure.
6121
             */
6122
0
            PORT_Assert(SECKEY_GetPublicKeyType(svrPubKey) == ecKey);
6123
0
            if (SECKEY_GetPublicKeyType(svrPubKey) != ecKey) {
6124
                /* something is wrong in sslsecur.c if this isn't an ecKey */
6125
0
                PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6126
0
                rv = SECFailure;
6127
0
                goto ec_cleanup;
6128
0
            }
6129
6130
0
            privWrapKey = SECKEY_CreateECPrivateKey(
6131
0
                &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
6132
0
            if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
6133
0
                rv = SECFailure;
6134
0
                goto ec_cleanup;
6135
0
            }
6136
6137
            /* Set the key size in bits */
6138
0
            if (pubWrapKey->u.ec.size == 0) {
6139
0
                pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
6140
0
            }
6141
6142
0
            PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +
6143
0
                            pubWrapKey->u.ec.publicValue.len <
6144
0
                        MAX_EC_WRAPPED_KEY_BUFLEN);
6145
0
            if (pubWrapKey->u.ec.DEREncodedParams.len +
6146
0
                    pubWrapKey->u.ec.publicValue.len >=
6147
0
                MAX_EC_WRAPPED_KEY_BUFLEN) {
6148
0
                PORT_SetError(SEC_ERROR_INVALID_KEY);
6149
0
                rv = SECFailure;
6150
0
                goto ec_cleanup;
6151
0
            }
6152
6153
            /* Derive Ks using ECDH */
6154
0
            Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
6155
0
                                       NULL, CKM_ECDH1_DERIVE, masterWrapMech,
6156
0
                                       CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
6157
0
            if (Ks == NULL) {
6158
0
                rv = SECFailure;
6159
0
                goto ec_cleanup;
6160
0
            }
6161
6162
0
            ecWrapped = (ECCWrappedKeyInfo *)(wswk.wrappedSymmetricWrappingkey);
6163
0
            ecWrapped->size = pubWrapKey->u.ec.size;
6164
0
            ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
6165
0
            PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
6166
0
                        pubWrapKey->u.ec.DEREncodedParams.len);
6167
6168
0
            ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
6169
0
            PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen,
6170
0
                        pubWrapKey->u.ec.publicValue.data,
6171
0
                        pubWrapKey->u.ec.publicValue.len);
6172
6173
0
            wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN -
6174
0
                             (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
6175
0
            wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
6176
0
                              ecWrapped->pubValueLen;
6177
6178
            /* wrap symmetricWrapping key with the local Ks */
6179
0
            rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
6180
0
                                 unwrappedWrappingKey, &wrappedKey);
6181
6182
0
            if (rv != SECSuccess) {
6183
0
                goto ec_cleanup;
6184
0
            }
6185
6186
            /* Write down the length of wrapped key in the buffer
6187
             * wswk.wrappedSymmetricWrappingkey at the appropriate offset
6188
             */
6189
0
            ecWrapped->wrappedKeyLen = wrappedKey.len;
6190
6191
0
        ec_cleanup:
6192
0
            if (privWrapKey)
6193
0
                SECKEY_DestroyPrivateKey(privWrapKey);
6194
0
            if (pubWrapKey)
6195
0
                SECKEY_DestroyPublicKey(pubWrapKey);
6196
0
            if (Ks)
6197
0
                PK11_FreeSymKey(Ks);
6198
0
            asymWrapMechanism = masterWrapMech;
6199
0
            break;
6200
6201
0
        default:
6202
0
            rv = SECFailure;
6203
0
            break;
6204
0
    }
6205
6206
0
    if (rv != SECSuccess) {
6207
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6208
0
        goto loser;
6209
0
    }
6210
6211
0
    PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
6212
6213
0
    wswk.symWrapMechanism = masterWrapMech;
6214
0
    wswk.asymWrapMechanism = asymWrapMechanism;
6215
0
    wswk.wrapMechIndex = wrapMechIndex;
6216
0
    wswk.wrapKeyIndex = wrapKeyIndex;
6217
0
    wswk.wrappedSymKeyLen = wrappedKey.len;
6218
6219
    /* put it on disk. */
6220
    /* If the wrapping key for this KEA type has already been set,
6221
     * then abandon the value we just computed and
6222
     * use the one we got from the disk.
6223
     */
6224
0
    rv = ssl_SetWrappingKey(&wswk);
6225
0
    if (rv == SECSuccess) {
6226
        /* somebody beat us to it.  The original contents of our wswk
6227
         * has been replaced with the content on disk.  Now, discard
6228
         * the key we just created and unwrap this new one.
6229
         */
6230
0
        PK11_FreeSymKey(unwrappedWrappingKey);
6231
6232
0
        unwrappedWrappingKey =
6233
0
            ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
6234
0
                                     masterWrapMech, pwArg);
6235
0
    }
6236
6237
0
install:
6238
0
    if (unwrappedWrappingKey) {
6239
0
        *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
6240
0
    }
6241
6242
0
loser:
6243
0
done:
6244
0
    PZ_Unlock(symWrapKeysLock);
6245
0
    return unwrappedWrappingKey;
6246
0
}
6247
6248
#ifdef NSS_ALLOW_SSLKEYLOGFILE
6249
/* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
6250
 * bytes to |out|. */
6251
static void
6252
hexEncode(char *out, const unsigned char *in, unsigned int length)
6253
0
{
6254
0
    static const char hextable[] = "0123456789abcdef";
6255
0
    unsigned int i;
6256
6257
0
    for (i = 0; i < length; i++) {
6258
0
        *(out++) = hextable[in[i] >> 4];
6259
0
        *(out++) = hextable[in[i] & 15];
6260
0
    }
6261
0
}
6262
#endif
6263
6264
/* Called from ssl3_SendClientKeyExchange(). */
6265
static SECStatus
6266
ssl3_SendRSAClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
6267
1.63k
{
6268
1.63k
    PK11SymKey *pms = NULL;
6269
1.63k
    SECStatus rv = SECFailure;
6270
1.63k
    SECItem enc_pms = { siBuffer, NULL, 0 };
6271
1.63k
    PRBool isTLS;
6272
6273
1.63k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6274
1.63k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6275
6276
    /* Generate the pre-master secret ...  */
6277
1.63k
    ssl_GetSpecWriteLock(ss);
6278
1.63k
    isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
6279
6280
1.63k
    pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
6281
1.63k
    ssl_ReleaseSpecWriteLock(ss);
6282
1.63k
    if (pms == NULL) {
6283
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6284
0
        goto loser;
6285
0
    }
6286
6287
    /* Get the wrapped (encrypted) pre-master secret, enc_pms */
6288
1.63k
    unsigned int svrPubKeyBits = SECKEY_PublicKeyStrengthInBits(svrPubKey);
6289
1.63k
    enc_pms.len = (svrPubKeyBits + 7) / 8;
6290
    /* Check that the RSA key isn't larger than 8k bit. */
6291
1.63k
    if (svrPubKeyBits > SSL_MAX_RSA_KEY_BITS) {
6292
0
        (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
6293
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6294
0
        goto loser;
6295
0
    }
6296
1.63k
    enc_pms.data = (unsigned char *)PORT_Alloc(enc_pms.len);
6297
1.63k
    if (enc_pms.data == NULL) {
6298
0
        goto loser; /* err set by PORT_Alloc */
6299
0
    }
6300
6301
    /* Wrap pre-master secret in server's public key. */
6302
1.63k
    rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
6303
1.63k
    if (rv != SECSuccess) {
6304
434
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6305
434
        goto loser;
6306
434
    }
6307
6308
1.20k
#ifdef TRACE
6309
1.20k
    if (ssl_trace >= 100) {
6310
0
        SECStatus extractRV = PK11_ExtractKeyValue(pms);
6311
0
        if (extractRV == SECSuccess) {
6312
0
            SECItem *keyData = PK11_GetKeyData(pms);
6313
0
            if (keyData && keyData->data && keyData->len) {
6314
0
                ssl_PrintBuf(ss, "Pre-Master Secret",
6315
0
                             keyData->data, keyData->len);
6316
0
            }
6317
0
        }
6318
0
    }
6319
1.20k
#endif
6320
6321
1.20k
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
6322
1.20k
                                    isTLS ? enc_pms.len + 2
6323
1.20k
                                          : enc_pms.len);
6324
1.20k
    if (rv != SECSuccess) {
6325
0
        goto loser; /* err set by ssl3_AppendHandshake* */
6326
0
    }
6327
1.20k
    if (isTLS) {
6328
1.20k
        rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
6329
1.20k
    } else {
6330
0
        rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
6331
0
    }
6332
1.20k
    if (rv != SECSuccess) {
6333
0
        goto loser; /* err set by ssl3_AppendHandshake* */
6334
0
    }
6335
6336
1.20k
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
6337
1.20k
    PK11_FreeSymKey(pms);
6338
1.20k
    pms = NULL;
6339
6340
1.20k
    if (rv != SECSuccess) {
6341
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6342
0
        goto loser;
6343
0
    }
6344
6345
1.20k
    rv = SECSuccess;
6346
6347
1.63k
loser:
6348
1.63k
    if (enc_pms.data != NULL) {
6349
1.63k
        PORT_Free(enc_pms.data);
6350
1.63k
    }
6351
1.63k
    if (pms != NULL) {
6352
434
        PK11_FreeSymKey(pms);
6353
434
    }
6354
1.63k
    return rv;
6355
1.20k
}
6356
6357
/* DH shares need to be padded to the size of their prime.  Some implementations
6358
 * require this.  TLS 1.3 also requires this. */
6359
SECStatus
6360
ssl_AppendPaddedDHKeyShare(sslBuffer *buf, const SECKEYPublicKey *pubKey,
6361
                           PRBool appendLength)
6362
3
{
6363
3
    SECStatus rv;
6364
3
    unsigned int pad = pubKey->u.dh.prime.len - pubKey->u.dh.publicValue.len;
6365
6366
3
    if (appendLength) {
6367
3
        rv = sslBuffer_AppendNumber(buf, pubKey->u.dh.prime.len, 2);
6368
3
        if (rv != SECSuccess) {
6369
0
            return rv;
6370
0
        }
6371
3
    }
6372
3
    while (pad) {
6373
0
        rv = sslBuffer_AppendNumber(buf, 0, 1);
6374
0
        if (rv != SECSuccess) {
6375
0
            return rv;
6376
0
        }
6377
0
        --pad;
6378
0
    }
6379
3
    rv = sslBuffer_Append(buf, pubKey->u.dh.publicValue.data,
6380
3
                          pubKey->u.dh.publicValue.len);
6381
3
    if (rv != SECSuccess) {
6382
0
        return rv;
6383
0
    }
6384
3
    return SECSuccess;
6385
3
}
6386
6387
/* Called from ssl3_SendClientKeyExchange(). */
6388
static SECStatus
6389
ssl3_SendDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
6390
3
{
6391
3
    PK11SymKey *pms = NULL;
6392
3
    SECStatus rv;
6393
3
    PRBool isTLS;
6394
3
    CK_MECHANISM_TYPE target;
6395
6396
3
    const ssl3DHParams *params;
6397
3
    ssl3DHParams customParams;
6398
3
    const sslNamedGroupDef *groupDef;
6399
3
    static const sslNamedGroupDef customGroupDef = {
6400
3
        ssl_grp_ffdhe_custom, 0, ssl_kea_dh, SEC_OID_TLS_DHE_CUSTOM, PR_FALSE
6401
3
    };
6402
3
    sslEphemeralKeyPair *keyPair = NULL;
6403
3
    SECKEYPublicKey *pubKey;
6404
3
    PRUint8 dhData[SSL_MAX_DH_KEY_BITS / 8 + 2];
6405
3
    sslBuffer dhBuf = SSL_BUFFER(dhData);
6406
6407
3
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6408
3
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6409
6410
3
    isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
6411
6412
    /* Copy DH parameters from server key */
6413
6414
3
    if (SECKEY_GetPublicKeyType(svrPubKey) != dhKey) {
6415
0
        PORT_SetError(SEC_ERROR_BAD_KEY);
6416
0
        return SECFailure;
6417
0
    }
6418
6419
    /* Work out the parameters. */
6420
3
    rv = ssl_ValidateDHENamedGroup(ss, &svrPubKey->u.dh.prime,
6421
3
                                   &svrPubKey->u.dh.base,
6422
3
                                   &groupDef, &params);
6423
3
    if (rv != SECSuccess) {
6424
        /* If we require named groups, we will have already validated the group
6425
         * in ssl_HandleDHServerKeyExchange() */
6426
0
        PORT_Assert(!ss->opt.requireDHENamedGroups &&
6427
0
                    !ss->xtnData.peerSupportsFfdheGroups);
6428
6429
0
        customParams.name = ssl_grp_ffdhe_custom;
6430
0
        customParams.prime.data = svrPubKey->u.dh.prime.data;
6431
0
        customParams.prime.len = svrPubKey->u.dh.prime.len;
6432
0
        customParams.base.data = svrPubKey->u.dh.base.data;
6433
0
        customParams.base.len = svrPubKey->u.dh.base.len;
6434
0
        params = &customParams;
6435
0
        groupDef = &customGroupDef;
6436
0
    }
6437
3
    ss->sec.keaGroup = groupDef;
6438
6439
3
    rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
6440
3
    if (rv != SECSuccess) {
6441
0
        ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
6442
0
        goto loser;
6443
0
    }
6444
3
    pubKey = keyPair->keys->pubKey;
6445
3
    PRINT_BUF(50, (ss, "DH public value:",
6446
3
                   pubKey->u.dh.publicValue.data,
6447
3
                   pubKey->u.dh.publicValue.len));
6448
6449
3
    if (isTLS)
6450
3
        target = CKM_TLS_MASTER_KEY_DERIVE_DH;
6451
0
    else
6452
0
        target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
6453
6454
    /* Determine the PMS */
6455
3
    pms = PK11_PubDerive(keyPair->keys->privKey, svrPubKey,
6456
3
                         PR_FALSE, NULL, NULL, CKM_DH_PKCS_DERIVE,
6457
3
                         target, CKA_DERIVE, 0, NULL);
6458
6459
3
    if (pms == NULL) {
6460
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6461
0
        goto loser;
6462
0
    }
6463
6464
    /* Note: send the DH share padded to avoid triggering bugs. */
6465
3
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
6466
3
                                    params->prime.len + 2);
6467
3
    if (rv != SECSuccess) {
6468
0
        goto loser; /* err set by ssl3_AppendHandshake* */
6469
0
    }
6470
3
    rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE);
6471
3
    if (rv != SECSuccess) {
6472
0
        goto loser; /* err set by ssl_AppendPaddedDHKeyShare */
6473
0
    }
6474
3
    rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
6475
3
    if (rv != SECSuccess) {
6476
0
        goto loser; /* err set by ssl3_AppendBufferToHandshake */
6477
0
    }
6478
6479
3
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
6480
3
    if (rv != SECSuccess) {
6481
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6482
0
        goto loser;
6483
0
    }
6484
6485
3
    sslBuffer_Clear(&dhBuf);
6486
3
    PK11_FreeSymKey(pms);
6487
3
    ssl_FreeEphemeralKeyPair(keyPair);
6488
3
    return SECSuccess;
6489
6490
0
loser:
6491
0
    if (pms)
6492
0
        PK11_FreeSymKey(pms);
6493
0
    if (keyPair)
6494
0
        ssl_FreeEphemeralKeyPair(keyPair);
6495
0
    sslBuffer_Clear(&dhBuf);
6496
0
    return SECFailure;
6497
3
}
6498
6499
/* Called from ssl3_HandleServerHelloDone(). */
6500
static SECStatus
6501
ssl3_SendClientKeyExchange(sslSocket *ss)
6502
5.35k
{
6503
5.35k
    SECKEYPublicKey *serverKey = NULL;
6504
5.35k
    SECStatus rv = SECFailure;
6505
6506
5.35k
    SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
6507
5.35k
                SSL_GETPID(), ss->fd));
6508
6509
5.35k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6510
5.35k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6511
6512
5.35k
    if (ss->sec.peerKey == NULL) {
6513
4.70k
        serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
6514
4.70k
        if (serverKey == NULL) {
6515
0
            ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
6516
0
            return SECFailure;
6517
0
        }
6518
4.70k
    } else {
6519
654
        serverKey = ss->sec.peerKey;
6520
654
        ss->sec.peerKey = NULL; /* we're done with it now */
6521
654
    }
6522
6523
5.35k
    ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
6524
5.35k
    ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
6525
6526
5.35k
    switch (ss->ssl3.hs.kea_def->exchKeyType) {
6527
1.63k
        case ssl_kea_rsa:
6528
1.63k
            rv = ssl3_SendRSAClientKeyExchange(ss, serverKey);
6529
1.63k
            break;
6530
6531
3
        case ssl_kea_dh:
6532
3
            rv = ssl3_SendDHClientKeyExchange(ss, serverKey);
6533
3
            break;
6534
6535
3.71k
        case ssl_kea_ecdh:
6536
3.71k
            rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
6537
3.71k
            break;
6538
6539
0
        default:
6540
0
            PORT_Assert(0);
6541
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6542
0
            break;
6543
5.35k
    }
6544
6545
5.35k
    SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
6546
5.35k
                SSL_GETPID(), ss->fd));
6547
6548
5.35k
    SECKEY_DestroyPublicKey(serverKey);
6549
5.35k
    return rv; /* err code already set. */
6550
5.35k
}
6551
6552
/* Used by ssl_PickSignatureScheme(). */
6553
PRBool
6554
ssl_CanUseSignatureScheme(SSLSignatureScheme scheme,
6555
                          const SSLSignatureScheme *peerSchemes,
6556
                          unsigned int peerSchemeCount,
6557
                          PRBool requireSha1,
6558
                          PRBool slotDoesPss)
6559
0
{
6560
0
    SSLHashType hashType;
6561
0
    unsigned int i;
6562
6563
    /* Skip RSA-PSS schemes when the certificate's private key slot does
6564
     * not support this signature mechanism. */
6565
0
    if (ssl_IsRsaPssSignatureScheme(scheme) && !slotDoesPss) {
6566
0
        return PR_FALSE;
6567
0
    }
6568
6569
0
    hashType = ssl_SignatureSchemeToHashType(scheme);
6570
0
    if (requireSha1 && (hashType != ssl_hash_sha1)) {
6571
0
        return PR_FALSE;
6572
0
    }
6573
6574
0
    if (!ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy)) {
6575
0
        return PR_FALSE;
6576
0
    }
6577
6578
0
    for (i = 0; i < peerSchemeCount; i++) {
6579
0
        if (peerSchemes[i] == scheme) {
6580
0
            return PR_TRUE;
6581
0
        }
6582
0
    }
6583
0
    return PR_FALSE;
6584
0
}
6585
6586
SECStatus
6587
ssl_PrivateKeySupportsRsaPss(SECKEYPrivateKey *privKey, CERTCertificate *cert,
6588
                             void *pwarg, PRBool *supportsRsaPss)
6589
0
{
6590
0
    PK11SlotInfo *slot = NULL;
6591
0
    if (privKey) {
6592
0
        slot = PK11_GetSlotFromPrivateKey(privKey);
6593
0
    } else {
6594
0
        CK_OBJECT_HANDLE certID = PK11_FindObjectForCert(cert, pwarg, &slot);
6595
0
        if (certID == CK_INVALID_HANDLE) {
6596
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6597
0
            return SECFailure;
6598
0
        }
6599
0
    }
6600
0
    if (!slot) {
6601
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6602
0
        return SECFailure;
6603
0
    }
6604
0
    *supportsRsaPss = PK11_DoesMechanism(slot, auth_alg_defs[ssl_auth_rsa_pss]);
6605
0
    PK11_FreeSlot(slot);
6606
0
    return SECSuccess;
6607
0
}
6608
6609
SECStatus
6610
ssl_PickSignatureScheme(sslSocket *ss,
6611
                        CERTCertificate *cert,
6612
                        SECKEYPublicKey *pubKey,
6613
                        SECKEYPrivateKey *privKey,
6614
                        const SSLSignatureScheme *peerSchemes,
6615
                        unsigned int peerSchemeCount,
6616
                        PRBool requireSha1,
6617
                        SSLSignatureScheme *schemePtr)
6618
0
{
6619
0
    unsigned int i;
6620
0
    PRBool doesRsaPss;
6621
0
    PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
6622
0
    SECStatus rv;
6623
0
    SSLSignatureScheme scheme;
6624
0
    SECOidTag spkiOid;
6625
6626
    /* We can't require SHA-1 in TLS 1.3. */
6627
0
    PORT_Assert(!(requireSha1 && isTLS13));
6628
0
    if (!pubKey || !cert) {
6629
0
        PORT_Assert(0);
6630
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6631
0
        return SECFailure;
6632
0
    }
6633
0
    rv = ssl_PrivateKeySupportsRsaPss(privKey, cert, ss->pkcs11PinArg,
6634
0
                                      &doesRsaPss);
6635
0
    if (rv != SECSuccess) {
6636
0
        return SECFailure;
6637
0
    }
6638
6639
    /* If the certificate SPKI indicates a single scheme, don't search. */
6640
0
    rv = ssl_SignatureSchemeFromSpki(&cert->subjectPublicKeyInfo,
6641
0
                                     isTLS13, &scheme);
6642
0
    if (rv != SECSuccess) {
6643
0
        return SECFailure;
6644
0
    }
6645
0
    if (scheme != ssl_sig_none) {
6646
0
        if (!ssl_SignatureSchemeEnabled(ss, scheme) ||
6647
0
            !ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
6648
0
                                       requireSha1, doesRsaPss)) {
6649
0
            PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
6650
0
            return SECFailure;
6651
0
        }
6652
0
        *schemePtr = scheme;
6653
0
        return SECSuccess;
6654
0
    }
6655
6656
0
    spkiOid = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm);
6657
0
    if (spkiOid == SEC_OID_UNKNOWN) {
6658
0
        return SECFailure;
6659
0
    }
6660
6661
    /* Now we have to search based on the key type. Go through our preferred
6662
     * schemes in order and find the first that can be used. */
6663
0
    for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
6664
0
        scheme = ss->ssl3.signatureSchemes[i];
6665
6666
0
        if (ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13) &&
6667
0
            ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
6668
0
                                      requireSha1, doesRsaPss)) {
6669
0
            *schemePtr = scheme;
6670
0
            return SECSuccess;
6671
0
        }
6672
0
    }
6673
6674
0
    PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
6675
0
    return SECFailure;
6676
0
}
6677
6678
static SECStatus
6679
ssl_PickFallbackSignatureScheme(sslSocket *ss, SECKEYPublicKey *pubKey)
6680
0
{
6681
0
    PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
6682
6683
0
    switch (SECKEY_GetPublicKeyType(pubKey)) {
6684
0
        case rsaKey:
6685
0
            if (isTLS12) {
6686
0
                ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1;
6687
0
            } else {
6688
0
                ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1md5;
6689
0
            }
6690
0
            break;
6691
0
        case ecKey:
6692
0
            ss->ssl3.hs.signatureScheme = ssl_sig_ecdsa_sha1;
6693
0
            break;
6694
0
        case dsaKey:
6695
0
            ss->ssl3.hs.signatureScheme = ssl_sig_dsa_sha1;
6696
0
            break;
6697
0
        default:
6698
0
            PORT_Assert(0);
6699
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
6700
0
            return SECFailure;
6701
0
    }
6702
0
    return SECSuccess;
6703
0
}
6704
6705
/* ssl3_PickServerSignatureScheme selects a signature scheme for signing the
6706
 * handshake.  Most of this is determined by the key pair we are using.
6707
 * Prior to TLS 1.2, the MD5/SHA1 combination is always used. With TLS 1.2, a
6708
 * client may advertise its support for signature and hash combinations. */
6709
static SECStatus
6710
ssl3_PickServerSignatureScheme(sslSocket *ss)
6711
0
{
6712
0
    const sslServerCert *cert = ss->sec.serverCert;
6713
0
    PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
6714
6715
0
    if (!isTLS12 || !ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) {
6716
        /* If the client didn't provide any signature_algorithms extension then
6717
         * we can assume that they support SHA-1: RFC5246, Section 7.4.1.4.1. */
6718
0
        return ssl_PickFallbackSignatureScheme(ss, cert->serverKeyPair->pubKey);
6719
0
    }
6720
6721
    /* Sets error code, if needed. */
6722
0
    return ssl_PickSignatureScheme(ss, cert->serverCert,
6723
0
                                   cert->serverKeyPair->pubKey,
6724
0
                                   cert->serverKeyPair->privKey,
6725
0
                                   ss->xtnData.sigSchemes,
6726
0
                                   ss->xtnData.numSigSchemes,
6727
0
                                   PR_FALSE /* requireSha1 */,
6728
0
                                   &ss->ssl3.hs.signatureScheme);
6729
0
}
6730
6731
SECStatus
6732
ssl_PickClientSignatureScheme(sslSocket *ss, CERTCertificate *clientCertificate,
6733
                              SECKEYPrivateKey *privKey,
6734
                              const SSLSignatureScheme *schemes,
6735
                              unsigned int numSchemes,
6736
                              SSLSignatureScheme *schemePtr)
6737
0
{
6738
0
    SECStatus rv;
6739
0
    PRBool isTLS13 = (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
6740
0
    SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(clientCertificate);
6741
6742
0
    PORT_Assert(pubKey);
6743
6744
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
6745
        /* We should have already checked that a signature scheme was
6746
         * listed in the request. */
6747
0
        PORT_Assert(schemes && numSchemes > 0);
6748
0
    }
6749
6750
0
    if (!isTLS13 &&
6751
0
        (SECKEY_GetPublicKeyType(pubKey) == rsaKey ||
6752
0
         SECKEY_GetPublicKeyType(pubKey) == dsaKey) &&
6753
0
        SECKEY_PublicKeyStrengthInBits(pubKey) <= 1024) {
6754
        /* If the key is a 1024-bit RSA or DSA key, assume conservatively that
6755
         * it may be unable to sign SHA-256 hashes. This is the case for older
6756
         * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and
6757
         * older, DSA key size is at most 1024 bits and the hash function must
6758
         * be SHA-1.
6759
         */
6760
0
        rv = ssl_PickSignatureScheme(ss, clientCertificate,
6761
0
                                     pubKey, privKey, schemes, numSchemes,
6762
0
                                     PR_TRUE /* requireSha1 */, schemePtr);
6763
0
        if (rv == SECSuccess) {
6764
0
            SECKEY_DestroyPublicKey(pubKey);
6765
0
            return SECSuccess;
6766
0
        }
6767
        /* If this fails, that's because the peer doesn't advertise SHA-1,
6768
         * so fall back to the full negotiation. */
6769
0
    }
6770
0
    rv = ssl_PickSignatureScheme(ss, clientCertificate,
6771
0
                                 pubKey, privKey, schemes, numSchemes,
6772
0
                                 PR_FALSE /* requireSha1 */, schemePtr);
6773
0
    SECKEY_DestroyPublicKey(pubKey);
6774
0
    return rv;
6775
0
}
6776
6777
/* Called from ssl3_HandleServerHelloDone(). */
6778
static SECStatus
6779
ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
6780
0
{
6781
0
    SECStatus rv = SECFailure;
6782
0
    PRBool isTLS12;
6783
0
    SECItem buf = { siBuffer, NULL, 0 };
6784
0
    SSL3Hashes hashes;
6785
0
    unsigned int len;
6786
0
    SSLHashType hashAlg;
6787
6788
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6789
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6790
6791
0
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
6792
0
                SSL_GETPID(), ss->fd));
6793
6794
0
    ssl_GetSpecReadLock(ss);
6795
6796
0
    if (ss->ssl3.hs.hashType == handshake_hash_record) {
6797
0
        hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
6798
0
    } else {
6799
        /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
6800
0
        hashAlg = ssl_hash_none;
6801
0
    }
6802
0
    if (ss->ssl3.hs.hashType == handshake_hash_record &&
6803
0
        hashAlg != ssl3_GetSuitePrfHash(ss)) {
6804
0
        rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
6805
0
                                       ss->ssl3.hs.messages.len,
6806
0
                                       hashAlg, &hashes);
6807
0
        if (rv != SECSuccess) {
6808
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
6809
0
        }
6810
0
    } else {
6811
0
        rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
6812
0
    }
6813
0
    ssl_ReleaseSpecReadLock(ss);
6814
0
    if (rv != SECSuccess) {
6815
0
        goto done; /* err code was set by ssl3_ComputeHandshakeHash(es) */
6816
0
    }
6817
6818
0
    isTLS12 = (PRBool)(ss->version == SSL_LIBRARY_VERSION_TLS_1_2);
6819
0
    PORT_Assert(ss->version <= SSL_LIBRARY_VERSION_TLS_1_2);
6820
6821
0
    rv = ssl3_SignHashes(ss, &hashes, privKey, &buf);
6822
0
    if (rv == SECSuccess && !ss->sec.isServer) {
6823
        /* Remember the info about the slot that did the signing.
6824
        ** Later, when doing an SSL restart handshake, verify this.
6825
        ** These calls are mere accessors, and can't fail.
6826
        */
6827
0
        PK11SlotInfo *slot;
6828
0
        sslSessionID *sid = ss->sec.ci.sid;
6829
6830
0
        slot = PK11_GetSlotFromPrivateKey(privKey);
6831
0
        sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
6832
0
        sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
6833
0
        sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
6834
0
        sid->u.ssl3.clAuthValid = PR_TRUE;
6835
0
        PK11_FreeSlot(slot);
6836
0
    }
6837
0
    if (rv != SECSuccess) {
6838
0
        goto done; /* err code was set by ssl3_SignHashes */
6839
0
    }
6840
6841
0
    len = buf.len + 2 + (isTLS12 ? 2 : 0);
6842
6843
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len);
6844
0
    if (rv != SECSuccess) {
6845
0
        goto done; /* error code set by AppendHandshake */
6846
0
    }
6847
0
    if (isTLS12) {
6848
0
        rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
6849
0
        if (rv != SECSuccess) {
6850
0
            goto done; /* err set by AppendHandshake. */
6851
0
        }
6852
0
    }
6853
0
    rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
6854
0
    if (rv != SECSuccess) {
6855
0
        goto done; /* error code set by AppendHandshake */
6856
0
    }
6857
6858
0
done:
6859
0
    if (buf.data)
6860
0
        PORT_Free(buf.data);
6861
0
    return rv;
6862
0
}
6863
6864
/* Once a cipher suite has been selected, make sure that the necessary secondary
6865
 * information is properly set. */
6866
SECStatus
6867
ssl3_SetupCipherSuite(sslSocket *ss, PRBool initHashes)
6868
12.6k
{
6869
12.6k
    ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
6870
12.6k
    if (!ss->ssl3.hs.suite_def) {
6871
0
        PORT_Assert(0);
6872
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6873
0
        return SECFailure;
6874
0
    }
6875
6876
12.6k
    ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg];
6877
12.6k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite;
6878
6879
12.6k
    if (!initHashes) {
6880
78
        return SECSuccess;
6881
78
    }
6882
    /* Now we have a cipher suite, initialize the handshake hashes. */
6883
12.5k
    return ssl3_InitHandshakeHashes(ss);
6884
12.6k
}
6885
6886
SECStatus
6887
ssl_ClientSetCipherSuite(sslSocket *ss, SSL3ProtocolVersion version,
6888
                         ssl3CipherSuite suite, PRBool initHashes)
6889
12.6k
{
6890
12.6k
    unsigned int i;
6891
12.6k
    if (ssl3_config_match_init(ss) == 0) {
6892
0
        PORT_Assert(PR_FALSE);
6893
0
        return SECFailure;
6894
0
    }
6895
503k
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
6896
503k
        ssl3CipherSuiteCfg *suiteCfg = &ss->cipherSuites[i];
6897
503k
        if (suite == suiteCfg->cipher_suite) {
6898
12.6k
            SSLVersionRange vrange = { version, version };
6899
12.6k
            if (!ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) {
6900
                /* config_match already checks whether the cipher suite is
6901
                 * acceptable for the version, but the check is repeated here
6902
                 * in order to give a more precise error code. */
6903
29
                if (!ssl3_CipherSuiteAllowedForVersionRange(suite, &vrange)) {
6904
29
                    PORT_SetError(SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION);
6905
29
                } else {
6906
0
                    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
6907
0
                }
6908
29
                return SECFailure;
6909
29
            }
6910
12.6k
            break;
6911
12.6k
        }
6912
503k
    }
6913
12.6k
    if (i >= ssl_V3_SUITES_IMPLEMENTED) {
6914
12
        PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
6915
12
        return SECFailure;
6916
12
    }
6917
6918
    /* Don't let the server change its mind. */
6919
12.6k
    if (ss->ssl3.hs.helloRetry && suite != ss->ssl3.hs.cipher_suite) {
6920
1
        (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
6921
1
        PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
6922
1
        return SECFailure;
6923
1
    }
6924
6925
12.6k
    ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)suite;
6926
12.6k
    return ssl3_SetupCipherSuite(ss, initHashes);
6927
12.6k
}
6928
6929
/* Check that session ID we received from the server, if any, matches our
6930
 * expectations, depending on whether we're in compat mode and whether we
6931
 * negotiated TLS 1.3+ or TLS 1.2-.
6932
 */
6933
static PRBool
6934
ssl_CheckServerSessionIdCorrectness(sslSocket *ss, SECItem *sidBytes)
6935
12.6k
{
6936
12.6k
    sslSessionID *sid = ss->sec.ci.sid;
6937
12.6k
    PRBool sidMatch = PR_FALSE;
6938
12.6k
    PRBool sentFakeSid = PR_FALSE;
6939
12.6k
    PRBool sentRealSid = sid && sid->version < SSL_LIBRARY_VERSION_TLS_1_3;
6940
6941
    /* If attempting to resume a TLS 1.2 connection, the session ID won't be a
6942
     * fake. Check for the real value. */
6943
12.6k
    if (sentRealSid) {
6944
4.07k
        sidMatch = (sidBytes->len == sid->u.ssl3.sessionIDLength) &&
6945
4.07k
                   (!sidBytes->len || PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len) == 0);
6946
8.59k
    } else {
6947
        /* Otherwise, the session ID was a fake if TLS 1.3 compat mode is
6948
         * enabled.  If so, check for the fake value. */
6949
8.59k
        sentFakeSid = ss->opt.enableTls13CompatMode && !IS_DTLS(ss);
6950
8.59k
        if (sentFakeSid && sidBytes->len == SSL3_SESSIONID_BYTES) {
6951
0
            PRUint8 buf[SSL3_SESSIONID_BYTES];
6952
0
            ssl_MakeFakeSid(ss, buf);
6953
0
            sidMatch = PORT_Memcmp(buf, sidBytes->data, sidBytes->len) == 0;
6954
0
        }
6955
8.59k
    }
6956
6957
    /* TLS 1.2: Session ID shouldn't match if we sent a fake. */
6958
12.6k
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
6959
12.4k
        if (sentFakeSid) {
6960
0
            return !sidMatch;
6961
0
        }
6962
12.4k
        return PR_TRUE;
6963
12.4k
    }
6964
6965
    /* TLS 1.3: We sent a session ID.  The server's should match. */
6966
195
    if (!IS_DTLS(ss) && (sentRealSid || sentFakeSid)) {
6967
0
        return sidMatch;
6968
0
    }
6969
6970
    /* TLS 1.3 (no SID)/DTLS 1.3: The server shouldn't send a session ID. */
6971
195
    return sidBytes->len == 0;
6972
195
}
6973
6974
static SECStatus
6975
ssl_CheckServerRandom(sslSocket *ss)
6976
13.0k
{
6977
    /* Check the ServerHello.random per [RFC 8446 Section 4.1.3].
6978
     *
6979
     * TLS 1.3 clients receiving a ServerHello indicating TLS 1.2 or below
6980
     * MUST check that the last 8 bytes are not equal to either of these
6981
     * values.  TLS 1.2 clients SHOULD also check that the last 8 bytes are
6982
     * not equal to the second value if the ServerHello indicates TLS 1.1 or
6983
     * below.  If a match is found, the client MUST abort the handshake with
6984
     * an "illegal_parameter" alert.
6985
     */
6986
13.0k
    SSL3ProtocolVersion checkVersion =
6987
13.0k
        ss->ssl3.downgradeCheckVersion ? ss->ssl3.downgradeCheckVersion
6988
13.0k
                                       : ss->vrange.max;
6989
6990
13.0k
    if (checkVersion >= SSL_LIBRARY_VERSION_TLS_1_2 &&
6991
13.0k
        checkVersion > ss->version) {
6992
        /* Both sections use the same sentinel region. */
6993
12.8k
        PRUint8 *downgrade_sentinel =
6994
12.8k
            ss->ssl3.hs.server_random +
6995
12.8k
            SSL3_RANDOM_LENGTH - sizeof(tls12_downgrade_random);
6996
6997
12.8k
        if (!PORT_Memcmp(downgrade_sentinel,
6998
12.8k
                         tls12_downgrade_random,
6999
12.8k
                         sizeof(tls12_downgrade_random)) ||
7000
12.8k
            !PORT_Memcmp(downgrade_sentinel,
7001
12.8k
                         tls1_downgrade_random,
7002
12.8k
                         sizeof(tls1_downgrade_random))) {
7003
2
            return SECFailure;
7004
2
        }
7005
12.8k
    }
7006
7007
13.0k
    return SECSuccess;
7008
13.0k
}
7009
7010
/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7011
 * ssl3 ServerHello message.
7012
 * Caller must hold Handshake and RecvBuf locks.
7013
 */
7014
static SECStatus
7015
ssl3_HandleServerHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
7016
12.9k
{
7017
12.9k
    PRUint32 cipher;
7018
12.9k
    int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7019
12.9k
    PRUint32 compression;
7020
12.9k
    SECStatus rv;
7021
12.9k
    SECItem sidBytes = { siBuffer, NULL, 0 };
7022
12.9k
    PRBool isHelloRetry;
7023
12.9k
    SSL3AlertDescription desc = illegal_parameter;
7024
12.9k
    const PRUint8 *savedMsg = b;
7025
12.9k
    const PRUint32 savedLength = length;
7026
7027
12.9k
    SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
7028
12.9k
                SSL_GETPID(), ss->fd));
7029
12.9k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7030
12.9k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7031
7032
12.9k
    if (ss->ssl3.hs.ws != wait_server_hello) {
7033
7
        errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
7034
7
        desc = unexpected_message;
7035
7
        goto alert_loser;
7036
7
    }
7037
7038
    /* clean up anything left from previous handshake. */
7039
12.9k
    if (ss->ssl3.clientCertChain != NULL) {
7040
0
        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
7041
0
        ss->ssl3.clientCertChain = NULL;
7042
0
    }
7043
12.9k
    if (ss->ssl3.clientCertificate != NULL) {
7044
0
        CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7045
0
        ss->ssl3.clientCertificate = NULL;
7046
0
    }
7047
12.9k
    if (ss->ssl3.clientPrivateKey != NULL) {
7048
0
        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7049
0
        ss->ssl3.clientPrivateKey = NULL;
7050
0
    }
7051
    // TODO(djackson) - Bob removed this. Why?
7052
12.9k
    if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL) {
7053
0
        PR_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
7054
0
        ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
7055
0
        ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
7056
0
    }
7057
7058
    /* Note that if the server selects TLS 1.3, this will set the version to TLS
7059
     * 1.2.  We will amend that once all other fields have been read. */
7060
12.9k
    rv = ssl_ClientReadVersion(ss, &b, &length, &ss->version);
7061
12.9k
    if (rv != SECSuccess) {
7062
15
        goto loser; /* alert has been sent */
7063
15
    }
7064
7065
12.9k
    rv = ssl3_ConsumeHandshake(
7066
12.9k
        ss, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
7067
12.9k
    if (rv != SECSuccess) {
7068
25
        goto loser; /* alert has been sent */
7069
25
    }
7070
12.9k
    isHelloRetry = !PORT_Memcmp(ss->ssl3.hs.server_random,
7071
12.9k
                                ssl_hello_retry_random, SSL3_RANDOM_LENGTH);
7072
7073
12.9k
    rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
7074
12.9k
    if (rv != SECSuccess) {
7075
92
        goto loser; /* alert has been sent */
7076
92
    }
7077
12.8k
    if (sidBytes.len > SSL3_SESSIONID_BYTES) {
7078
18
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_0)
7079
4
            desc = decode_error;
7080
18
        goto alert_loser; /* malformed. */
7081
18
    }
7082
7083
    /* Read the cipher suite. */
7084
12.7k
    rv = ssl3_ConsumeHandshakeNumber(ss, &cipher, 2, &b, &length);
7085
12.7k
    if (rv != SECSuccess) {
7086
3
        goto loser; /* alert has been sent */
7087
3
    }
7088
7089
    /* Compression method. */
7090
12.7k
    rv = ssl3_ConsumeHandshakeNumber(ss, &compression, 1, &b, &length);
7091
12.7k
    if (rv != SECSuccess) {
7092
3
        goto loser; /* alert has been sent */
7093
3
    }
7094
12.7k
    if (compression != ssl_compression_null) {
7095
11
        desc = illegal_parameter;
7096
11
        errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7097
11
        goto alert_loser;
7098
11
    }
7099
7100
    /* Parse extensions. */
7101
12.7k
    if (length != 0) {
7102
5.58k
        PRUint32 extensionLength;
7103
5.58k
        rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
7104
5.58k
        if (rv != SECSuccess) {
7105
2
            goto loser; /* alert already sent */
7106
2
        }
7107
5.58k
        if (extensionLength != length) {
7108
10
            desc = decode_error;
7109
10
            goto alert_loser;
7110
10
        }
7111
5.57k
        rv = ssl3_ParseExtensions(ss, &b, &length);
7112
5.57k
        if (rv != SECSuccess) {
7113
41
            goto alert_loser; /* malformed */
7114
41
        }
7115
5.57k
    }
7116
7117
    /* Read supported_versions if present. */
7118
12.7k
    rv = tls13_ClientReadSupportedVersion(ss);
7119
12.7k
    if (rv != SECSuccess) {
7120
26
        goto loser;
7121
26
    }
7122
7123
    /* RFC 9147. 5.2. 
7124
     * DTLS Handshake Message Format states the difference between the computation
7125
     * of the transcript if the version is DTLS1.2 or DTLS1.3.
7126
     *
7127
     * At this moment we are sure which version
7128
     * we are planning to use during the connection, so we can compute the hash. */
7129
12.6k
    rv = ssl3_MaybeUpdateHashWithSavedRecord(ss);
7130
12.6k
    if (rv != SECSuccess) {
7131
0
        goto loser;
7132
0
    }
7133
7134
12.6k
    PORT_Assert(!SSL_ALL_VERSIONS_DISABLED(&ss->vrange));
7135
    /* Check that the version is within the configured range. */
7136
12.6k
    if (ss->vrange.min > ss->version || ss->vrange.max < ss->version) {
7137
16
        desc = (ss->version > SSL_LIBRARY_VERSION_3_0)
7138
16
                   ? protocol_version
7139
16
                   : handshake_failure;
7140
16
        errCode = SSL_ERROR_UNSUPPORTED_VERSION;
7141
16
        goto alert_loser;
7142
16
    }
7143
7144
12.6k
    if (isHelloRetry && ss->ssl3.hs.helloRetry) {
7145
1
        SSL_TRC(3, ("%d: SSL3[%d]: received a second hello_retry_request",
7146
1
                    SSL_GETPID(), ss->fd));
7147
1
        desc = unexpected_message;
7148
1
        errCode = SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST;
7149
1
        goto alert_loser;
7150
1
    }
7151
7152
    /* There are three situations in which the server must pick
7153
     * TLS 1.3.
7154
     *
7155
     * 1. We received HRR
7156
     * 2. We sent early app data
7157
     * 3. ECH was accepted (checked in MaybeHandleEchSignal)
7158
     *
7159
     * If we offered ECH and the server negotiated a lower version,
7160
     * authenticate to the public name for secure disablement.
7161
     *
7162
     */
7163
12.6k
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
7164
12.4k
        if (isHelloRetry || ss->ssl3.hs.helloRetry) {
7165
            /* SSL3_SendAlert() will uncache the SID. */
7166
2
            desc = illegal_parameter;
7167
2
            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7168
2
            goto alert_loser;
7169
2
        }
7170
12.4k
        if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
7171
            /* SSL3_SendAlert() will uncache the SID. */
7172
0
            desc = illegal_parameter;
7173
0
            errCode = SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA;
7174
0
            goto alert_loser;
7175
0
        }
7176
12.4k
    }
7177
7178
    /* Check that the server negotiated the same version as it did
7179
     * in the first handshake. This isn't really the best place for
7180
     * us to be getting this version number, but it's what we have.
7181
     * (1294697). */
7182
12.6k
    if (ss->firstHsDone && (ss->version != ss->ssl3.crSpec->version)) {
7183
1
        desc = protocol_version;
7184
1
        errCode = SSL_ERROR_UNSUPPORTED_VERSION;
7185
1
        goto alert_loser;
7186
1
    }
7187
7188
12.6k
    if (ss->opt.enableHelloDowngradeCheck) {
7189
12.6k
        rv = ssl_CheckServerRandom(ss);
7190
12.6k
        if (rv != SECSuccess) {
7191
2
            desc = illegal_parameter;
7192
2
            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7193
2
            goto alert_loser;
7194
2
        }
7195
12.6k
    }
7196
7197
    /* Finally, now all the version-related checks have passed. */
7198
12.6k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
7199
    /* Update the write cipher spec to match the version. But not after
7200
     * HelloRetryRequest, because cwSpec might be a 0-RTT cipher spec,
7201
     * in which case this is a no-op. */
7202
12.6k
    if (!ss->firstHsDone && !isHelloRetry) {
7203
8.51k
        ssl_GetSpecWriteLock(ss);
7204
8.51k
        ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
7205
8.51k
        ssl_ReleaseSpecWriteLock(ss);
7206
8.51k
    }
7207
7208
    /* Check that the session ID is as expected. */
7209
12.6k
    if (!ssl_CheckServerSessionIdCorrectness(ss, &sidBytes)) {
7210
1
        desc = illegal_parameter;
7211
1
        errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7212
1
        goto alert_loser;
7213
1
    }
7214
7215
    /* Only initialize hashes if this isn't a Hello Retry. */
7216
12.6k
    rv = ssl_ClientSetCipherSuite(ss, ss->version, cipher,
7217
12.6k
                                  !isHelloRetry);
7218
12.6k
    if (rv != SECSuccess) {
7219
42
        desc = illegal_parameter;
7220
42
        errCode = PORT_GetError();
7221
42
        goto alert_loser;
7222
42
    }
7223
7224
12.6k
    dtls_ReceivedFirstMessageInFlight(ss);
7225
7226
12.6k
    if (isHelloRetry) {
7227
78
        rv = tls13_HandleHelloRetryRequest(ss, savedMsg, savedLength);
7228
78
        if (rv != SECSuccess) {
7229
22
            goto loser;
7230
22
        }
7231
56
        return SECSuccess;
7232
78
    }
7233
7234
12.5k
    rv = ssl3_HandleParsedExtensions(ss, ssl_hs_server_hello);
7235
12.5k
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
7236
12.5k
    if (rv != SECSuccess) {
7237
342
        goto alert_loser;
7238
342
    }
7239
7240
12.2k
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_server_hello,
7241
12.2k
                                  savedMsg, savedLength);
7242
12.2k
    if (rv != SECSuccess) {
7243
0
        goto loser;
7244
0
    }
7245
7246
12.2k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
7247
73
        rv = tls13_HandleServerHelloPart2(ss, savedMsg, savedLength);
7248
73
        if (rv != SECSuccess) {
7249
73
            errCode = PORT_GetError();
7250
73
            goto loser;
7251
73
        }
7252
12.1k
    } else {
7253
12.1k
        rv = ssl3_HandleServerHelloPart2(ss, &sidBytes, &errCode);
7254
12.1k
        if (rv != SECSuccess)
7255
2.95k
            goto loser;
7256
12.1k
    }
7257
7258
9.18k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
7259
9.18k
    return SECSuccess;
7260
7261
494
alert_loser:
7262
494
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
7263
7264
3.71k
loser:
7265
    /* Clean up the temporary pointer to the handshake buffer. */
7266
3.71k
    ss->xtnData.signedCertTimestamps.len = 0;
7267
3.71k
    ssl_MapLowLevelError(errCode);
7268
3.71k
    return SECFailure;
7269
494
}
7270
7271
static SECStatus
7272
ssl3_UnwrapMasterSecretClient(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
7273
0
{
7274
0
    PK11SlotInfo *slot;
7275
0
    PK11SymKey *wrapKey;
7276
0
    CK_FLAGS keyFlags = 0;
7277
0
    SECItem wrappedMS = {
7278
0
        siBuffer,
7279
0
        sid->u.ssl3.keys.wrapped_master_secret,
7280
0
        sid->u.ssl3.keys.wrapped_master_secret_len
7281
0
    };
7282
7283
    /* unwrap master secret */
7284
0
    slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
7285
0
                             sid->u.ssl3.masterSlotID);
7286
0
    if (slot == NULL) {
7287
0
        return SECFailure;
7288
0
    }
7289
0
    if (!PK11_IsPresent(slot)) {
7290
0
        PK11_FreeSlot(slot);
7291
0
        return SECFailure;
7292
0
    }
7293
0
    wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
7294
0
                              sid->u.ssl3.masterWrapMech,
7295
0
                              sid->u.ssl3.masterWrapSeries,
7296
0
                              ss->pkcs11PinArg);
7297
0
    PK11_FreeSlot(slot);
7298
0
    if (wrapKey == NULL) {
7299
0
        return SECFailure;
7300
0
    }
7301
7302
0
    if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
7303
0
        keyFlags = CKF_SIGN | CKF_VERIFY;
7304
0
    }
7305
7306
0
    *ms = PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
7307
0
                                     NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
7308
0
                                     CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH, keyFlags);
7309
0
    PK11_FreeSymKey(wrapKey);
7310
0
    if (!*ms) {
7311
0
        return SECFailure;
7312
0
    }
7313
0
    return SECSuccess;
7314
0
}
7315
7316
static SECStatus
7317
ssl3_HandleServerHelloPart2(sslSocket *ss, const SECItem *sidBytes,
7318
                            int *retErrCode)
7319
12.1k
{
7320
12.1k
    SSL3AlertDescription desc = handshake_failure;
7321
12.1k
    int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7322
12.1k
    SECStatus rv;
7323
12.1k
    PRBool sid_match;
7324
12.1k
    sslSessionID *sid = ss->sec.ci.sid;
7325
7326
12.1k
    if ((ss->opt.requireSafeNegotiation ||
7327
12.1k
         (ss->firstHsDone && (ss->peerRequestedProtection ||
7328
4.06k
                              ss->opt.enableRenegotiation ==
7329
4.06k
                                  SSL_RENEGOTIATE_REQUIRES_XTN))) &&
7330
12.1k
        !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7331
2.95k
        desc = handshake_failure;
7332
2.95k
        errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
7333
2.95k
                                  : SSL_ERROR_UNSAFE_NEGOTIATION;
7334
2.95k
        goto alert_loser;
7335
2.95k
    }
7336
7337
    /* Any errors after this point are not "malformed" errors. */
7338
9.18k
    desc = handshake_failure;
7339
7340
    /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
7341
     * key exchange algorithm. */
7342
9.18k
    rv = ssl3_SetupBothPendingCipherSpecs(ss);
7343
9.18k
    if (rv != SECSuccess) {
7344
0
        goto alert_loser; /* error code is set. */
7345
0
    }
7346
7347
    /* We may or may not have sent a session id, we may get one back or
7348
     * not and if so it may match the one we sent.
7349
     * Attempt to restore the master secret to see if this is so...
7350
     * Don't consider failure to find a matching SID an error.
7351
     */
7352
9.18k
    sid_match = (PRBool)(sidBytes->len > 0 &&
7353
9.18k
                         sidBytes->len ==
7354
4.46k
                             sid->u.ssl3.sessionIDLength &&
7355
9.18k
                         !PORT_Memcmp(sid->u.ssl3.sessionID,
7356
0
                                      sidBytes->data, sidBytes->len));
7357
7358
9.18k
    if (sid_match) {
7359
0
        if (sid->version != ss->version ||
7360
0
            sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
7361
0
            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7362
0
            goto alert_loser;
7363
0
        }
7364
0
        do {
7365
0
            PK11SymKey *masterSecret;
7366
7367
            /* [draft-ietf-tls-session-hash-06; Section 5.3]
7368
             *
7369
             * o  If the original session did not use the "extended_master_secret"
7370
             *    extension but the new ServerHello contains the extension, the
7371
             *    client MUST abort the handshake.
7372
             */
7373
0
            if (!sid->u.ssl3.keys.extendedMasterSecretUsed &&
7374
0
                ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
7375
0
                errCode = SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET;
7376
0
                goto alert_loser;
7377
0
            }
7378
7379
            /*
7380
             *   o  If the original session used an extended master secret but the new
7381
             *      ServerHello does not contain the "extended_master_secret"
7382
             *      extension, the client SHOULD abort the handshake.
7383
             *
7384
             * TODO(ekr@rtfm.com): Add option to refuse to resume when EMS is not
7385
             * used at all (bug 1176526).
7386
             */
7387
0
            if (sid->u.ssl3.keys.extendedMasterSecretUsed &&
7388
0
                !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
7389
0
                errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
7390
0
                goto alert_loser;
7391
0
            }
7392
7393
0
            ss->sec.authType = sid->authType;
7394
0
            ss->sec.authKeyBits = sid->authKeyBits;
7395
0
            ss->sec.keaType = sid->keaType;
7396
0
            ss->sec.keaKeyBits = sid->keaKeyBits;
7397
0
            ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
7398
0
            ss->sec.signatureScheme = sid->sigScheme;
7399
7400
0
            rv = ssl3_UnwrapMasterSecretClient(ss, sid, &masterSecret);
7401
0
            if (rv != SECSuccess) {
7402
0
                break; /* not considered an error */
7403
0
            }
7404
7405
            /* Got a Match */
7406
0
            SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_hits);
7407
7408
            /* If we sent a session ticket, then this is a stateless resume. */
7409
0
            if (ss->xtnData.sentSessionTicketInClientHello)
7410
0
                SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_stateless_resumes);
7411
7412
0
            if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
7413
0
                ss->ssl3.hs.ws = wait_new_session_ticket;
7414
0
            else
7415
0
                ss->ssl3.hs.ws = wait_change_cipher;
7416
7417
0
            ss->ssl3.hs.isResuming = PR_TRUE;
7418
7419
            /* copy the peer cert from the SID */
7420
0
            if (sid->peerCert != NULL) {
7421
0
                ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
7422
0
            }
7423
7424
            /* We are re-using the old MS, so no need to derive again. */
7425
0
            rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE);
7426
0
            if (rv != SECSuccess) {
7427
0
                goto alert_loser; /* err code was set */
7428
0
            }
7429
0
            return SECSuccess;
7430
0
        } while (0);
7431
0
    }
7432
7433
9.18k
    if (sid_match)
7434
0
        SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_not_ok);
7435
9.18k
    else
7436
9.18k
        SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_misses);
7437
7438
    /* We tried to resume a 1.3 session but the server negotiated 1.2. */
7439
9.18k
    if (ss->statelessResume) {
7440
0
        PORT_Assert(sid->version == SSL_LIBRARY_VERSION_TLS_1_3);
7441
0
        PORT_Assert(ss->ssl3.hs.currentSecret);
7442
7443
        /* Reset resumption state, only used by 1.3 code. */
7444
0
        ss->statelessResume = PR_FALSE;
7445
7446
        /* Clear TLS 1.3 early data traffic key. */
7447
0
        PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
7448
0
        ss->ssl3.hs.currentSecret = NULL;
7449
0
    }
7450
7451
    /* throw the old one away */
7452
9.18k
    sid->u.ssl3.keys.resumable = PR_FALSE;
7453
9.18k
    ssl_UncacheSessionID(ss);
7454
9.18k
    ssl_FreeSID(sid);
7455
7456
    /* get a new sid */
7457
9.18k
    ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
7458
9.18k
    if (sid == NULL) {
7459
0
        goto alert_loser; /* memory error is set. */
7460
0
    }
7461
7462
9.18k
    sid->version = ss->version;
7463
9.18k
    sid->u.ssl3.sessionIDLength = sidBytes->len;
7464
9.18k
    if (sidBytes->len > 0) {
7465
4.46k
        PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len);
7466
4.46k
    }
7467
7468
9.18k
    sid->u.ssl3.keys.extendedMasterSecretUsed =
7469
9.18k
        ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
7470
7471
    /* Copy Signed Certificate Timestamps, if any. */
7472
9.18k
    if (ss->xtnData.signedCertTimestamps.len) {
7473
0
        rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps,
7474
0
                              &ss->xtnData.signedCertTimestamps);
7475
0
        ss->xtnData.signedCertTimestamps.len = 0;
7476
0
        if (rv != SECSuccess)
7477
0
            goto loser;
7478
0
    }
7479
7480
9.18k
    ss->ssl3.hs.isResuming = PR_FALSE;
7481
9.18k
    if (ss->ssl3.hs.kea_def->authKeyType != ssl_auth_null) {
7482
        /* All current cipher suites other than those with ssl_auth_null (i.e.,
7483
         * (EC)DH_anon_* suites) require a certificate, so use that signal. */
7484
9.18k
        ss->ssl3.hs.ws = wait_server_cert;
7485
9.18k
    } else {
7486
        /* All the remaining cipher suites must be (EC)DH_anon_* and so
7487
         * must be ephemeral. Note, if we ever add PSK this might
7488
         * change. */
7489
0
        PORT_Assert(ss->ssl3.hs.kea_def->ephemeral);
7490
0
        ss->ssl3.hs.ws = wait_server_key;
7491
0
    }
7492
9.18k
    return SECSuccess;
7493
7494
2.95k
alert_loser:
7495
2.95k
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
7496
7497
2.95k
loser:
7498
2.95k
    *retErrCode = errCode;
7499
2.95k
    return SECFailure;
7500
2.95k
}
7501
7502
static SECStatus
7503
ssl_HandleDHServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
7504
859
{
7505
859
    SECStatus rv;
7506
859
    int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
7507
859
    SSL3AlertDescription desc = illegal_parameter;
7508
859
    SSLHashType hashAlg;
7509
859
    PRBool isTLS = ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0;
7510
859
    SSLSignatureScheme sigScheme;
7511
7512
859
    SECItem dh_p = { siBuffer, NULL, 0 };
7513
859
    SECItem dh_g = { siBuffer, NULL, 0 };
7514
859
    SECItem dh_Ys = { siBuffer, NULL, 0 };
7515
859
    unsigned dh_p_bits;
7516
859
    unsigned dh_g_bits;
7517
859
    PRInt32 minDH = 0;
7518
859
    PRInt32 optval;
7519
7520
859
    SSL3Hashes hashes;
7521
859
    SECItem signature = { siBuffer, NULL, 0 };
7522
859
    PLArenaPool *arena = NULL;
7523
859
    SECKEYPublicKey *peerKey = NULL;
7524
7525
859
    rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
7526
859
    if (rv != SECSuccess) {
7527
10
        goto loser; /* malformed. */
7528
10
    }
7529
849
    rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS, &optval);
7530
849
    if ((rv == SECSuccess) && (optval & NSS_KEY_SIZE_POLICY_SSL_FLAG)) {
7531
849
        (void)NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH);
7532
849
    }
7533
7534
849
    if (minDH <= 0) {
7535
0
        minDH = SSL_DH_MIN_P_BITS;
7536
0
    }
7537
849
    dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p);
7538
849
    if (dh_p_bits < (unsigned)minDH) {
7539
7
        errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
7540
7
        goto alert_loser;
7541
7
    }
7542
842
    if (dh_p_bits > SSL_MAX_DH_KEY_BITS) {
7543
7
        errCode = SSL_ERROR_DH_KEY_TOO_LONG;
7544
7
        goto alert_loser;
7545
7
    }
7546
835
    rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
7547
835
    if (rv != SECSuccess) {
7548
26
        goto loser; /* malformed. */
7549
26
    }
7550
    /* Abort if dh_g is 0, 1, or obviously too big. */
7551
809
    dh_g_bits = SECKEY_BigIntegerBitLength(&dh_g);
7552
809
    if (dh_g_bits > dh_p_bits || dh_g_bits <= 1) {
7553
4
        goto alert_loser;
7554
4
    }
7555
805
    if (ss->opt.requireDHENamedGroups) {
7556
        /* If we're doing named groups, make sure it's good. */
7557
795
        rv = ssl_ValidateDHENamedGroup(ss, &dh_p, &dh_g, NULL, NULL);
7558
795
        if (rv != SECSuccess) {
7559
789
            errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
7560
789
            goto alert_loser;
7561
789
        }
7562
795
    }
7563
7564
16
    rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
7565
16
    if (rv != SECSuccess) {
7566
4
        goto loser; /* malformed. */
7567
4
    }
7568
12
    if (!ssl_IsValidDHEShare(&dh_p, &dh_Ys)) {
7569
2
        errCode = SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE;
7570
2
        goto alert_loser;
7571
2
    }
7572
7573
10
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
7574
4
        rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
7575
4
        if (rv != SECSuccess) {
7576
0
            goto loser; /* alert already sent */
7577
0
        }
7578
4
        rv = ssl_CheckSignatureSchemeConsistency(
7579
4
            ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo);
7580
4
        if (rv != SECSuccess) {
7581
1
            goto alert_loser;
7582
1
        }
7583
3
        hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
7584
6
    } else {
7585
        /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
7586
6
        hashAlg = ssl_hash_none;
7587
6
        sigScheme = ssl_sig_none;
7588
6
    }
7589
9
    rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
7590
9
    if (rv != SECSuccess) {
7591
1
        goto loser; /* malformed. */
7592
1
    }
7593
8
    if (length != 0) {
7594
1
        if (isTLS) {
7595
1
            desc = decode_error;
7596
1
        }
7597
1
        goto alert_loser; /* malformed. */
7598
1
    }
7599
7600
7
    PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
7601
7
    PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
7602
7
    PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
7603
7604
    /* failures after this point are not malformed handshakes. */
7605
    /* TLS: send decrypt_error if signature failed. */
7606
7
    desc = isTLS ? decrypt_error : handshake_failure;
7607
7608
    /*
7609
     * Check to make sure the hash is signed by right guy.
7610
     */
7611
7
    rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
7612
7
                               dh_p, dh_g, dh_Ys, PR_FALSE /* padY */);
7613
7
    if (rv != SECSuccess) {
7614
0
        errCode =
7615
0
            ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7616
0
        goto alert_loser;
7617
0
    }
7618
7
    rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signature);
7619
7
    if (rv != SECSuccess) {
7620
0
        errCode =
7621
0
            ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7622
0
        goto alert_loser;
7623
0
    }
7624
7625
    /*
7626
     * we really need to build a new key here because we can no longer
7627
     * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
7628
     * pkcs11 slots and ID's.
7629
     */
7630
7
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7631
7
    if (arena == NULL) {
7632
0
        errCode = SEC_ERROR_NO_MEMORY;
7633
0
        goto loser;
7634
0
    }
7635
7636
7
    peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
7637
7
    if (peerKey == NULL) {
7638
0
        errCode = SEC_ERROR_NO_MEMORY;
7639
0
        goto loser;
7640
0
    }
7641
7642
7
    peerKey->arena = arena;
7643
7
    peerKey->keyType = dhKey;
7644
7
    peerKey->pkcs11Slot = NULL;
7645
7
    peerKey->pkcs11ID = CK_INVALID_HANDLE;
7646
7647
7
    if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) ||
7648
7
        SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) ||
7649
7
        SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) {
7650
0
        errCode = SEC_ERROR_NO_MEMORY;
7651
0
        goto loser;
7652
0
    }
7653
7
    ss->sec.peerKey = peerKey;
7654
7
    return SECSuccess;
7655
7656
811
alert_loser:
7657
811
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
7658
852
loser:
7659
852
    if (arena) {
7660
0
        PORT_FreeArena(arena, PR_FALSE);
7661
0
    }
7662
852
    PORT_SetError(ssl_MapLowLevelError(errCode));
7663
852
    return SECFailure;
7664
811
}
7665
7666
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
7667
 * complete ssl3 ServerKeyExchange message.
7668
 * Caller must hold Handshake and RecvBuf locks.
7669
 */
7670
static SECStatus
7671
ssl3_HandleServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
7672
3.01k
{
7673
3.01k
    SECStatus rv;
7674
7675
3.01k
    SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
7676
3.01k
                SSL_GETPID(), ss->fd));
7677
3.01k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7678
3.01k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7679
7680
3.01k
    if (ss->ssl3.hs.ws != wait_server_key) {
7681
6
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
7682
6
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
7683
6
        return SECFailure;
7684
6
    }
7685
7686
3.01k
    switch (ss->ssl3.hs.kea_def->exchKeyType) {
7687
859
        case ssl_kea_dh:
7688
859
            rv = ssl_HandleDHServerKeyExchange(ss, b, length);
7689
859
            break;
7690
7691
2.15k
        case ssl_kea_ecdh:
7692
2.15k
            rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
7693
2.15k
            break;
7694
7695
0
        default:
7696
0
            SSL3_SendAlert(ss, alert_fatal, handshake_failure);
7697
0
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
7698
0
            rv = SECFailure;
7699
0
            break;
7700
3.01k
    }
7701
7702
3.01k
    if (rv == SECSuccess) {
7703
2.12k
        ss->ssl3.hs.ws = wait_cert_request;
7704
2.12k
    }
7705
    /* All Handle*ServerKeyExchange functions set the error code. */
7706
3.01k
    return rv;
7707
3.01k
}
7708
7709
typedef struct dnameNode {
7710
    struct dnameNode *next;
7711
    SECItem name;
7712
} dnameNode;
7713
7714
/*
7715
 * Parse the ca_list structure in a CertificateRequest.
7716
 *
7717
 * Called from:
7718
 * ssl3_HandleCertificateRequest
7719
 * tls13_HandleCertificateRequest
7720
 */
7721
SECStatus
7722
ssl3_ParseCertificateRequestCAs(sslSocket *ss, PRUint8 **b, PRUint32 *length,
7723
                                CERTDistNames *ca_list)
7724
157
{
7725
157
    PRUint32 remaining;
7726
157
    int nnames = 0;
7727
157
    dnameNode *node;
7728
157
    SECStatus rv;
7729
157
    int i;
7730
7731
157
    rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 2, b, length);
7732
157
    if (rv != SECSuccess)
7733
17
        return SECFailure; /* malformed, alert has been sent */
7734
7735
140
    if (remaining > *length)
7736
76
        goto alert_loser;
7737
7738
64
    ca_list->head = node = PORT_ArenaZNew(ca_list->arena, dnameNode);
7739
64
    if (node == NULL)
7740
0
        goto no_mem;
7741
7742
571
    while (remaining > 0) {
7743
546
        PRUint32 len;
7744
7745
546
        if (remaining < 2)
7746
1
            goto alert_loser; /* malformed */
7747
7748
545
        rv = ssl3_ConsumeHandshakeNumber(ss, &len, 2, b, length);
7749
545
        if (rv != SECSuccess)
7750
0
            return SECFailure; /* malformed, alert has been sent */
7751
545
        if (len == 0 || remaining < len + 2)
7752
29
            goto alert_loser; /* malformed */
7753
7754
516
        remaining -= 2;
7755
516
        if (SECITEM_MakeItem(ca_list->arena, &node->name, *b, len) != SECSuccess) {
7756
0
            goto no_mem;
7757
0
        }
7758
516
        node->name.len = len;
7759
516
        *b += len;
7760
516
        *length -= len;
7761
516
        remaining -= len;
7762
516
        nnames++;
7763
516
        if (remaining <= 0)
7764
9
            break; /* success */
7765
7766
507
        node->next = PORT_ArenaZNew(ca_list->arena, dnameNode);
7767
507
        node = node->next;
7768
507
        if (node == NULL)
7769
0
            goto no_mem;
7770
507
    }
7771
7772
34
    ca_list->nnames = nnames;
7773
34
    ca_list->names = PORT_ArenaNewArray(ca_list->arena, SECItem, nnames);
7774
34
    if (nnames > 0 && ca_list->names == NULL)
7775
0
        goto no_mem;
7776
7777
34
    for (i = 0, node = (dnameNode *)ca_list->head;
7778
382
         i < nnames;
7779
348
         i++, node = node->next) {
7780
348
        ca_list->names[i] = node->name;
7781
348
    }
7782
7783
34
    return SECSuccess;
7784
7785
0
no_mem:
7786
0
    return SECFailure;
7787
7788
106
alert_loser:
7789
106
    (void)SSL3_SendAlert(ss, alert_fatal,
7790
106
                         ss->version < SSL_LIBRARY_VERSION_TLS_1_0 ? illegal_parameter
7791
106
                                                                   : decode_error);
7792
106
    PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
7793
106
    return SECFailure;
7794
34
}
7795
7796
SECStatus
7797
ssl_ParseSignatureSchemes(const sslSocket *ss, PLArenaPool *arena,
7798
                          SSLSignatureScheme **schemesOut,
7799
                          unsigned int *numSchemesOut,
7800
                          unsigned char **b, unsigned int *len)
7801
122
{
7802
122
    SECStatus rv;
7803
122
    SECItem buf;
7804
122
    SSLSignatureScheme *schemes = NULL;
7805
122
    unsigned int numSupported = 0;
7806
122
    unsigned int numRemaining = 0;
7807
122
    unsigned int max;
7808
7809
122
    rv = ssl3_ExtConsumeHandshakeVariable(ss, &buf, 2, b, len);
7810
122
    if (rv != SECSuccess) {
7811
1
        return SECFailure;
7812
1
    }
7813
    /* An odd-length value is invalid. */
7814
121
    if ((buf.len & 1) != 0) {
7815
1
        ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
7816
1
        return SECFailure;
7817
1
    }
7818
7819
    /* Let the caller decide whether to alert here. */
7820
120
    if (buf.len == 0) {
7821
1
        goto done;
7822
1
    }
7823
7824
    /* Limit the number of schemes we read. */
7825
119
    numRemaining = buf.len / 2;
7826
119
    max = PR_MIN(numRemaining, MAX_SIGNATURE_SCHEMES);
7827
7828
119
    if (arena) {
7829
119
        schemes = PORT_ArenaZNewArray(arena, SSLSignatureScheme, max);
7830
119
    } else {
7831
0
        schemes = PORT_ZNewArray(SSLSignatureScheme, max);
7832
0
    }
7833
119
    if (!schemes) {
7834
0
        ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
7835
0
        return SECFailure;
7836
0
    }
7837
7838
10.8k
    for (; numRemaining && numSupported < MAX_SIGNATURE_SCHEMES; --numRemaining) {
7839
10.7k
        PRUint32 tmp;
7840
10.7k
        rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2, &buf.data, &buf.len);
7841
10.7k
        if (rv != SECSuccess) {
7842
0
            PORT_Assert(0);
7843
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
7844
0
            return SECFailure;
7845
0
        }
7846
10.7k
        if (ssl_SignatureSchemeValid((SSLSignatureScheme)tmp, SEC_OID_UNKNOWN,
7847
10.7k
                                     (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)) {
7848
717
            ;
7849
717
            schemes[numSupported++] = (SSLSignatureScheme)tmp;
7850
717
        }
7851
10.7k
    }
7852
7853
119
    if (!numSupported) {
7854
8
        if (!arena) {
7855
0
            PORT_Free(schemes);
7856
0
        }
7857
8
        schemes = NULL;
7858
8
    }
7859
7860
120
done:
7861
120
    *schemesOut = schemes;
7862
120
    *numSchemesOut = numSupported;
7863
120
    return SECSuccess;
7864
119
}
7865
7866
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
7867
 * a complete ssl3 Certificate Request message.
7868
 * Caller must hold Handshake and RecvBuf locks.
7869
 */
7870
static SECStatus
7871
ssl3_HandleCertificateRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
7872
173
{
7873
173
    PLArenaPool *arena = NULL;
7874
173
    PRBool isTLS = PR_FALSE;
7875
173
    PRBool isTLS12 = PR_FALSE;
7876
173
    int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
7877
173
    SECStatus rv;
7878
173
    SSL3AlertDescription desc = illegal_parameter;
7879
173
    SECItem cert_types = { siBuffer, NULL, 0 };
7880
173
    SSLSignatureScheme *signatureSchemes = NULL;
7881
173
    unsigned int signatureSchemeCount = 0;
7882
173
    CERTDistNames ca_list;
7883
7884
173
    SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
7885
173
                SSL_GETPID(), ss->fd));
7886
173
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7887
173
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7888
7889
173
    if (ss->ssl3.hs.ws != wait_cert_request) {
7890
4
        desc = unexpected_message;
7891
4
        errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
7892
4
        goto alert_loser;
7893
4
    }
7894
7895
169
    PORT_Assert(ss->ssl3.clientCertChain == NULL);
7896
169
    PORT_Assert(ss->ssl3.clientCertificate == NULL);
7897
169
    PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
7898
7899
169
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
7900
169
    isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
7901
169
    rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
7902
169
    if (rv != SECSuccess)
7903
1
        goto loser; /* malformed, alert has been sent */
7904
7905
168
    arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7906
168
    if (arena == NULL)
7907
0
        goto no_mem;
7908
7909
168
    if (isTLS12) {
7910
122
        rv = ssl_ParseSignatureSchemes(ss, arena,
7911
122
                                       &signatureSchemes,
7912
122
                                       &signatureSchemeCount,
7913
122
                                       &b, &length);
7914
122
        if (rv != SECSuccess) {
7915
2
            PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
7916
2
            goto loser; /* malformed, alert has been sent */
7917
2
        }
7918
120
        if (signatureSchemeCount == 0) {
7919
9
            errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
7920
9
            desc = handshake_failure;
7921
9
            goto alert_loser;
7922
9
        }
7923
120
    }
7924
7925
157
    rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, &ca_list);
7926
157
    if (rv != SECSuccess)
7927
123
        goto done; /* alert sent in ssl3_ParseCertificateRequestCAs */
7928
7929
34
    if (length != 0)
7930
18
        goto alert_loser; /* malformed */
7931
7932
16
    ss->ssl3.hs.ws = wait_hello_done;
7933
7934
16
    rv = ssl3_BeginHandleCertificateRequest(ss, signatureSchemes,
7935
16
                                            signatureSchemeCount, &ca_list);
7936
16
    if (rv != SECSuccess) {
7937
0
        PORT_Assert(0);
7938
0
        errCode = SEC_ERROR_LIBRARY_FAILURE;
7939
0
        desc = internal_error;
7940
0
        goto alert_loser;
7941
0
    }
7942
16
    goto done;
7943
7944
16
no_mem:
7945
0
    rv = SECFailure;
7946
0
    PORT_SetError(SEC_ERROR_NO_MEMORY);
7947
0
    goto done;
7948
7949
31
alert_loser:
7950
31
    if (isTLS && desc == illegal_parameter)
7951
18
        desc = decode_error;
7952
31
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
7953
34
loser:
7954
34
    PORT_SetError(errCode);
7955
34
    rv = SECFailure;
7956
173
done:
7957
173
    if (arena != NULL)
7958
168
        PORT_FreeArena(arena, PR_FALSE);
7959
173
    return rv;
7960
34
}
7961
7962
static void
7963
ssl3_ClientAuthCallbackOutcome(sslSocket *ss, SECStatus outcome)
7964
16
{
7965
16
    SECStatus rv;
7966
16
    switch (outcome) {
7967
0
        case SECSuccess:
7968
            /* check what the callback function returned */
7969
0
            if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
7970
                /* we are missing either the key or cert */
7971
0
                goto send_no_certificate;
7972
0
            }
7973
            /* Setting ssl3.clientCertChain non-NULL will cause
7974
             * ssl3_HandleServerHelloDone to call SendCertificate.
7975
             */
7976
0
            ss->ssl3.clientCertChain = CERT_CertChainFromCert(
7977
0
                ss->ssl3.clientCertificate,
7978
0
                certUsageSSLClient, PR_FALSE);
7979
0
            if (ss->ssl3.clientCertChain == NULL) {
7980
0
                goto send_no_certificate;
7981
0
            }
7982
0
            if (ss->ssl3.hs.hashType == handshake_hash_record ||
7983
0
                ss->ssl3.hs.hashType == handshake_hash_single) {
7984
0
                rv = ssl_PickClientSignatureScheme(ss,
7985
0
                                                   ss->ssl3.clientCertificate,
7986
0
                                                   ss->ssl3.clientPrivateKey,
7987
0
                                                   ss->ssl3.hs.clientAuthSignatureSchemes,
7988
0
                                                   ss->ssl3.hs.clientAuthSignatureSchemesLen,
7989
0
                                                   &ss->ssl3.hs.signatureScheme);
7990
0
                if (rv != SECSuccess) {
7991
                    /* This should only happen if our schemes changed or
7992
                     * if an RSA-PSS cert was selected, but the token
7993
                     * does not support PSS schemes.
7994
                     */
7995
0
                    goto send_no_certificate;
7996
0
                }
7997
0
            }
7998
0
            break;
7999
8000
16
        case SECFailure:
8001
16
        default:
8002
16
        send_no_certificate:
8003
16
            CERT_DestroyCertificate(ss->ssl3.clientCertificate);
8004
16
            SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
8005
16
            ss->ssl3.clientCertificate = NULL;
8006
16
            ss->ssl3.clientPrivateKey = NULL;
8007
16
            if (ss->ssl3.clientCertChain) {
8008
0
                CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
8009
0
                ss->ssl3.clientCertChain = NULL;
8010
0
            }
8011
8012
16
            if (ss->version > SSL_LIBRARY_VERSION_3_0) {
8013
16
                ss->ssl3.sendEmptyCert = PR_TRUE;
8014
16
            } else {
8015
0
                (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
8016
0
            }
8017
16
            break;
8018
16
    }
8019
8020
    /* Release the cached parameters */
8021
16
    PORT_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
8022
16
    ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
8023
16
    ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
8024
16
}
8025
8026
SECStatus
8027
ssl3_BeginHandleCertificateRequest(sslSocket *ss,
8028
                                   const SSLSignatureScheme *signatureSchemes,
8029
                                   unsigned int signatureSchemeCount,
8030
                                   CERTDistNames *ca_list)
8031
16
{
8032
16
    SECStatus rv;
8033
8034
16
    PR_ASSERT(!ss->ssl3.hs.clientCertificatePending);
8035
8036
    /* Should not send a client cert when (non-GREASE) ECH is rejected. */
8037
16
    if (ss->ssl3.hs.echHpkeCtx && !ss->ssl3.hs.echAccepted) {
8038
0
        PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn));
8039
0
        rv = SECFailure;
8040
16
    } else if (ss->getClientAuthData != NULL) {
8041
0
        PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
8042
0
                    ssl_preinfo_all);
8043
0
        PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
8044
0
        PORT_Assert(ss->ssl3.clientCertificate == NULL);
8045
0
        PORT_Assert(ss->ssl3.clientCertChain == NULL);
8046
8047
        /* Previously cached parameters should be empty */
8048
0
        PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemes == NULL);
8049
0
        PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemesLen == 0);
8050
        /*
8051
         * Peer signatures are only available while in the context of
8052
         * of a getClientAuthData callback. It is required for proper
8053
         * functioning of SSL_CertIsUsable and SSL_FilterClientCertListBySocket
8054
         * Calling these functions outside the context of a getClientAuthData
8055
         * callback will result in no filtering.*/
8056
8057
0
        ss->ssl3.hs.clientAuthSignatureSchemes = PORT_ZNewArray(SSLSignatureScheme, signatureSchemeCount);
8058
0
        PORT_Memcpy(ss->ssl3.hs.clientAuthSignatureSchemes, signatureSchemes, signatureSchemeCount * sizeof(SSLSignatureScheme));
8059
0
        ss->ssl3.hs.clientAuthSignatureSchemesLen = signatureSchemeCount;
8060
8061
0
        rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
8062
0
                                                 ss->fd, ca_list,
8063
0
                                                 &ss->ssl3.clientCertificate,
8064
0
                                                 &ss->ssl3.clientPrivateKey);
8065
16
    } else {
8066
16
        rv = SECFailure; /* force it to send a no_certificate alert */
8067
16
    }
8068
8069
16
    if (rv == SECWouldBlock) {
8070
        /* getClientAuthData needs more time (e.g. for user interaction) */
8071
8072
        /* The out parameters should not have changed. */
8073
0
        PORT_Assert(ss->ssl3.clientCertificate == NULL);
8074
0
        PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
8075
8076
        /* Mark the handshake as blocked */
8077
0
        ss->ssl3.hs.clientCertificatePending = PR_TRUE;
8078
8079
0
        rv = SECSuccess;
8080
16
    } else {
8081
        /* getClientAuthData returned SECSuccess or SECFailure immediately, handle accordingly */
8082
16
        ssl3_ClientAuthCallbackOutcome(ss, rv);
8083
16
        rv = SECSuccess;
8084
16
    }
8085
16
    return rv;
8086
16
}
8087
8088
/* Invoked by the application when client certificate selection is complete */
8089
SECStatus
8090
ssl3_ClientCertCallbackComplete(sslSocket *ss, SECStatus outcome, SECKEYPrivateKey *clientPrivateKey, CERTCertificate *clientCertificate)
8091
0
{
8092
0
    PORT_Assert(ss->ssl3.hs.clientCertificatePending);
8093
0
    ss->ssl3.hs.clientCertificatePending = PR_FALSE;
8094
8095
0
    ss->ssl3.clientCertificate = clientCertificate;
8096
0
    ss->ssl3.clientPrivateKey = clientPrivateKey;
8097
8098
0
    ssl3_ClientAuthCallbackOutcome(ss, outcome);
8099
8100
    /* Continue the handshake */
8101
0
    PORT_Assert(ss->ssl3.hs.restartTarget);
8102
0
    if (!ss->ssl3.hs.restartTarget) {
8103
0
        FATAL_ERROR(ss, PR_INVALID_STATE_ERROR, internal_error);
8104
0
        return SECFailure;
8105
0
    }
8106
0
    sslRestartTarget target = ss->ssl3.hs.restartTarget;
8107
0
    ss->ssl3.hs.restartTarget = NULL;
8108
0
    return target(ss);
8109
0
}
8110
8111
static SECStatus
8112
ssl3_CheckFalseStart(sslSocket *ss)
8113
379
{
8114
379
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8115
379
    PORT_Assert(!ss->ssl3.hs.authCertificatePending);
8116
379
    PORT_Assert(!ss->ssl3.hs.canFalseStart);
8117
8118
379
    if (!ss->canFalseStartCallback) {
8119
0
        SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start",
8120
0
                    SSL_GETPID(), ss->fd));
8121
379
    } else {
8122
379
        SECStatus rv;
8123
8124
379
        rv = ssl_CheckServerRandom(ss);
8125
379
        if (rv != SECSuccess) {
8126
0
            SSL_TRC(3, ("%d: SSL[%d]: no false start due to possible downgrade",
8127
0
                        SSL_GETPID(), ss->fd));
8128
0
            goto no_false_start;
8129
0
        }
8130
8131
        /* An attacker can control the selected ciphersuite so we only wish to
8132
         * do False Start in the case that the selected ciphersuite is
8133
         * sufficiently strong that the attack can gain no advantage.
8134
         * Therefore we always require an 80-bit cipher. */
8135
379
        ssl_GetSpecReadLock(ss);
8136
379
        PRBool weakCipher = ss->ssl3.cwSpec->cipherDef->secret_key_size < 10;
8137
379
        ssl_ReleaseSpecReadLock(ss);
8138
379
        if (weakCipher) {
8139
55
            SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher",
8140
55
                        SSL_GETPID(), ss->fd));
8141
55
            goto no_false_start;
8142
55
        }
8143
8144
324
        if (ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn)) {
8145
0
            SSL_TRC(3, ("%d: SSL[%d]: no false start due to lower version after ECH",
8146
0
                        SSL_GETPID(), ss->fd));
8147
0
            goto no_false_start;
8148
0
        }
8149
8150
324
        PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
8151
324
                    ssl_preinfo_all);
8152
324
        rv = (ss->canFalseStartCallback)(ss->fd,
8153
324
                                         ss->canFalseStartCallbackData,
8154
324
                                         &ss->ssl3.hs.canFalseStart);
8155
324
        if (rv == SECSuccess) {
8156
324
            SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s",
8157
324
                        SSL_GETPID(), ss->fd,
8158
324
                        ss->ssl3.hs.canFalseStart ? "TRUE"
8159
324
                                                  : "FALSE"));
8160
324
        } else {
8161
0
            SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)",
8162
0
                        SSL_GETPID(), ss->fd,
8163
0
                        PR_ErrorToName(PR_GetError())));
8164
0
        }
8165
324
        return rv;
8166
324
    }
8167
8168
55
no_false_start:
8169
55
    ss->ssl3.hs.canFalseStart = PR_FALSE;
8170
55
    return SECSuccess;
8171
379
}
8172
8173
PRBool
8174
ssl3_WaitingForServerSecondRound(sslSocket *ss)
8175
5.26k
{
8176
5.26k
    PRBool result;
8177
8178
5.26k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8179
8180
5.26k
    switch (ss->ssl3.hs.ws) {
8181
0
        case wait_new_session_ticket:
8182
4.99k
        case wait_change_cipher:
8183
5.26k
        case wait_finished:
8184
5.26k
            result = PR_TRUE;
8185
5.26k
            break;
8186
0
        default:
8187
0
            result = PR_FALSE;
8188
0
            break;
8189
5.26k
    }
8190
8191
5.26k
    return result;
8192
5.26k
}
8193
8194
static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
8195
8196
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
8197
 * a complete ssl3 Server Hello Done message.
8198
 * Caller must hold Handshake and RecvBuf locks.
8199
 */
8200
static SECStatus
8201
ssl3_HandleServerHelloDone(sslSocket *ss)
8202
5.35k
{
8203
5.35k
    SECStatus rv;
8204
5.35k
    SSL3WaitState ws = ss->ssl3.hs.ws;
8205
8206
5.35k
    SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
8207
5.35k
                SSL_GETPID(), ss->fd));
8208
5.35k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
8209
5.35k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8210
8211
    /* Skipping CertificateRequest is always permitted. */
8212
5.35k
    if (ws != wait_hello_done &&
8213
5.35k
        ws != wait_cert_request) {
8214
3
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8215
3
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
8216
3
        return SECFailure;
8217
3
    }
8218
8219
5.35k
    rv = ssl3_SendClientSecondRound(ss);
8220
8221
5.35k
    return rv;
8222
5.35k
}
8223
8224
/* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
8225
 *
8226
 * Caller must hold Handshake and RecvBuf locks.
8227
 */
8228
static SECStatus
8229
ssl3_SendClientSecondRound(sslSocket *ss)
8230
5.35k
{
8231
5.35k
    SECStatus rv;
8232
5.35k
    PRBool sendClientCert;
8233
8234
5.35k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
8235
5.35k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8236
8237
5.35k
    sendClientCert = !ss->ssl3.sendEmptyCert &&
8238
5.35k
                     ss->ssl3.clientCertChain != NULL &&
8239
5.35k
                     ss->ssl3.clientPrivateKey != NULL;
8240
8241
    /* We must wait for the server's certificate to be authenticated before
8242
     * sending the client certificate in order to disclosing the client
8243
     * certificate to an attacker that does not have a valid cert for the
8244
     * domain we are connecting to.
8245
     *
8246
     * During the initial handshake on a connection, we never send/receive
8247
     * application data until we have authenticated the server's certificate;
8248
     * i.e. we have fully authenticated the handshake before using the cipher
8249
     * specs agreed upon for that handshake. During a renegotiation, we may
8250
     * continue sending and receiving application data during the handshake
8251
     * interleaved with the handshake records. If we were to send the client's
8252
     * second round for a renegotiation before the server's certificate was
8253
     * authenticated, then the application data sent/received after this point
8254
     * would be using cipher spec that hadn't been authenticated. By waiting
8255
     * until the server's certificate has been authenticated during
8256
     * renegotiations, we ensure that renegotiations have the same property
8257
     * as initial handshakes; i.e. we have fully authenticated the handshake
8258
     * before using the cipher specs agreed upon for that handshake for
8259
     * application data.
8260
     */
8261
5.35k
    if (ss->ssl3.hs.restartTarget) {
8262
0
        PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
8263
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
8264
0
        return SECFailure;
8265
0
    }
8266
    /* Check whether waiting for client certificate selection OR
8267
       waiting on server certificate verification AND
8268
       going to send client cert */
8269
5.35k
    if ((ss->ssl3.hs.clientCertificatePending) ||
8270
5.35k
        (ss->ssl3.hs.authCertificatePending && (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone))) {
8271
0
        SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"
8272
0
                    " certificate authentication is still pending.",
8273
0
                    SSL_GETPID(), ss->fd));
8274
0
        ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
8275
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
8276
0
        return SECFailure;
8277
0
    }
8278
8279
5.35k
    ssl_GetXmitBufLock(ss); /*******************************/
8280
8281
5.35k
    if (ss->ssl3.sendEmptyCert) {
8282
11
        ss->ssl3.sendEmptyCert = PR_FALSE;
8283
11
        rv = ssl3_SendEmptyCertificate(ss);
8284
        /* Don't send verify */
8285
11
        if (rv != SECSuccess) {
8286
0
            goto loser; /* error code is set. */
8287
0
        }
8288
5.34k
    } else if (sendClientCert) {
8289
0
        rv = ssl3_SendCertificate(ss);
8290
0
        if (rv != SECSuccess) {
8291
0
            goto loser; /* error code is set. */
8292
0
        }
8293
0
    }
8294
8295
5.35k
    rv = ssl3_SendClientKeyExchange(ss);
8296
5.35k
    if (rv != SECSuccess) {
8297
694
        goto loser; /* err is set. */
8298
694
    }
8299
8300
4.66k
    if (sendClientCert) {
8301
0
        rv = ssl3_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
8302
0
        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
8303
0
        ss->ssl3.clientPrivateKey = NULL;
8304
0
        if (rv != SECSuccess) {
8305
0
            goto loser; /* err is set. */
8306
0
        }
8307
0
    }
8308
8309
4.66k
    rv = ssl3_SendChangeCipherSpecs(ss);
8310
4.66k
    if (rv != SECSuccess) {
8311
0
        goto loser; /* err code was set. */
8312
0
    }
8313
8314
    /* This must be done after we've set ss->ssl3.cwSpec in
8315
     * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information
8316
     * from cwSpec. This must be done before we call ssl3_CheckFalseStart
8317
     * because the false start callback (if any) may need the information from
8318
     * the functions that depend on this being set.
8319
     */
8320
4.66k
    ss->enoughFirstHsDone = PR_TRUE;
8321
8322
4.66k
    if (!ss->firstHsDone) {
8323
783
        if (ss->opt.enableFalseStart) {
8324
379
            if (!ss->ssl3.hs.authCertificatePending) {
8325
                /* When we fix bug 589047, we will need to know whether we are
8326
                 * false starting before we try to flush the client second
8327
                 * round to the network. With that in mind, we purposefully
8328
                 * call ssl3_CheckFalseStart before calling ssl3_SendFinished,
8329
                 * which includes a call to ssl3_FlushHandshake, so that
8330
                 * no application develops a reliance on such flushing being
8331
                 * done before its false start callback is called.
8332
                 */
8333
379
                ssl_ReleaseXmitBufLock(ss);
8334
379
                rv = ssl3_CheckFalseStart(ss);
8335
379
                ssl_GetXmitBufLock(ss);
8336
379
                if (rv != SECSuccess) {
8337
0
                    goto loser;
8338
0
                }
8339
379
            } else {
8340
                /* The certificate authentication and the server's Finished
8341
                 * message are racing each other. If the certificate
8342
                 * authentication wins, then we will try to false start in
8343
                 * ssl3_AuthCertificateComplete.
8344
                 */
8345
0
                SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because"
8346
0
                            " certificate authentication is still pending.",
8347
0
                            SSL_GETPID(), ss->fd));
8348
0
            }
8349
379
        }
8350
783
    }
8351
8352
4.66k
    rv = ssl3_SendFinished(ss, 0);
8353
4.66k
    if (rv != SECSuccess) {
8354
0
        goto loser; /* err code was set. */
8355
0
    }
8356
8357
4.66k
    ssl_ReleaseXmitBufLock(ss); /*******************************/
8358
8359
4.66k
    if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
8360
0
        ss->ssl3.hs.ws = wait_new_session_ticket;
8361
4.66k
    else
8362
4.66k
        ss->ssl3.hs.ws = wait_change_cipher;
8363
8364
4.66k
    PORT_Assert(ssl3_WaitingForServerSecondRound(ss));
8365
8366
4.66k
    return SECSuccess;
8367
8368
694
loser:
8369
694
    ssl_ReleaseXmitBufLock(ss);
8370
694
    return rv;
8371
4.66k
}
8372
8373
/*
8374
 * Routines used by servers
8375
 */
8376
static SECStatus
8377
ssl3_SendHelloRequest(sslSocket *ss)
8378
0
{
8379
0
    SECStatus rv;
8380
8381
0
    SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
8382
0
                ss->fd));
8383
8384
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8385
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8386
8387
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_hello_request, 0);
8388
0
    if (rv != SECSuccess) {
8389
0
        return rv; /* err set by AppendHandshake */
8390
0
    }
8391
0
    rv = ssl3_FlushHandshake(ss, 0);
8392
0
    if (rv != SECSuccess) {
8393
0
        return rv; /* error code set by ssl3_FlushHandshake */
8394
0
    }
8395
0
    ss->ssl3.hs.ws = wait_client_hello;
8396
0
    return SECSuccess;
8397
0
}
8398
8399
/*
8400
 * Called from:
8401
 *  ssl3_HandleClientHello()
8402
 */
8403
static SECComparison
8404
ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
8405
0
{
8406
0
    if (!name1 != !name2) {
8407
0
        return SECLessThan;
8408
0
    }
8409
0
    if (!name1) {
8410
0
        return SECEqual;
8411
0
    }
8412
0
    if (name1->type != name2->type) {
8413
0
        return SECLessThan;
8414
0
    }
8415
0
    return SECITEM_CompareItem(name1, name2);
8416
0
}
8417
8418
/* Sets memory error when returning NULL.
8419
 * Called from:
8420
 *  ssl3_SendClientHello()
8421
 *  ssl3_HandleServerHello()
8422
 *  ssl3_HandleClientHello()
8423
 *  ssl3_HandleV2ClientHello()
8424
 */
8425
sslSessionID *
8426
ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
8427
32.4k
{
8428
32.4k
    sslSessionID *sid;
8429
8430
32.4k
    sid = PORT_ZNew(sslSessionID);
8431
32.4k
    if (sid == NULL)
8432
0
        return sid;
8433
8434
32.4k
    if (is_server) {
8435
0
        const SECItem *srvName;
8436
0
        SECStatus rv = SECSuccess;
8437
8438
0
        ssl_GetSpecReadLock(ss); /********************************/
8439
0
        srvName = &ss->ssl3.hs.srvVirtName;
8440
0
        if (srvName->len && srvName->data) {
8441
0
            rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
8442
0
        }
8443
0
        ssl_ReleaseSpecReadLock(ss); /************************************/
8444
0
        if (rv != SECSuccess) {
8445
0
            PORT_Free(sid);
8446
0
            return NULL;
8447
0
        }
8448
0
    }
8449
32.4k
    sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
8450
32.4k
    sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url);
8451
32.4k
    sid->addr = ss->sec.ci.peer;
8452
32.4k
    sid->port = ss->sec.ci.port;
8453
32.4k
    sid->references = 1;
8454
32.4k
    sid->cached = never_cached;
8455
32.4k
    sid->version = ss->version;
8456
32.4k
    sid->sigScheme = ssl_sig_none;
8457
8458
32.4k
    sid->u.ssl3.keys.resumable = PR_TRUE;
8459
32.4k
    sid->u.ssl3.policy = SSL_ALLOWED;
8460
32.4k
    sid->u.ssl3.keys.extendedMasterSecretUsed = PR_FALSE;
8461
8462
32.4k
    if (is_server) {
8463
0
        SECStatus rv;
8464
0
        int pid = SSL_GETPID();
8465
8466
0
        sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
8467
0
        sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff;
8468
0
        sid->u.ssl3.sessionID[1] = pid & 0xff;
8469
0
        rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
8470
0
                                 SSL3_SESSIONID_BYTES - 2);
8471
0
        if (rv != SECSuccess) {
8472
0
            ssl_FreeSID(sid);
8473
0
            ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
8474
0
            return NULL;
8475
0
        }
8476
0
    }
8477
32.4k
    return sid;
8478
32.4k
}
8479
8480
/* Called from:  ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
8481
static SECStatus
8482
ssl3_SendServerHelloSequence(sslSocket *ss)
8483
0
{
8484
0
    const ssl3KEADef *kea_def;
8485
0
    SECStatus rv;
8486
8487
0
    SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
8488
0
                SSL_GETPID(), ss->fd));
8489
8490
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8491
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8492
8493
0
    rv = ssl3_SendServerHello(ss);
8494
0
    if (rv != SECSuccess) {
8495
0
        return rv; /* err code is set. */
8496
0
    }
8497
0
    rv = ssl3_SendCertificate(ss);
8498
0
    if (rv != SECSuccess) {
8499
0
        return rv; /* error code is set. */
8500
0
    }
8501
0
    rv = ssl3_SendCertificateStatus(ss);
8502
0
    if (rv != SECSuccess) {
8503
0
        return rv; /* error code is set. */
8504
0
    }
8505
    /* We have to do this after the call to ssl3_SendServerHello,
8506
     * because kea_def is set up by ssl3_SendServerHello().
8507
     */
8508
0
    kea_def = ss->ssl3.hs.kea_def;
8509
8510
0
    if (kea_def->ephemeral) {
8511
0
        rv = ssl3_SendServerKeyExchange(ss);
8512
0
        if (rv != SECSuccess) {
8513
0
            return rv; /* err code was set. */
8514
0
        }
8515
0
    }
8516
8517
0
    if (ss->opt.requestCertificate) {
8518
0
        rv = ssl3_SendCertificateRequest(ss);
8519
0
        if (rv != SECSuccess) {
8520
0
            return rv; /* err code is set. */
8521
0
        }
8522
0
    }
8523
0
    rv = ssl3_SendServerHelloDone(ss);
8524
0
    if (rv != SECSuccess) {
8525
0
        return rv; /* err code is set. */
8526
0
    }
8527
8528
0
    ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
8529
0
                                                  : wait_client_key;
8530
0
    return SECSuccess;
8531
0
}
8532
8533
/* An empty TLS Renegotiation Info (RI) extension */
8534
static const PRUint8 emptyRIext[5] = { 0xff, 0x01, 0x00, 0x01, 0x00 };
8535
8536
static PRBool
8537
ssl3_KEASupportsTickets(const ssl3KEADef *kea_def)
8538
0
{
8539
0
    if (kea_def->signKeyType == dsaKey) {
8540
        /* TODO: Fix session tickets for DSS. The server code rejects the
8541
         * session ticket received from the client. Bug 1174677 */
8542
0
        return PR_FALSE;
8543
0
    }
8544
0
    return PR_TRUE;
8545
0
}
8546
8547
static PRBool
8548
ssl3_PeerSupportsCipherSuite(const SECItem *peerSuites, uint16_t suite)
8549
0
{
8550
0
    for (unsigned int i = 0; i + 1 < peerSuites->len; i += 2) {
8551
0
        PRUint16 suite_i = (peerSuites->data[i] << 8) | peerSuites->data[i + 1];
8552
0
        if (suite_i == suite) {
8553
0
            return PR_TRUE;
8554
0
        }
8555
0
    }
8556
0
    return PR_FALSE;
8557
0
}
8558
8559
SECStatus
8560
ssl3_NegotiateCipherSuiteInner(sslSocket *ss, const SECItem *suites,
8561
                               PRUint16 version, PRUint16 *suitep)
8562
0
{
8563
0
    unsigned int i;
8564
0
    SSLVersionRange vrange = { version, version };
8565
8566
    /* If we negotiated an External PSK and that PSK has a ciphersuite
8567
     * configured, we need to constrain our choice. If the client does
8568
     * not support it, negotiate a certificate auth suite and fall back.
8569
     */
8570
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
8571
0
        ss->xtnData.selectedPsk &&
8572
0
        ss->xtnData.selectedPsk->type == ssl_psk_external &&
8573
0
        ss->xtnData.selectedPsk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL) {
8574
0
        PRUint16 pskSuite = ss->xtnData.selectedPsk->zeroRttSuite;
8575
0
        ssl3CipherSuiteCfg *pskSuiteCfg = ssl_LookupCipherSuiteCfgMutable(pskSuite,
8576
0
                                                                          ss->cipherSuites);
8577
0
        if (ssl3_config_match(pskSuiteCfg, ss->ssl3.policy, &vrange, ss) &&
8578
0
            ssl3_PeerSupportsCipherSuite(suites, pskSuite)) {
8579
0
            *suitep = pskSuite;
8580
0
            return SECSuccess;
8581
0
        }
8582
0
    }
8583
8584
0
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
8585
0
        ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
8586
0
        if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
8587
0
            continue;
8588
0
        }
8589
0
        if (!ssl3_PeerSupportsCipherSuite(suites, suite->cipher_suite)) {
8590
0
            continue;
8591
0
        }
8592
0
        *suitep = suite->cipher_suite;
8593
0
        return SECSuccess;
8594
0
    }
8595
0
    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8596
0
    return SECFailure;
8597
0
}
8598
8599
/* Select a cipher suite.
8600
**
8601
** NOTE: This suite selection algorithm should be the same as the one in
8602
** ssl3_HandleV2ClientHello().
8603
**
8604
** If TLS 1.0 is enabled, we could handle the case where the client
8605
** offered TLS 1.1 but offered only export cipher suites by choosing TLS
8606
** 1.0 and selecting one of those export cipher suites. However, a secure
8607
** TLS 1.1 client should not have export cipher suites enabled at all,
8608
** and a TLS 1.1 client should definitely not be offering *only* export
8609
** cipher suites. Therefore, we refuse to negotiate export cipher suites
8610
** with any client that indicates support for TLS 1.1 or higher when we
8611
** (the server) have TLS 1.1 support enabled.
8612
*/
8613
SECStatus
8614
ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites,
8615
                          PRBool initHashes)
8616
0
{
8617
0
    PRUint16 selected;
8618
0
    SECStatus rv;
8619
8620
    /* Ensure that only valid cipher suites are enabled. */
8621
0
    if (ssl3_config_match_init(ss) == 0) {
8622
        /* No configured cipher is both supported by PK11 and allowed.
8623
         * This is a configuration error, so report handshake failure.*/
8624
0
        FATAL_ERROR(ss, PORT_GetError(), handshake_failure);
8625
0
        return SECFailure;
8626
0
    }
8627
8628
0
    rv = ssl3_NegotiateCipherSuiteInner(ss, suites, ss->version, &selected);
8629
0
    if (rv != SECSuccess) {
8630
0
        return SECFailure;
8631
0
    }
8632
8633
0
    ss->ssl3.hs.cipher_suite = selected;
8634
0
    return ssl3_SetupCipherSuite(ss, initHashes);
8635
0
}
8636
8637
/*
8638
 * Call the SNI config hook.
8639
 *
8640
 * Called from:
8641
 *   ssl3_HandleClientHello
8642
 *   tls13_HandleClientHelloPart2
8643
 */
8644
SECStatus
8645
ssl3_ServerCallSNICallback(sslSocket *ss)
8646
0
{
8647
0
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8648
0
    SSL3AlertDescription desc = illegal_parameter;
8649
0
    int ret = 0;
8650
8651
#ifdef SSL_SNI_ALLOW_NAME_CHANGE_2HS
8652
#error("No longer allowed to set SSL_SNI_ALLOW_NAME_CHANGE_2HS")
8653
#endif
8654
0
    if (!ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
8655
0
        if (ss->firstHsDone) {
8656
            /* Check that we don't have the name is current spec
8657
             * if this extension was not negotiated on the 2d hs. */
8658
0
            PRBool passed = PR_TRUE;
8659
0
            ssl_GetSpecReadLock(ss); /*******************************/
8660
0
            if (ss->ssl3.hs.srvVirtName.data) {
8661
0
                passed = PR_FALSE;
8662
0
            }
8663
0
            ssl_ReleaseSpecReadLock(ss); /***************************/
8664
0
            if (!passed) {
8665
0
                errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8666
0
                desc = handshake_failure;
8667
0
                goto alert_loser;
8668
0
            }
8669
0
        }
8670
0
        return SECSuccess;
8671
0
    }
8672
8673
0
    if (ss->sniSocketConfig)
8674
0
        do { /* not a loop */
8675
0
            PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
8676
0
                        ssl_preinfo_all);
8677
8678
0
            ret = SSL_SNI_SEND_ALERT;
8679
            /* If extension is negotiated, the len of names should > 0. */
8680
0
            if (ss->xtnData.sniNameArrSize) {
8681
                /* Calling client callback to reconfigure the socket. */
8682
0
                ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
8683
0
                                                        ss->xtnData.sniNameArr,
8684
0
                                                        ss->xtnData.sniNameArrSize,
8685
0
                                                        ss->sniSocketConfigArg);
8686
0
            }
8687
0
            if (ret <= SSL_SNI_SEND_ALERT) {
8688
                /* Application does not know the name or was not able to
8689
                 * properly reconfigure the socket. */
8690
0
                errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8691
0
                desc = unrecognized_name;
8692
0
                break;
8693
0
            } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
8694
0
                SECStatus rv = SECSuccess;
8695
0
                SECItem pwsNameBuf = { 0, NULL, 0 };
8696
0
                SECItem *pwsName = &pwsNameBuf;
8697
0
                SECItem *cwsName;
8698
8699
0
                ssl_GetSpecWriteLock(ss); /*******************************/
8700
0
                cwsName = &ss->ssl3.hs.srvVirtName;
8701
                /* not allow name change on the 2d HS */
8702
0
                if (ss->firstHsDone) {
8703
0
                    if (ssl3_ServerNameCompare(pwsName, cwsName)) {
8704
0
                        ssl_ReleaseSpecWriteLock(ss); /******************/
8705
0
                        errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8706
0
                        desc = handshake_failure;
8707
0
                        ret = SSL_SNI_SEND_ALERT;
8708
0
                        break;
8709
0
                    }
8710
0
                }
8711
0
                if (pwsName->data) {
8712
0
                    SECITEM_FreeItem(pwsName, PR_FALSE);
8713
0
                }
8714
0
                if (cwsName->data) {
8715
0
                    rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
8716
0
                }
8717
0
                ssl_ReleaseSpecWriteLock(ss); /**************************/
8718
0
                if (rv != SECSuccess) {
8719
0
                    errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8720
0
                    desc = internal_error;
8721
0
                    ret = SSL_SNI_SEND_ALERT;
8722
0
                    break;
8723
0
                }
8724
0
            } else if ((unsigned int)ret < ss->xtnData.sniNameArrSize) {
8725
                /* Application has configured new socket info. Lets check it
8726
                 * and save the name. */
8727
0
                SECStatus rv;
8728
0
                SECItem *name = &ss->xtnData.sniNameArr[ret];
8729
0
                SECItem *pwsName;
8730
8731
                /* get rid of the old name and save the newly picked. */
8732
                /* This code is protected by ssl3HandshakeLock. */
8733
0
                ssl_GetSpecWriteLock(ss); /*******************************/
8734
                /* not allow name change on the 2d HS */
8735
0
                if (ss->firstHsDone) {
8736
0
                    SECItem *cwsName = &ss->ssl3.hs.srvVirtName;
8737
0
                    if (ssl3_ServerNameCompare(name, cwsName)) {
8738
0
                        ssl_ReleaseSpecWriteLock(ss); /******************/
8739
0
                        errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8740
0
                        desc = handshake_failure;
8741
0
                        ret = SSL_SNI_SEND_ALERT;
8742
0
                        break;
8743
0
                    }
8744
0
                }
8745
0
                pwsName = &ss->ssl3.hs.srvVirtName;
8746
0
                if (pwsName->data) {
8747
0
                    SECITEM_FreeItem(pwsName, PR_FALSE);
8748
0
                }
8749
0
                rv = SECITEM_CopyItem(NULL, pwsName, name);
8750
0
                ssl_ReleaseSpecWriteLock(ss); /***************************/
8751
0
                if (rv != SECSuccess) {
8752
0
                    errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8753
0
                    desc = internal_error;
8754
0
                    ret = SSL_SNI_SEND_ALERT;
8755
0
                    break;
8756
0
                }
8757
                /* Need to tell the client that application has picked
8758
                 * the name from the offered list and reconfigured the socket.
8759
                 */
8760
0
                ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_server_name_xtn,
8761
0
                                             ssl_SendEmptyExtension);
8762
0
            } else {
8763
                /* Callback returned index outside of the boundary. */
8764
0
                PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize);
8765
0
                errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8766
0
                desc = internal_error;
8767
0
                ret = SSL_SNI_SEND_ALERT;
8768
0
                break;
8769
0
            }
8770
0
        } while (0);
8771
0
    ssl3_FreeSniNameArray(&ss->xtnData);
8772
0
    if (ret <= SSL_SNI_SEND_ALERT) {
8773
        /* desc and errCode should be set. */
8774
0
        goto alert_loser;
8775
0
    }
8776
8777
0
    return SECSuccess;
8778
8779
0
alert_loser:
8780
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
8781
0
    PORT_SetError(errCode);
8782
0
    return SECFailure;
8783
0
}
8784
8785
SECStatus
8786
ssl3_SelectServerCert(sslSocket *ss)
8787
0
{
8788
0
    const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
8789
0
    PRCList *cursor;
8790
0
    SECStatus rv;
8791
8792
    /* If the client didn't include the supported groups extension, assume just
8793
     * P-256 support and disable all the other ECDHE groups.  This also affects
8794
     * ECDHE group selection, but this function is called first. */
8795
0
    if (!ssl3_ExtensionNegotiated(ss, ssl_supported_groups_xtn)) {
8796
0
        unsigned int i;
8797
0
        for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
8798
0
            if (ss->namedGroupPreferences[i] &&
8799
0
                ss->namedGroupPreferences[i]->keaType == ssl_kea_ecdh &&
8800
0
                ss->namedGroupPreferences[i]->name != ssl_grp_ec_secp256r1) {
8801
0
                ss->namedGroupPreferences[i] = NULL;
8802
0
            }
8803
0
        }
8804
0
    }
8805
8806
    /* This picks the first certificate that has:
8807
     * a) the right authentication method, and
8808
     * b) the right named curve (EC only)
8809
     *
8810
     * We might want to do some sort of ranking here later.  For now, it's all
8811
     * based on what order they are configured in. */
8812
0
    for (cursor = PR_NEXT_LINK(&ss->serverCerts);
8813
0
         cursor != &ss->serverCerts;
8814
0
         cursor = PR_NEXT_LINK(cursor)) {
8815
0
        sslServerCert *cert = (sslServerCert *)cursor;
8816
0
        if (kea_def->authKeyType == ssl_auth_rsa_sign) {
8817
            /* We consider PSS certificates here as well for TLS 1.2. */
8818
0
            if (!SSL_CERT_IS(cert, ssl_auth_rsa_sign) &&
8819
0
                (!SSL_CERT_IS(cert, ssl_auth_rsa_pss) ||
8820
0
                 ss->version < SSL_LIBRARY_VERSION_TLS_1_2)) {
8821
0
                continue;
8822
0
            }
8823
0
        } else {
8824
0
            if (!SSL_CERT_IS(cert, kea_def->authKeyType)) {
8825
0
                continue;
8826
0
            }
8827
0
            if (SSL_CERT_IS_EC(cert) &&
8828
0
                !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
8829
0
                continue;
8830
0
            }
8831
0
        }
8832
8833
        /* Found one. */
8834
0
        ss->sec.serverCert = cert;
8835
0
        ss->sec.authKeyBits = cert->serverKeyBits;
8836
8837
        /* Don't pick a signature scheme if we aren't going to use it. */
8838
0
        if (kea_def->signKeyType == nullKey) {
8839
0
            ss->sec.authType = kea_def->authKeyType;
8840
0
            return SECSuccess;
8841
0
        }
8842
8843
0
        rv = ssl3_PickServerSignatureScheme(ss);
8844
0
        if (rv != SECSuccess) {
8845
0
            return SECFailure;
8846
0
        }
8847
0
        ss->sec.authType =
8848
0
            ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme);
8849
0
        return SECSuccess;
8850
0
    }
8851
8852
0
    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8853
0
    return SECFailure;
8854
0
}
8855
8856
static SECStatus
8857
ssl_GenerateServerRandom(sslSocket *ss)
8858
0
{
8859
0
    SECStatus rv;
8860
0
    PRUint8 *downgradeSentinel;
8861
8862
0
    rv = ssl3_GetNewRandom(ss->ssl3.hs.server_random);
8863
0
    if (rv != SECSuccess) {
8864
0
        return SECFailure;
8865
0
    }
8866
8867
0
    if (ss->version == ss->vrange.max) {
8868
0
        return SECSuccess;
8869
0
    }
8870
8871
    /*
8872
     * [RFC 8446 Section 4.1.3].
8873
     *
8874
     * TLS 1.3 servers which negotiate TLS 1.2 or below in response to a
8875
     * ClientHello MUST set the last 8 bytes of their Random value specially in
8876
     * their ServerHello.
8877
     *
8878
     * If negotiating TLS 1.2, TLS 1.3 servers MUST set the last 8 bytes of
8879
     * their Random value to the bytes:
8880
     *
8881
     *   44 4F 57 4E 47 52 44 01
8882
     *
8883
     * If negotiating TLS 1.1 or below, TLS 1.3 servers MUST, and TLS 1.2
8884
     * servers SHOULD, set the last 8 bytes of their ServerHello.Random value to
8885
     * the bytes:
8886
     *
8887
     *   44 4F 57 4E 47 52 44 00
8888
     */
8889
0
    downgradeSentinel =
8890
0
        ss->ssl3.hs.server_random +
8891
0
        SSL3_RANDOM_LENGTH - sizeof(tls12_downgrade_random);
8892
0
    if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_2) {
8893
0
        switch (ss->version) {
8894
0
            case SSL_LIBRARY_VERSION_TLS_1_2:
8895
                /* vrange.max > 1.2, since we didn't early exit above. */
8896
0
                PORT_Memcpy(downgradeSentinel,
8897
0
                            tls12_downgrade_random, sizeof(tls12_downgrade_random));
8898
0
                break;
8899
0
            case SSL_LIBRARY_VERSION_TLS_1_1:
8900
0
            case SSL_LIBRARY_VERSION_TLS_1_0:
8901
0
                PORT_Memcpy(downgradeSentinel,
8902
0
                            tls1_downgrade_random, sizeof(tls1_downgrade_random));
8903
0
                break;
8904
0
            default:
8905
                /* Do not change random. */
8906
0
                break;
8907
0
        }
8908
0
    }
8909
8910
0
    return SECSuccess;
8911
0
}
8912
8913
SECStatus
8914
ssl3_HandleClientHelloPreamble(sslSocket *ss, PRUint8 **b, PRUint32 *length, SECItem *sidBytes,
8915
                               SECItem *cookieBytes, SECItem *suites, SECItem *comps)
8916
0
{
8917
0
    SECStatus rv;
8918
0
    PRUint32 tmp;
8919
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
8920
0
    if (rv != SECSuccess) {
8921
0
        return SECFailure; /* malformed, alert already sent */
8922
0
    }
8923
8924
    /* Translate the version. */
8925
0
    if (IS_DTLS(ss)) {
8926
0
        ss->clientHelloVersion = dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
8927
0
    } else {
8928
0
        ss->clientHelloVersion = (SSL3ProtocolVersion)tmp;
8929
0
    }
8930
8931
    /* Grab the client random data. */
8932
0
    rv = ssl3_ConsumeHandshake(
8933
0
        ss, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, b, length);
8934
0
    if (rv != SECSuccess) {
8935
0
        return SECFailure; /* malformed */
8936
0
    }
8937
8938
    /* Grab the client's SID, if present. */
8939
0
    rv = ssl3_ConsumeHandshakeVariable(ss, sidBytes, 1, b, length);
8940
    /* Check that the SID has the format: opaque legacy_session_id<0..32>, as
8941
     * specified in RFC8446, Section 4.1.2. */
8942
0
    if (rv != SECSuccess || sidBytes->len > SSL3_SESSIONID_BYTES) {
8943
0
        return SECFailure; /* malformed */
8944
0
    }
8945
8946
    /* Grab the client's cookie, if present. It is checked after version negotiation. */
8947
0
    if (IS_DTLS(ss)) {
8948
0
        rv = ssl3_ConsumeHandshakeVariable(ss, cookieBytes, 1, b, length);
8949
0
        if (rv != SECSuccess) {
8950
0
            return SECFailure; /* malformed */
8951
0
        }
8952
0
    }
8953
8954
    /* Grab the list of cipher suites. */
8955
0
    rv = ssl3_ConsumeHandshakeVariable(ss, suites, 2, b, length);
8956
0
    if (rv != SECSuccess) {
8957
0
        return SECFailure; /* malformed */
8958
0
    }
8959
8960
    /* Grab the list of compression methods. */
8961
0
    rv = ssl3_ConsumeHandshakeVariable(ss, comps, 1, b, length);
8962
0
    if (rv != SECSuccess) {
8963
0
        return SECFailure; /* malformed */
8964
0
    }
8965
0
    return SECSuccess;
8966
0
}
8967
8968
static SECStatus
8969
ssl3_ValidatePreambleWithVersion(sslSocket *ss, const SECItem *sidBytes, const SECItem *comps,
8970
                                 const SECItem *cookieBytes)
8971
0
{
8972
0
    SECStatus rv;
8973
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
8974
0
        if (sidBytes->len > 0 && !IS_DTLS(ss)) {
8975
0
            SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
8976
0
            rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.fakeSid, sidBytes);
8977
0
            if (rv != SECSuccess) {
8978
0
                FATAL_ERROR(ss, PORT_GetError(), internal_error);
8979
0
                return SECFailure;
8980
0
            }
8981
0
        }
8982
8983
        /* TLS 1.3 requires that compression include only null. */
8984
0
        if (comps->len != 1 || comps->data[0] != ssl_compression_null) {
8985
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
8986
0
            return SECFailure;
8987
0
        }
8988
8989
        /* receivedCcs is only valid if we sent an HRR. */
8990
0
        if (ss->ssl3.hs.receivedCcs && !ss->ssl3.hs.helloRetry) {
8991
0
            FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message);
8992
0
            return SECFailure;
8993
0
        }
8994
8995
        /* A DTLS 1.3-only client MUST set the legacy_cookie field to zero length.
8996
         * If a DTLS 1.3 ClientHello is received with any other value in this field,
8997
         * the server MUST abort the handshake with an "illegal_parameter" alert. */
8998
0
        if (IS_DTLS(ss) && cookieBytes->len != 0) {
8999
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
9000
0
            return SECFailure;
9001
0
        }
9002
0
    } else {
9003
        /* ECH not possible here. */
9004
0
        ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
9005
9006
        /* HRR and ECH are TLS1.3-only. We ignore the Cookie extension here. */
9007
0
        if (ss->ssl3.hs.helloRetry) {
9008
0
            FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, protocol_version);
9009
0
            return SECFailure;
9010
0
        }
9011
9012
        /* receivedCcs is only valid if we sent an HRR. */
9013
0
        if (ss->ssl3.hs.receivedCcs) {
9014
0
            FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message);
9015
0
            return SECFailure;
9016
0
        }
9017
9018
        /* TLS versions prior to 1.3 must include null somewhere. */
9019
0
        if (comps->len < 1 ||
9020
0
            !memchr(comps->data, ssl_compression_null, comps->len)) {
9021
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
9022
0
            return SECFailure;
9023
0
        }
9024
9025
        /* We never send cookies in DTLS 1.2. */
9026
0
        if (IS_DTLS(ss) && cookieBytes->len != 0) {
9027
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
9028
0
            return SECFailure;
9029
0
        }
9030
0
    }
9031
9032
0
    return SECSuccess;
9033
0
}
9034
9035
/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9036
 * ssl3 Client Hello message.
9037
 * Caller must hold Handshake and RecvBuf locks.
9038
 */
9039
static SECStatus
9040
ssl3_HandleClientHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
9041
0
{
9042
0
    sslSessionID *sid = NULL;
9043
0
    unsigned int i;
9044
0
    SECStatus rv;
9045
0
    PRUint32 extensionLength;
9046
0
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9047
0
    SSL3AlertDescription desc = illegal_parameter;
9048
0
    SSL3AlertLevel level = alert_fatal;
9049
0
    TLSExtension *versionExtension;
9050
0
    SECItem sidBytes = { siBuffer, NULL, 0 };
9051
0
    SECItem cookieBytes = { siBuffer, NULL, 0 };
9052
0
    SECItem suites = { siBuffer, NULL, 0 };
9053
0
    SECItem comps = { siBuffer, NULL, 0 };
9054
0
    SECItem *echInner = NULL;
9055
0
    PRBool isTLS13;
9056
0
    const PRUint8 *savedMsg = b;
9057
0
    const PRUint32 savedLen = length;
9058
9059
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
9060
0
                SSL_GETPID(), ss->fd));
9061
9062
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
9063
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9064
0
    ss->ssl3.hs.preliminaryInfo = 0;
9065
9066
0
    if (!ss->sec.isServer ||
9067
0
        (ss->ssl3.hs.ws != wait_client_hello &&
9068
0
         ss->ssl3.hs.ws != idle_handshake)) {
9069
0
        desc = unexpected_message;
9070
0
        errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
9071
0
        goto alert_loser;
9072
0
    }
9073
0
    if (ss->ssl3.hs.ws == idle_handshake) {
9074
        /* Refuse re-handshake when we have already negotiated TLS 1.3. */
9075
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
9076
0
            desc = unexpected_message;
9077
0
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9078
0
            goto alert_loser;
9079
0
        }
9080
0
        if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
9081
0
            desc = no_renegotiation;
9082
0
            level = alert_warning;
9083
0
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9084
0
            goto alert_loser;
9085
0
        }
9086
0
    }
9087
9088
    /* We should always be in a fresh state. */
9089
0
    SSL_ASSERT_HASHES_EMPTY(ss);
9090
9091
    /* Get peer name of client */
9092
0
    rv = ssl_GetPeerInfo(ss);
9093
0
    if (rv != SECSuccess) {
9094
0
        return rv; /* error code is set. */
9095
0
    }
9096
9097
    /* We might be starting session renegotiation in which case we should
9098
     * clear previous state.
9099
     */
9100
0
    ssl3_ResetExtensionData(&ss->xtnData, ss);
9101
0
    ss->statelessResume = PR_FALSE;
9102
9103
0
    if (IS_DTLS(ss)) {
9104
0
        dtls_RehandshakeCleanup(ss);
9105
0
    }
9106
9107
0
    rv = ssl3_HandleClientHelloPreamble(ss, &b, &length, &sidBytes,
9108
0
                                        &cookieBytes, &suites, &comps);
9109
0
    if (rv != SECSuccess) {
9110
0
        goto loser; /* malformed */
9111
0
    }
9112
9113
    /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
9114
     * we are restarting a previous session until extensions have been
9115
     * parsed, since we might have received a SessionTicket extension.
9116
     * Note: we allow extensions even when negotiating SSL3 for the sake
9117
     * of interoperability (and backwards compatibility).
9118
     */
9119
0
    if (length) {
9120
        /* Get length of hello extensions */
9121
0
        rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
9122
0
        if (rv != SECSuccess) {
9123
0
            goto loser; /* alert already sent */
9124
0
        }
9125
0
        if (extensionLength != length) {
9126
0
            errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9127
0
            desc = decode_error;
9128
0
            goto alert_loser;
9129
0
        }
9130
9131
0
        rv = ssl3_ParseExtensions(ss, &b, &length);
9132
0
        if (rv != SECSuccess) {
9133
0
            goto loser; /* malformed */
9134
0
        }
9135
0
    }
9136
9137
0
    versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
9138
0
    if (versionExtension) {
9139
0
        rv = tls13_NegotiateVersion(ss, versionExtension);
9140
0
        if (rv != SECSuccess) {
9141
0
            errCode = PORT_GetError();
9142
0
            desc = (errCode == SSL_ERROR_UNSUPPORTED_VERSION) ? protocol_version : illegal_parameter;
9143
0
            goto alert_loser;
9144
0
        }
9145
0
    } else {
9146
        /* The PR_MIN here ensures that we never negotiate 1.3 if the
9147
         * peer didn't offer "supported_versions". */
9148
0
        rv = ssl3_NegotiateVersion(ss,
9149
0
                                   PR_MIN(ss->clientHelloVersion,
9150
0
                                          SSL_LIBRARY_VERSION_TLS_1_2),
9151
0
                                   PR_TRUE);
9152
        /* Send protocol version alert if the ClientHello.legacy_version is not
9153
         * supported by the server.
9154
         *
9155
         * If the "supported_versions" extension is absent and the server only
9156
         * supports versions greater than ClientHello.legacy_version, the
9157
         * server MUST abort the handshake with a "protocol_version" alert
9158
         * [RFC8446, Appendix D.2]. */
9159
0
        if (rv != SECSuccess) {
9160
0
            desc = protocol_version;
9161
0
            errCode = SSL_ERROR_UNSUPPORTED_VERSION;
9162
0
            goto alert_loser;
9163
0
        }
9164
0
    }
9165
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
9166
9167
    /* Update the write spec to match the selected version. */
9168
0
    if (!ss->firstHsDone) {
9169
0
        ssl_GetSpecWriteLock(ss);
9170
0
        ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
9171
0
        ssl_ReleaseSpecWriteLock(ss);
9172
0
    }
9173
9174
0
    isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
9175
0
    if (isTLS13) {
9176
0
        if (ss->firstHsDone) {
9177
0
            desc = unexpected_message;
9178
0
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9179
0
            goto alert_loser;
9180
0
        }
9181
9182
        /* If there is a cookie, then this is a second ClientHello (TLS 1.3). */
9183
0
        if (ssl3_FindExtension(ss, ssl_tls13_cookie_xtn)) {
9184
0
            ss->ssl3.hs.helloRetry = PR_TRUE;
9185
0
        }
9186
9187
0
        rv = tls13_MaybeHandleEch(ss, savedMsg, savedLen, &sidBytes,
9188
0
                                  &comps, &cookieBytes, &suites, &echInner);
9189
0
        if (rv != SECSuccess) {
9190
0
            errCode = PORT_GetError();
9191
0
            goto loser; /* code set, alert sent. */
9192
0
        }
9193
0
    }
9194
9195
0
    rv = ssl3_ValidatePreambleWithVersion(ss, &sidBytes, &comps, &cookieBytes);
9196
0
    if (rv != SECSuccess) {
9197
0
        errCode = PORT_GetError();
9198
0
        goto loser; /* code set, alert sent. */
9199
0
    }
9200
9201
    /* Now parse the rest of the extensions. */
9202
0
    rv = ssl3_HandleParsedExtensions(ss, ssl_hs_client_hello);
9203
0
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
9204
0
    if (rv != SECSuccess) {
9205
0
        if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
9206
0
            errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
9207
0
        }
9208
0
        goto loser; /* malformed */
9209
0
    }
9210
9211
    /* If the ClientHello version is less than our maximum version, check for a
9212
     * TLS_FALLBACK_SCSV and reject the connection if found. */
9213
0
    if (ss->vrange.max > ss->version) {
9214
0
        for (i = 0; i + 1 < suites.len; i += 2) {
9215
0
            PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
9216
0
            if (suite_i != TLS_FALLBACK_SCSV)
9217
0
                continue;
9218
0
            desc = inappropriate_fallback;
9219
0
            errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
9220
0
            goto alert_loser;
9221
0
        }
9222
0
    }
9223
9224
0
    if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9225
        /* If we didn't receive an RI extension, look for the SCSV,
9226
         * and if found, treat it just like an empty RI extension
9227
         * by processing a local copy of an empty RI extension.
9228
         */
9229
0
        for (i = 0; i + 1 < suites.len; i += 2) {
9230
0
            PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
9231
0
            if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
9232
0
                PRUint8 *b2 = (PRUint8 *)emptyRIext;
9233
0
                PRUint32 L2 = sizeof emptyRIext;
9234
0
                (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
9235
0
                break;
9236
0
            }
9237
0
        }
9238
0
    }
9239
9240
    /* The check for renegotiation in TLS 1.3 is earlier. */
9241
0
    if (!isTLS13) {
9242
0
        if (ss->firstHsDone &&
9243
0
            (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
9244
0
             ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) &&
9245
0
            !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9246
0
            desc = no_renegotiation;
9247
0
            level = alert_warning;
9248
0
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9249
0
            goto alert_loser;
9250
0
        }
9251
0
        if ((ss->opt.requireSafeNegotiation ||
9252
0
             (ss->firstHsDone && ss->peerRequestedProtection)) &&
9253
0
            !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9254
0
            desc = handshake_failure;
9255
0
            errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
9256
0
            goto alert_loser;
9257
0
        }
9258
0
    }
9259
9260
    /* We do stateful resumes only if we are in TLS < 1.3 and
9261
     * either of the following conditions are satisfied:
9262
     * (1) the client does not support the session ticket extension, or
9263
     * (2) the client support the session ticket extension, but sent an
9264
     * empty ticket.
9265
     */
9266
0
    if (!isTLS13 &&
9267
0
        (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
9268
0
         ss->xtnData.emptySessionTicket)) {
9269
0
        if (sidBytes.len > 0 && !ss->opt.noCache) {
9270
0
            SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
9271
0
                        SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
9272
0
                        ss->sec.ci.peer.pr_s6_addr32[1],
9273
0
                        ss->sec.ci.peer.pr_s6_addr32[2],
9274
0
                        ss->sec.ci.peer.pr_s6_addr32[3]));
9275
0
            if (ssl_sid_lookup) {
9276
0
                sid = (*ssl_sid_lookup)(ssl_Time(ss), &ss->sec.ci.peer,
9277
0
                                        sidBytes.data, sidBytes.len, ss->dbHandle);
9278
0
            } else {
9279
0
                errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
9280
0
                goto loser;
9281
0
            }
9282
0
        }
9283
0
    } else if (ss->statelessResume) {
9284
        /* Fill in the client's session ID if doing a stateless resume.
9285
         * (When doing stateless resumes, server echos client's SessionID.)
9286
         * This branch also handles TLS 1.3 resumption-PSK.
9287
         */
9288
0
        sid = ss->sec.ci.sid;
9289
0
        PORT_Assert(sid != NULL); /* Should have already been filled in.*/
9290
9291
0
        if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
9292
0
            sid->u.ssl3.sessionIDLength = sidBytes.len;
9293
0
            PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
9294
0
                        sidBytes.len);
9295
0
            sid->u.ssl3.sessionIDLength = sidBytes.len;
9296
0
        } else {
9297
0
            sid->u.ssl3.sessionIDLength = 0;
9298
0
        }
9299
0
        ss->sec.ci.sid = NULL;
9300
0
    }
9301
9302
    /* Free a potentially leftover session ID from a previous handshake. */
9303
0
    if (ss->sec.ci.sid) {
9304
0
        ssl_FreeSID(ss->sec.ci.sid);
9305
0
        ss->sec.ci.sid = NULL;
9306
0
    }
9307
9308
0
    if (sid != NULL) {
9309
        /* We've found a session cache entry for this client.
9310
         * Now, if we're going to require a client-auth cert,
9311
         * and we don't already have this client's cert in the session cache,
9312
         * and this is the first handshake on this connection (not a redo),
9313
         * then drop this old cache entry and start a new session.
9314
         */
9315
0
        if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
9316
0
            ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
9317
0
             (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
9318
0
             ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) &&
9319
0
              !ss->firstHsDone))) {
9320
9321
0
            SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
9322
0
            ssl_FreeSID(sid);
9323
0
            sid = NULL;
9324
0
            ss->statelessResume = PR_FALSE;
9325
0
        }
9326
0
    }
9327
9328
0
    if (IS_DTLS(ss)) {
9329
0
        ssl3_DisableNonDTLSSuites(ss);
9330
0
        dtls_ReceivedFirstMessageInFlight(ss);
9331
0
    }
9332
9333
0
    if (isTLS13) {
9334
0
        rv = tls13_HandleClientHelloPart2(ss, &suites, sid,
9335
0
                                          ss->ssl3.hs.echAccepted ? echInner->data : savedMsg,
9336
0
                                          ss->ssl3.hs.echAccepted ? echInner->len : savedLen);
9337
0
        SECITEM_FreeItem(echInner, PR_TRUE);
9338
0
        echInner = NULL;
9339
0
    } else {
9340
0
        rv = ssl3_HandleClientHelloPart2(ss, &suites, sid,
9341
0
                                         savedMsg, savedLen);
9342
0
    }
9343
0
    if (rv != SECSuccess) {
9344
0
        errCode = PORT_GetError();
9345
0
        goto loser;
9346
0
    }
9347
0
    return SECSuccess;
9348
9349
0
alert_loser:
9350
0
    (void)SSL3_SendAlert(ss, level, desc);
9351
/* FALLTHRU */
9352
0
loser:
9353
0
    SECITEM_FreeItem(echInner, PR_TRUE);
9354
0
    PORT_SetError(errCode);
9355
0
    return SECFailure;
9356
0
}
9357
9358
/* unwrap helper function to handle the case where the wrapKey doesn't wind
9359
 * up in the correct token for the master secret */
9360
PK11SymKey *
9361
ssl_unwrapSymKey(PK11SymKey *wrapKey,
9362
                 CK_MECHANISM_TYPE wrapType, SECItem *param,
9363
                 SECItem *wrappedKey,
9364
                 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
9365
                 int keySize, CK_FLAGS keyFlags, void *pinArg)
9366
0
{
9367
0
    PK11SymKey *unwrappedKey;
9368
9369
    /* unwrap the master secret. */
9370
0
    unwrappedKey = PK11_UnwrapSymKeyWithFlags(wrapKey, wrapType, param,
9371
0
                                              wrappedKey, target, operation, keySize,
9372
0
                                              keyFlags);
9373
0
    if (!unwrappedKey) {
9374
0
        PK11SlotInfo *targetSlot = PK11_GetBestSlot(target, pinArg);
9375
0
        PK11SymKey *newWrapKey;
9376
9377
        /* it's possible that we failed to unwrap because the wrapKey is in
9378
         * a slot that can't handle target. Move the wrapKey to a slot that
9379
         * can handle this mechanism and retry the operation */
9380
0
        if (targetSlot == NULL) {
9381
0
            return NULL;
9382
0
        }
9383
0
        newWrapKey = PK11_MoveSymKey(targetSlot, CKA_UNWRAP, 0,
9384
0
                                     PR_FALSE, wrapKey);
9385
0
        PK11_FreeSlot(targetSlot);
9386
0
        if (newWrapKey == NULL) {
9387
0
            return NULL;
9388
0
        }
9389
0
        unwrappedKey = PK11_UnwrapSymKeyWithFlags(newWrapKey, wrapType, param,
9390
0
                                                  wrappedKey, target, operation, keySize,
9391
0
                                                  keyFlags);
9392
0
        PK11_FreeSymKey(newWrapKey);
9393
0
    }
9394
0
    return unwrappedKey;
9395
0
}
9396
9397
static SECStatus
9398
ssl3_UnwrapMasterSecretServer(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
9399
0
{
9400
0
    PK11SymKey *wrapKey;
9401
0
    CK_FLAGS keyFlags = 0;
9402
0
    SECItem wrappedMS = {
9403
0
        siBuffer,
9404
0
        sid->u.ssl3.keys.wrapped_master_secret,
9405
0
        sid->u.ssl3.keys.wrapped_master_secret_len
9406
0
    };
9407
9408
0
    wrapKey = ssl3_GetWrappingKey(ss, NULL, sid->u.ssl3.masterWrapMech,
9409
0
                                  ss->pkcs11PinArg);
9410
0
    if (!wrapKey) {
9411
0
        return SECFailure;
9412
0
    }
9413
9414
0
    if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
9415
0
        keyFlags = CKF_SIGN | CKF_VERIFY;
9416
0
    }
9417
9418
0
    *ms = ssl_unwrapSymKey(wrapKey, sid->u.ssl3.masterWrapMech, NULL,
9419
0
                           &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
9420
0
                           CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH,
9421
0
                           keyFlags, ss->pkcs11PinArg);
9422
0
    PK11_FreeSymKey(wrapKey);
9423
0
    if (!*ms) {
9424
0
        SSL_TRC(10, ("%d: SSL3[%d]: server wrapping key found, but couldn't unwrap MasterSecret. wrapMech=0x%0lx",
9425
0
                     SSL_GETPID(), ss->fd, sid->u.ssl3.masterWrapMech));
9426
0
        return SECFailure;
9427
0
    }
9428
0
    return SECSuccess;
9429
0
}
9430
9431
static SECStatus
9432
ssl3_HandleClientHelloPart2(sslSocket *ss,
9433
                            SECItem *suites,
9434
                            sslSessionID *sid,
9435
                            const PRUint8 *msg,
9436
                            unsigned int len)
9437
0
{
9438
0
    PRBool haveXmitBufLock = PR_FALSE;
9439
0
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9440
0
    SSL3AlertDescription desc = illegal_parameter;
9441
0
    SECStatus rv;
9442
0
    unsigned int i;
9443
0
    unsigned int j;
9444
9445
0
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_client_hello, msg, len);
9446
0
    if (rv != SECSuccess) {
9447
0
        errCode = SEC_ERROR_LIBRARY_FAILURE;
9448
0
        desc = internal_error;
9449
0
        goto alert_loser;
9450
0
    }
9451
9452
    /* If we already have a session for this client, be sure to pick the same
9453
    ** cipher suite we picked before.  This is not a loop, despite appearances.
9454
    */
9455
0
    if (sid)
9456
0
        do {
9457
0
            ssl3CipherSuiteCfg *suite;
9458
0
            SSLVersionRange vrange = { ss->version, ss->version };
9459
9460
0
            suite = ss->cipherSuites;
9461
            /* Find the entry for the cipher suite used in the cached session. */
9462
0
            for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
9463
0
                if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
9464
0
                    break;
9465
0
            }
9466
0
            PORT_Assert(j > 0);
9467
0
            if (j == 0)
9468
0
                break;
9469
9470
            /* Double check that the cached cipher suite is still enabled,
9471
             * implemented, and allowed by policy.  Might have been disabled.
9472
             */
9473
0
            if (ssl3_config_match_init(ss) == 0) {
9474
0
                desc = handshake_failure;
9475
0
                errCode = PORT_GetError();
9476
0
                goto alert_loser;
9477
0
            }
9478
0
            if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss))
9479
0
                break;
9480
9481
            /* Double check that the cached cipher suite is in the client's
9482
             * list.  If it isn't, fall through and start a new session. */
9483
0
            for (i = 0; i + 1 < suites->len; i += 2) {
9484
0
                PRUint16 suite_i = (suites->data[i] << 8) | suites->data[i + 1];
9485
0
                if (suite_i == suite->cipher_suite) {
9486
0
                    ss->ssl3.hs.cipher_suite = suite_i;
9487
0
                    rv = ssl3_SetupCipherSuite(ss, PR_TRUE);
9488
0
                    if (rv != SECSuccess) {
9489
0
                        desc = internal_error;
9490
0
                        errCode = PORT_GetError();
9491
0
                        goto alert_loser;
9492
0
                    }
9493
9494
0
                    goto cipher_found;
9495
0
                }
9496
0
            }
9497
0
        } while (0);
9498
    /* START A NEW SESSION */
9499
9500
0
    rv = ssl3_NegotiateCipherSuite(ss, suites, PR_TRUE);
9501
0
    if (rv != SECSuccess) {
9502
0
        desc = handshake_failure;
9503
0
        errCode = PORT_GetError();
9504
0
        goto alert_loser;
9505
0
    }
9506
9507
0
cipher_found:
9508
0
    suites->data = NULL;
9509
9510
    /* If there are any failures while processing the old sid,
9511
     * we don't consider them to be errors.  Instead, We just behave
9512
     * as if the client had sent us no sid to begin with, and make a new one.
9513
     * The exception here is attempts to resume extended_master_secret
9514
     * sessions without the extension, which causes an alert.
9515
     */
9516
0
    if (sid != NULL)
9517
0
        do {
9518
0
            PK11SymKey *masterSecret;
9519
9520
0
            if (sid->version != ss->version ||
9521
0
                sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
9522
0
                break; /* not an error */
9523
0
            }
9524
9525
            /* server sids don't remember the server cert we previously sent,
9526
            ** but they do remember the slot we originally used, so we
9527
            ** can locate it again, provided that the current ssl socket
9528
            ** has had its server certs configured the same as the previous one.
9529
            */
9530
0
            ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType, sid->namedCurve);
9531
0
            if (!ss->sec.serverCert || !ss->sec.serverCert->serverCert) {
9532
                /* A compatible certificate must not have been configured.  It
9533
                 * might not be the same certificate, but we only find that out
9534
                 * when the ticket fails to decrypt. */
9535
0
                break;
9536
0
            }
9537
9538
            /* [draft-ietf-tls-session-hash-06; Section 5.3]
9539
             * o  If the original session did not use the "extended_master_secret"
9540
             *    extension but the new ClientHello contains the extension, then the
9541
             *    server MUST NOT perform the abbreviated handshake.  Instead, it
9542
             *    SHOULD continue with a full handshake (as described in
9543
             *    Section 5.2) to negotiate a new session.
9544
             *
9545
             * o  If the original session used the "extended_master_secret"
9546
             *    extension but the new ClientHello does not contain the extension,
9547
             *    the server MUST abort the abbreviated handshake.
9548
             */
9549
0
            if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
9550
0
                if (!sid->u.ssl3.keys.extendedMasterSecretUsed) {
9551
0
                    break; /* not an error */
9552
0
                }
9553
0
            } else {
9554
0
                if (sid->u.ssl3.keys.extendedMasterSecretUsed) {
9555
                    /* Note: we do not destroy the session */
9556
0
                    desc = handshake_failure;
9557
0
                    errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
9558
0
                    goto alert_loser;
9559
0
                }
9560
0
            }
9561
9562
0
            if (ss->sec.ci.sid) {
9563
0
                ssl_UncacheSessionID(ss);
9564
0
                PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */
9565
0
                if (ss->sec.ci.sid != sid) {
9566
0
                    ssl_FreeSID(ss->sec.ci.sid);
9567
0
                }
9568
0
                ss->sec.ci.sid = NULL;
9569
0
            }
9570
9571
            /* we need to resurrect the master secret.... */
9572
0
            rv = ssl3_UnwrapMasterSecretServer(ss, sid, &masterSecret);
9573
0
            if (rv != SECSuccess) {
9574
0
                break; /* not an error */
9575
0
            }
9576
9577
0
            ss->sec.ci.sid = sid;
9578
0
            if (sid->peerCert != NULL) {
9579
0
                ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
9580
0
            }
9581
9582
            /*
9583
             * Old SID passed all tests, so resume this old session.
9584
             */
9585
0
            SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_hits);
9586
0
            if (ss->statelessResume)
9587
0
                SSL_AtomicIncrementLong(&ssl3stats.hch_sid_stateless_resumes);
9588
0
            ss->ssl3.hs.isResuming = PR_TRUE;
9589
9590
0
            ss->sec.authType = sid->authType;
9591
0
            ss->sec.authKeyBits = sid->authKeyBits;
9592
0
            ss->sec.keaType = sid->keaType;
9593
0
            ss->sec.keaKeyBits = sid->keaKeyBits;
9594
0
            ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
9595
0
            ss->sec.signatureScheme = sid->sigScheme;
9596
9597
0
            ss->sec.localCert =
9598
0
                CERT_DupCertificate(ss->sec.serverCert->serverCert);
9599
9600
            /* Copy cached name in to pending spec */
9601
0
            if (sid != NULL &&
9602
0
                sid->version > SSL_LIBRARY_VERSION_3_0 &&
9603
0
                sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
9604
                /* Set server name from sid */
9605
0
                SECItem *sidName = &sid->u.ssl3.srvName;
9606
0
                SECItem *pwsName = &ss->ssl3.hs.srvVirtName;
9607
0
                if (pwsName->data) {
9608
0
                    SECITEM_FreeItem(pwsName, PR_FALSE);
9609
0
                }
9610
0
                rv = SECITEM_CopyItem(NULL, pwsName, sidName);
9611
0
                if (rv != SECSuccess) {
9612
0
                    errCode = PORT_GetError();
9613
0
                    desc = internal_error;
9614
0
                    goto alert_loser;
9615
0
                }
9616
0
            }
9617
9618
            /* Clean up sni name array */
9619
0
            ssl3_FreeSniNameArray(&ss->xtnData);
9620
9621
0
            ssl_GetXmitBufLock(ss);
9622
0
            haveXmitBufLock = PR_TRUE;
9623
9624
0
            rv = ssl3_SendServerHello(ss);
9625
0
            if (rv != SECSuccess) {
9626
0
                errCode = PORT_GetError();
9627
0
                goto loser;
9628
0
            }
9629
9630
            /* We are re-using the old MS, so no need to derive again. */
9631
0
            rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE);
9632
0
            if (rv != SECSuccess) {
9633
0
                errCode = PORT_GetError();
9634
0
                goto loser;
9635
0
            }
9636
9637
0
            rv = ssl3_SendChangeCipherSpecs(ss);
9638
0
            if (rv != SECSuccess) {
9639
0
                errCode = PORT_GetError();
9640
0
                goto loser;
9641
0
            }
9642
0
            rv = ssl3_SendFinished(ss, 0);
9643
0
            ss->ssl3.hs.ws = wait_change_cipher;
9644
0
            if (rv != SECSuccess) {
9645
0
                errCode = PORT_GetError();
9646
0
                goto loser;
9647
0
            }
9648
9649
0
            if (haveXmitBufLock) {
9650
0
                ssl_ReleaseXmitBufLock(ss);
9651
0
            }
9652
9653
0
            return SECSuccess;
9654
0
        } while (0);
9655
9656
0
    if (sid) { /* we had a sid, but it's no longer valid, free it */
9657
0
        ss->statelessResume = PR_FALSE;
9658
0
        SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
9659
0
        ssl_UncacheSessionID(ss);
9660
0
        ssl_FreeSID(sid);
9661
0
        sid = NULL;
9662
0
    }
9663
0
    SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
9664
9665
    /* We only send a session ticket extension if the client supports
9666
     * the extension and we are unable to resume.
9667
     *
9668
     * TODO: send a session ticket if performing a stateful
9669
     * resumption.  (As per RFC4507, a server may issue a session
9670
     * ticket while doing a (stateless or stateful) session resume,
9671
     * but OpenSSL-0.9.8g does not accept session tickets while
9672
     * resuming.)
9673
     */
9674
0
    if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
9675
0
        ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
9676
0
        ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_session_ticket_xtn,
9677
0
                                     ssl_SendEmptyExtension);
9678
0
    }
9679
9680
0
    rv = ssl3_ServerCallSNICallback(ss);
9681
0
    if (rv != SECSuccess) {
9682
        /* The alert has already been sent. */
9683
0
        errCode = PORT_GetError();
9684
0
        goto loser;
9685
0
    }
9686
9687
0
    rv = ssl3_SelectServerCert(ss);
9688
0
    if (rv != SECSuccess) {
9689
0
        errCode = PORT_GetError();
9690
0
        desc = handshake_failure;
9691
0
        goto alert_loser;
9692
0
    }
9693
9694
0
    sid = ssl3_NewSessionID(ss, PR_TRUE);
9695
0
    if (sid == NULL) {
9696
0
        errCode = PORT_GetError();
9697
0
        goto loser; /* memory error is set. */
9698
0
    }
9699
0
    ss->sec.ci.sid = sid;
9700
9701
0
    sid->u.ssl3.keys.extendedMasterSecretUsed =
9702
0
        ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
9703
0
    ss->ssl3.hs.isResuming = PR_FALSE;
9704
9705
0
    ssl_GetXmitBufLock(ss);
9706
0
    rv = ssl3_SendServerHelloSequence(ss);
9707
0
    ssl_ReleaseXmitBufLock(ss);
9708
0
    if (rv != SECSuccess) {
9709
0
        errCode = PORT_GetError();
9710
0
        desc = handshake_failure;
9711
0
        goto alert_loser;
9712
0
    }
9713
9714
0
    if (haveXmitBufLock) {
9715
0
        ssl_ReleaseXmitBufLock(ss);
9716
0
    }
9717
9718
0
    return SECSuccess;
9719
9720
0
alert_loser:
9721
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
9722
/* FALLTHRU */
9723
0
loser:
9724
0
    if (sid && sid != ss->sec.ci.sid) {
9725
0
        ssl_UncacheSessionID(ss);
9726
0
        ssl_FreeSID(sid);
9727
0
    }
9728
9729
0
    if (haveXmitBufLock) {
9730
0
        ssl_ReleaseXmitBufLock(ss);
9731
0
    }
9732
9733
0
    PORT_SetError(errCode);
9734
0
    return SECFailure;
9735
0
}
9736
9737
/*
9738
 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
9739
 * in asking to use the V3 handshake.
9740
 */
9741
SECStatus
9742
ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, unsigned int length,
9743
                         PRUint8 padding)
9744
0
{
9745
0
    sslSessionID *sid = NULL;
9746
0
    unsigned char *suites;
9747
0
    unsigned char *random;
9748
0
    SSL3ProtocolVersion version;
9749
0
    SECStatus rv;
9750
0
    unsigned int i;
9751
0
    unsigned int j;
9752
0
    unsigned int sid_length;
9753
0
    unsigned int suite_length;
9754
0
    unsigned int rand_length;
9755
0
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9756
0
    SSL3AlertDescription desc = handshake_failure;
9757
0
    unsigned int total = SSL_HL_CLIENT_HELLO_HBYTES;
9758
9759
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
9760
9761
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
9762
9763
0
    ssl_GetSSL3HandshakeLock(ss);
9764
9765
0
    version = (buffer[1] << 8) | buffer[2];
9766
0
    if (version < SSL_LIBRARY_VERSION_3_0) {
9767
0
        goto loser;
9768
0
    }
9769
9770
0
    ssl3_RestartHandshakeHashes(ss);
9771
9772
0
    if (ss->ssl3.hs.ws != wait_client_hello) {
9773
0
        desc = unexpected_message;
9774
0
        errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
9775
0
        goto alert_loser;
9776
0
    }
9777
9778
0
    total += suite_length = (buffer[3] << 8) | buffer[4];
9779
0
    total += sid_length = (buffer[5] << 8) | buffer[6];
9780
0
    total += rand_length = (buffer[7] << 8) | buffer[8];
9781
0
    total += padding;
9782
0
    ss->clientHelloVersion = version;
9783
9784
0
    if (version >= SSL_LIBRARY_VERSION_TLS_1_3) {
9785
        /* [draft-ietf-tls-tls-11; C.3] forbids sending a TLS 1.3
9786
         * ClientHello using the backwards-compatible format. */
9787
0
        desc = illegal_parameter;
9788
0
        errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9789
0
        goto alert_loser;
9790
0
    }
9791
9792
0
    rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
9793
0
    if (rv != SECSuccess) {
9794
        /* send back which ever alert client will understand. */
9795
0
        desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
9796
0
                                                   : handshake_failure;
9797
0
        errCode = SSL_ERROR_UNSUPPORTED_VERSION;
9798
0
        goto alert_loser;
9799
0
    }
9800
    /* ECH not possible here. */
9801
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
9802
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
9803
0
    if (!ss->firstHsDone) {
9804
0
        ssl_GetSpecWriteLock(ss);
9805
0
        ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
9806
0
        ssl_ReleaseSpecWriteLock(ss);
9807
0
    }
9808
9809
    /* if we get a non-zero SID, just ignore it. */
9810
0
    if (length != total) {
9811
0
        SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
9812
0
                 SSL_GETPID(), ss->fd, length, total));
9813
0
        desc = illegal_parameter;
9814
0
        errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9815
0
        goto alert_loser;
9816
0
    }
9817
9818
0
    suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
9819
0
    random = suites + suite_length + sid_length;
9820
9821
0
    if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
9822
0
        rand_length > SSL_MAX_CHALLENGE_BYTES) {
9823
0
        desc = illegal_parameter;
9824
0
        errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9825
0
        goto alert_loser;
9826
0
    }
9827
9828
0
    PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
9829
9830
0
    PORT_Memset(ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
9831
0
    PORT_Memcpy(&ss->ssl3.hs.client_random[SSL3_RANDOM_LENGTH - rand_length],
9832
0
                random, rand_length);
9833
9834
0
    PRINT_BUF(60, (ss, "client random:", ss->ssl3.hs.client_random,
9835
0
                   SSL3_RANDOM_LENGTH));
9836
9837
0
    if (ssl3_config_match_init(ss) == 0) {
9838
0
        errCode = PORT_GetError(); /* error code is already set. */
9839
0
        goto alert_loser;
9840
0
    }
9841
9842
    /* Select a cipher suite.
9843
    **
9844
    ** NOTE: This suite selection algorithm should be the same as the one in
9845
    ** ssl3_HandleClientHello().
9846
    */
9847
0
    for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
9848
0
        ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
9849
0
        SSLVersionRange vrange = { ss->version, ss->version };
9850
0
        if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
9851
0
            continue;
9852
0
        }
9853
0
        for (i = 0; i + 2 < suite_length; i += 3) {
9854
0
            PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9855
0
            if (suite_i == suite->cipher_suite) {
9856
0
                ss->ssl3.hs.cipher_suite = suite_i;
9857
0
                rv = ssl3_SetupCipherSuite(ss, PR_TRUE);
9858
0
                if (rv != SECSuccess) {
9859
0
                    desc = internal_error;
9860
0
                    errCode = PORT_GetError();
9861
0
                    goto alert_loser;
9862
0
                }
9863
0
                goto suite_found;
9864
0
            }
9865
0
        }
9866
0
    }
9867
0
    errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
9868
0
    goto alert_loser;
9869
9870
0
suite_found:
9871
9872
    /* If the ClientHello version is less than our maximum version, check for a
9873
     * TLS_FALLBACK_SCSV and reject the connection if found. */
9874
0
    if (ss->vrange.max > ss->clientHelloVersion) {
9875
0
        for (i = 0; i + 2 < suite_length; i += 3) {
9876
0
            PRUint16 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9877
0
            if (suite_i == TLS_FALLBACK_SCSV) {
9878
0
                desc = inappropriate_fallback;
9879
0
                errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
9880
0
                goto alert_loser;
9881
0
            }
9882
0
        }
9883
0
    }
9884
9885
    /* Look for the SCSV, and if found, treat it just like an empty RI
9886
     * extension by processing a local copy of an empty RI extension.
9887
     */
9888
0
    for (i = 0; i + 2 < suite_length; i += 3) {
9889
0
        PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9890
0
        if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
9891
0
            PRUint8 *b2 = (PRUint8 *)emptyRIext;
9892
0
            PRUint32 L2 = sizeof emptyRIext;
9893
0
            (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
9894
0
            break;
9895
0
        }
9896
0
    }
9897
9898
0
    if (ss->opt.requireSafeNegotiation &&
9899
0
        !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9900
0
        desc = handshake_failure;
9901
0
        errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
9902
0
        goto alert_loser;
9903
0
    }
9904
9905
0
    rv = ssl3_SelectServerCert(ss);
9906
0
    if (rv != SECSuccess) {
9907
0
        errCode = PORT_GetError();
9908
0
        desc = handshake_failure;
9909
0
        goto alert_loser;
9910
0
    }
9911
9912
    /* we don't even search for a cache hit here.  It's just a miss. */
9913
0
    SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
9914
0
    sid = ssl3_NewSessionID(ss, PR_TRUE);
9915
0
    if (sid == NULL) {
9916
0
        errCode = PORT_GetError();
9917
0
        goto loser; /* memory error is set. */
9918
0
    }
9919
0
    ss->sec.ci.sid = sid;
9920
    /* do not worry about memory leak of sid since it now belongs to ci */
9921
9922
    /* We have to update the handshake hashes before we can send stuff */
9923
0
    rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
9924
0
    if (rv != SECSuccess) {
9925
0
        errCode = PORT_GetError();
9926
0
        goto loser;
9927
0
    }
9928
9929
0
    ssl_GetXmitBufLock(ss);
9930
0
    rv = ssl3_SendServerHelloSequence(ss);
9931
0
    ssl_ReleaseXmitBufLock(ss);
9932
0
    if (rv != SECSuccess) {
9933
0
        errCode = PORT_GetError();
9934
0
        goto loser;
9935
0
    }
9936
9937
0
    ssl_ReleaseSSL3HandshakeLock(ss);
9938
0
    return SECSuccess;
9939
9940
0
alert_loser:
9941
0
    SSL3_SendAlert(ss, alert_fatal, desc);
9942
0
loser:
9943
0
    ssl_ReleaseSSL3HandshakeLock(ss);
9944
0
    PORT_SetError(errCode);
9945
0
    return SECFailure;
9946
0
}
9947
9948
SECStatus
9949
ssl_ConstructServerHello(sslSocket *ss, PRBool helloRetry,
9950
                         const sslBuffer *extensionBuf, sslBuffer *messageBuf)
9951
0
{
9952
0
    SECStatus rv;
9953
0
    SSL3ProtocolVersion version;
9954
0
    sslSessionID *sid = ss->sec.ci.sid;
9955
0
    const PRUint8 *random;
9956
9957
0
    version = PR_MIN(ss->version, SSL_LIBRARY_VERSION_TLS_1_2);
9958
0
    if (IS_DTLS(ss)) {
9959
0
        version = dtls_TLSVersionToDTLSVersion(version);
9960
0
    }
9961
0
    rv = sslBuffer_AppendNumber(messageBuf, version, 2);
9962
0
    if (rv != SECSuccess) {
9963
0
        return SECFailure;
9964
0
    }
9965
9966
0
    if (helloRetry) {
9967
0
        random = ssl_hello_retry_random;
9968
0
    } else {
9969
0
        rv = ssl_GenerateServerRandom(ss);
9970
0
        if (rv != SECSuccess) {
9971
0
            return SECFailure;
9972
0
        }
9973
0
        random = ss->ssl3.hs.server_random;
9974
0
    }
9975
0
    rv = sslBuffer_Append(messageBuf, random, SSL3_RANDOM_LENGTH);
9976
0
    if (rv != SECSuccess) {
9977
0
        return SECFailure;
9978
0
    }
9979
9980
0
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
9981
0
        if (sid) {
9982
0
            rv = sslBuffer_AppendVariable(messageBuf, sid->u.ssl3.sessionID,
9983
0
                                          sid->u.ssl3.sessionIDLength, 1);
9984
0
        } else {
9985
0
            rv = sslBuffer_AppendNumber(messageBuf, 0, 1);
9986
0
        }
9987
0
    } else {
9988
0
        rv = sslBuffer_AppendVariable(messageBuf, ss->ssl3.hs.fakeSid.data,
9989
0
                                      ss->ssl3.hs.fakeSid.len, 1);
9990
0
    }
9991
0
    if (rv != SECSuccess) {
9992
0
        return SECFailure;
9993
0
    }
9994
9995
0
    rv = sslBuffer_AppendNumber(messageBuf, ss->ssl3.hs.cipher_suite, 2);
9996
0
    if (rv != SECSuccess) {
9997
0
        return SECFailure;
9998
0
    }
9999
0
    rv = sslBuffer_AppendNumber(messageBuf, ssl_compression_null, 1);
10000
0
    if (rv != SECSuccess) {
10001
0
        return SECFailure;
10002
0
    }
10003
0
    if (SSL_BUFFER_LEN(extensionBuf)) {
10004
        /* Directly copy the extensions */
10005
0
        rv = sslBuffer_AppendBufferVariable(messageBuf, extensionBuf, 2);
10006
0
        if (rv != SECSuccess) {
10007
0
            return SECFailure;
10008
0
        }
10009
0
    }
10010
10011
0
    if (ss->xtnData.ech && ss->xtnData.ech->receivedInnerXtn) {
10012
        /* Signal ECH acceptance if we handled handled both CHOuter/CHInner (i.e.
10013
         * in shared mode), or if we received a CHInner in split/backend mode. */
10014
0
        if (ss->ssl3.hs.echAccepted || ss->opt.enableTls13BackendEch) {
10015
0
            if (helloRetry) {
10016
0
                return tls13_WriteServerEchHrrSignal(ss, SSL_BUFFER_BASE(messageBuf),
10017
0
                                                     SSL_BUFFER_LEN(messageBuf));
10018
0
            } else {
10019
0
                return tls13_WriteServerEchSignal(ss, SSL_BUFFER_BASE(messageBuf),
10020
0
                                                  SSL_BUFFER_LEN(messageBuf));
10021
0
            }
10022
0
        }
10023
0
    }
10024
0
    return SECSuccess;
10025
0
}
10026
10027
/* The negotiated version number has been already placed in ss->version.
10028
**
10029
** Called from:  ssl3_HandleClientHello                     (resuming session),
10030
**  ssl3_SendServerHelloSequence <- ssl3_HandleClientHello   (new session),
10031
**  ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
10032
*/
10033
SECStatus
10034
ssl3_SendServerHello(sslSocket *ss)
10035
0
{
10036
0
    SECStatus rv;
10037
0
    sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
10038
0
    sslBuffer messageBuf = SSL_BUFFER_EMPTY;
10039
10040
0
    SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
10041
0
                ss->fd));
10042
10043
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10044
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10045
10046
0
    PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
10047
0
    if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
10048
0
        PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
10049
0
        return SECFailure;
10050
0
    }
10051
10052
0
    rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_server_hello);
10053
0
    if (rv != SECSuccess) {
10054
0
        goto loser;
10055
0
    }
10056
10057
0
    rv = ssl_ConstructServerHello(ss, PR_FALSE, &extensionBuf, &messageBuf);
10058
0
    if (rv != SECSuccess) {
10059
0
        goto loser;
10060
0
    }
10061
10062
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello,
10063
0
                                    SSL_BUFFER_LEN(&messageBuf));
10064
0
    if (rv != SECSuccess) {
10065
0
        goto loser; /* err set by AppendHandshake. */
10066
0
    }
10067
10068
0
    rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&messageBuf),
10069
0
                              SSL_BUFFER_LEN(&messageBuf));
10070
0
    if (rv != SECSuccess) {
10071
0
        goto loser; /* err set by AppendHandshake. */
10072
0
    }
10073
10074
0
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
10075
0
        rv = ssl3_SetupBothPendingCipherSpecs(ss);
10076
0
        if (rv != SECSuccess) {
10077
0
            goto loser; /* err set */
10078
0
        }
10079
0
    }
10080
10081
0
    sslBuffer_Clear(&extensionBuf);
10082
0
    sslBuffer_Clear(&messageBuf);
10083
0
    return SECSuccess;
10084
10085
0
loser:
10086
0
    sslBuffer_Clear(&extensionBuf);
10087
0
    sslBuffer_Clear(&messageBuf);
10088
0
    return SECFailure;
10089
0
}
10090
10091
SECStatus
10092
ssl_CreateDHEKeyPair(const sslNamedGroupDef *groupDef,
10093
                     const ssl3DHParams *params,
10094
                     sslEphemeralKeyPair **keyPair)
10095
8
{
10096
8
    SECKEYDHParams dhParam;
10097
8
    SECKEYPublicKey *pubKey = NULL;   /* Ephemeral DH key */
10098
8
    SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */
10099
8
    sslEphemeralKeyPair *pair;
10100
10101
8
    dhParam.prime.data = params->prime.data;
10102
8
    dhParam.prime.len = params->prime.len;
10103
8
    dhParam.base.data = params->base.data;
10104
8
    dhParam.base.len = params->base.len;
10105
10106
8
    PRINT_BUF(60, (NULL, "Server DH p", dhParam.prime.data,
10107
8
                   dhParam.prime.len));
10108
8
    PRINT_BUF(60, (NULL, "Server DH g", dhParam.base.data,
10109
8
                   dhParam.base.len));
10110
10111
    /* Generate ephemeral DH keypair */
10112
8
    privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
10113
8
    if (!privKey || !pubKey) {
10114
0
        ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
10115
0
        return SECFailure;
10116
0
    }
10117
10118
8
    pair = ssl_NewEphemeralKeyPair(groupDef, privKey, pubKey);
10119
8
    if (!pair) {
10120
0
        SECKEY_DestroyPrivateKey(privKey);
10121
0
        SECKEY_DestroyPublicKey(pubKey);
10122
10123
0
        return SECFailure;
10124
0
    }
10125
10126
8
    *keyPair = pair;
10127
8
    return SECSuccess;
10128
8
}
10129
10130
static SECStatus
10131
ssl3_SendDHServerKeyExchange(sslSocket *ss)
10132
0
{
10133
0
    const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
10134
0
    SECStatus rv = SECFailure;
10135
0
    int length;
10136
0
    SECItem signed_hash = { siBuffer, NULL, 0 };
10137
0
    SSL3Hashes hashes;
10138
0
    SSLHashType hashAlg;
10139
10140
0
    const ssl3DHParams *params;
10141
0
    sslEphemeralKeyPair *keyPair;
10142
0
    SECKEYPublicKey *pubKey;
10143
0
    SECKEYPrivateKey *certPrivateKey;
10144
0
    const sslNamedGroupDef *groupDef;
10145
    /* Do this on the heap, this could be over 2k long. */
10146
0
    sslBuffer dhBuf = SSL_BUFFER_EMPTY;
10147
10148
0
    if (kea_def->kea != kea_dhe_dss && kea_def->kea != kea_dhe_rsa) {
10149
        /* TODO: Support DH_anon. It might be sufficient to drop the signature.
10150
                 See bug 1170510. */
10151
0
        PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
10152
0
        return SECFailure;
10153
0
    }
10154
10155
0
    rv = ssl_SelectDHEGroup(ss, &groupDef);
10156
0
    if (rv == SECFailure) {
10157
0
        PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
10158
0
        return SECFailure;
10159
0
    }
10160
0
    ss->sec.keaGroup = groupDef;
10161
10162
0
    params = ssl_GetDHEParams(groupDef);
10163
0
    rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
10164
0
    if (rv == SECFailure) {
10165
0
        ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
10166
0
        return SECFailure;
10167
0
    }
10168
0
    PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs);
10169
10170
0
    if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
10171
0
        hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
10172
0
    } else {
10173
        /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
10174
0
        hashAlg = ssl_hash_none;
10175
0
    }
10176
10177
0
    pubKey = keyPair->keys->pubKey;
10178
0
    PRINT_BUF(50, (ss, "DH public value:",
10179
0
                   pubKey->u.dh.publicValue.data,
10180
0
                   pubKey->u.dh.publicValue.len));
10181
0
    rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
10182
0
                               pubKey->u.dh.prime,
10183
0
                               pubKey->u.dh.base,
10184
0
                               pubKey->u.dh.publicValue,
10185
0
                               PR_TRUE /* padY */);
10186
0
    if (rv != SECSuccess) {
10187
0
        ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
10188
0
        goto loser;
10189
0
    }
10190
10191
0
    certPrivateKey = ss->sec.serverCert->serverKeyPair->privKey;
10192
0
    rv = ssl3_SignHashes(ss, &hashes, certPrivateKey, &signed_hash);
10193
0
    if (rv != SECSuccess) {
10194
0
        goto loser; /* ssl3_SignHashes has set err. */
10195
0
    }
10196
10197
0
    length = 2 + pubKey->u.dh.prime.len +
10198
0
             2 + pubKey->u.dh.base.len +
10199
0
             2 + pubKey->u.dh.prime.len +
10200
0
             2 + signed_hash.len;
10201
10202
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
10203
0
        length += 2;
10204
0
    }
10205
10206
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_key_exchange, length);
10207
0
    if (rv != SECSuccess) {
10208
0
        goto loser; /* err set by AppendHandshake. */
10209
0
    }
10210
10211
0
    rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.prime.data,
10212
0
                                      pubKey->u.dh.prime.len, 2);
10213
0
    if (rv != SECSuccess) {
10214
0
        goto loser; /* err set by AppendHandshake. */
10215
0
    }
10216
10217
0
    rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.base.data,
10218
0
                                      pubKey->u.dh.base.len, 2);
10219
0
    if (rv != SECSuccess) {
10220
0
        goto loser; /* err set by AppendHandshake. */
10221
0
    }
10222
10223
0
    rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE);
10224
0
    if (rv != SECSuccess) {
10225
0
        goto loser; /* err set by AppendPaddedDHKeyShare. */
10226
0
    }
10227
0
    rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
10228
0
    if (rv != SECSuccess) {
10229
0
        goto loser; /* err set by AppendHandshake. */
10230
0
    }
10231
10232
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
10233
0
        rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
10234
0
        if (rv != SECSuccess) {
10235
0
            goto loser; /* err set by AppendHandshake. */
10236
0
        }
10237
0
    }
10238
10239
0
    rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
10240
0
                                      signed_hash.len, 2);
10241
0
    if (rv != SECSuccess) {
10242
0
        goto loser; /* err set by AppendHandshake. */
10243
0
    }
10244
10245
0
    sslBuffer_Clear(&dhBuf);
10246
0
    PORT_Free(signed_hash.data);
10247
0
    return SECSuccess;
10248
10249
0
loser:
10250
0
    if (signed_hash.data)
10251
0
        PORT_Free(signed_hash.data);
10252
0
    sslBuffer_Clear(&dhBuf);
10253
0
    return SECFailure;
10254
0
}
10255
10256
static SECStatus
10257
ssl3_SendServerKeyExchange(sslSocket *ss)
10258
0
{
10259
0
    const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
10260
10261
0
    SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
10262
0
                SSL_GETPID(), ss->fd));
10263
10264
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10265
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10266
10267
0
    switch (kea_def->exchKeyType) {
10268
0
        case ssl_kea_dh: {
10269
0
            return ssl3_SendDHServerKeyExchange(ss);
10270
0
        }
10271
10272
0
        case ssl_kea_ecdh: {
10273
0
            return ssl3_SendECDHServerKeyExchange(ss);
10274
0
        }
10275
10276
0
        case ssl_kea_rsa:
10277
0
        case ssl_kea_null:
10278
0
        default:
10279
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10280
0
            break;
10281
0
    }
10282
10283
0
    return SECFailure;
10284
0
}
10285
10286
SECStatus
10287
ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool forCert,
10288
                   PRBool grease, sslBuffer *buf)
10289
13.7k
{
10290
13.7k
    SSLSignatureScheme filtered[MAX_SIGNATURE_SCHEMES] = { 0 };
10291
13.7k
    unsigned int filteredCount = 0;
10292
10293
13.7k
    SECStatus rv = ssl3_FilterSigAlgs(ss, minVersion, PR_FALSE, forCert,
10294
13.7k
                                      PR_ARRAY_SIZE(filtered),
10295
13.7k
                                      filtered, &filteredCount);
10296
13.7k
    if (rv != SECSuccess) {
10297
0
        return SECFailure;
10298
0
    }
10299
13.7k
    return ssl3_EncodeFilteredSigAlgs(ss, filtered, filteredCount, grease, buf);
10300
13.7k
}
10301
10302
SECStatus
10303
ssl3_EncodeFilteredSigAlgs(const sslSocket *ss, const SSLSignatureScheme *schemes,
10304
                           PRUint32 numSchemes, PRBool grease, sslBuffer *buf)
10305
13.7k
{
10306
13.7k
    if (!numSchemes) {
10307
0
        PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
10308
0
        return SECFailure;
10309
0
    }
10310
10311
13.7k
    unsigned int lengthOffset;
10312
13.7k
    SECStatus rv;
10313
10314
13.7k
    rv = sslBuffer_Skip(buf, 2, &lengthOffset);
10315
13.7k
    if (rv != SECSuccess) {
10316
0
        return SECFailure;
10317
0
    }
10318
10319
219k
    for (unsigned int i = 0; i < numSchemes; ++i) {
10320
205k
        rv = sslBuffer_AppendNumber(buf, schemes[i], 2);
10321
205k
        if (rv != SECSuccess) {
10322
0
            return SECFailure;
10323
0
        }
10324
205k
    }
10325
10326
    /* GREASE SignatureAlgorithms:
10327
     * A client MAY select one or more GREASE signature algorithm values and
10328
     * advertise them in the "signature_algorithms" or
10329
     * "signature_algorithms_cert" extensions, if sent [RFC8701, Section 3.1].
10330
     *
10331
     * When sending a CertificateRequest in TLS 1.3, a server MAY behave as
10332
     * follows: [...] A server MAY select one or more GREASE signature
10333
     * algorithm values and advertise them in the "signature_algorithms" or
10334
     * "signature_algorithms_cert" extensions, if present
10335
     * [RFC8701, Section 4.1]. */
10336
13.7k
    if (grease &&
10337
13.7k
        ((!ss->sec.isServer && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) ||
10338
0
         (ss->sec.isServer && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3))) {
10339
0
        PRUint16 value;
10340
0
        if (ss->sec.isServer) {
10341
0
            rv = tls13_RandomGreaseValue(&value);
10342
0
            if (rv != SECSuccess) {
10343
0
                return SECFailure;
10344
0
            }
10345
0
        } else {
10346
0
            value = ss->ssl3.hs.grease->idx[grease_sigalg];
10347
0
        }
10348
0
        rv = sslBuffer_AppendNumber(buf, value, 2);
10349
0
        if (rv != SECSuccess) {
10350
0
            return SECFailure;
10351
0
        }
10352
0
    }
10353
10354
13.7k
    return sslBuffer_InsertLength(buf, lengthOffset, 2);
10355
13.7k
}
10356
10357
/*
10358
 * In TLS 1.3 we are permitted to advertise support for PKCS#1
10359
 * schemes. This doesn't affect the signatures in TLS itself, just
10360
 * those on certificates. Not advertising PKCS#1 signatures creates a
10361
 * serious compatibility risk as it excludes many certificate chains
10362
 * that include PKCS#1. Hence, forCert is used to enable advertising
10363
 * PKCS#1 support. Note that we include these in signature_algorithms
10364
 * because we don't yet support signature_algorithms_cert. TLS 1.3
10365
 * requires that PKCS#1 schemes are placed last in the list if they
10366
 * are present. This sorting can be removed once we support
10367
 * signature_algorithms_cert.
10368
 */
10369
SECStatus
10370
ssl3_FilterSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool disableRsae,
10371
                   PRBool forCert,
10372
                   unsigned int maxSchemes, SSLSignatureScheme *filteredSchemes,
10373
                   unsigned int *numFilteredSchemes)
10374
13.7k
{
10375
13.7k
    PORT_Assert(filteredSchemes);
10376
13.7k
    PORT_Assert(numFilteredSchemes);
10377
13.7k
    PORT_Assert(maxSchemes >= ss->ssl3.signatureSchemeCount);
10378
13.7k
    if (maxSchemes < ss->ssl3.signatureSchemeCount) {
10379
0
        return SECFailure;
10380
0
    }
10381
10382
13.7k
    *numFilteredSchemes = 0;
10383
13.7k
    PRBool allowUnsortedPkcs1 = forCert && minVersion < SSL_LIBRARY_VERSION_TLS_1_3;
10384
219k
    for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
10385
205k
        if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
10386
0
            continue;
10387
0
        }
10388
205k
        if (ssl_SignatureSchemeAccepted(minVersion,
10389
205k
                                        ss->ssl3.signatureSchemes[i],
10390
205k
                                        allowUnsortedPkcs1)) {
10391
205k
            filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
10392
205k
        }
10393
205k
    }
10394
13.7k
    if (forCert && !allowUnsortedPkcs1) {
10395
0
        for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
10396
0
            if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
10397
0
                continue;
10398
0
            }
10399
0
            if (!ssl_SignatureSchemeAccepted(minVersion,
10400
0
                                             ss->ssl3.signatureSchemes[i],
10401
0
                                             PR_FALSE) &&
10402
0
                ssl_SignatureSchemeAccepted(minVersion,
10403
0
                                            ss->ssl3.signatureSchemes[i],
10404
0
                                            PR_TRUE)) {
10405
0
                filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
10406
0
            }
10407
0
        }
10408
0
    }
10409
13.7k
    return SECSuccess;
10410
13.7k
}
10411
10412
static SECStatus
10413
ssl3_SendCertificateRequest(sslSocket *ss)
10414
0
{
10415
0
    PRBool isTLS12;
10416
0
    const PRUint8 *certTypes;
10417
0
    SECStatus rv;
10418
0
    PRUint32 length;
10419
0
    const SECItem *names;
10420
0
    unsigned int calen;
10421
0
    unsigned int nnames;
10422
0
    const SECItem *name;
10423
0
    unsigned int i;
10424
0
    int certTypesLength;
10425
0
    PRUint8 sigAlgs[2 + MAX_SIGNATURE_SCHEMES * 2];
10426
0
    sslBuffer sigAlgsBuf = SSL_BUFFER(sigAlgs);
10427
10428
0
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
10429
0
                SSL_GETPID(), ss->fd));
10430
10431
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10432
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10433
10434
0
    isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
10435
10436
0
    rv = ssl_GetCertificateRequestCAs(ss, &calen, &names, &nnames);
10437
0
    if (rv != SECSuccess) {
10438
0
        return rv;
10439
0
    }
10440
0
    certTypes = certificate_types;
10441
0
    certTypesLength = sizeof certificate_types;
10442
10443
0
    length = 1 + certTypesLength + 2 + calen;
10444
0
    if (isTLS12) {
10445
0
        rv = ssl3_EncodeSigAlgs(ss, ss->version, PR_TRUE /* forCert */,
10446
0
                                PR_FALSE /* GREASE */, &sigAlgsBuf);
10447
0
        if (rv != SECSuccess) {
10448
0
            return rv;
10449
0
        }
10450
0
        length += SSL_BUFFER_LEN(&sigAlgsBuf);
10451
0
    }
10452
10453
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request, length);
10454
0
    if (rv != SECSuccess) {
10455
0
        return rv; /* err set by AppendHandshake. */
10456
0
    }
10457
0
    rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
10458
0
    if (rv != SECSuccess) {
10459
0
        return rv; /* err set by AppendHandshake. */
10460
0
    }
10461
0
    if (isTLS12) {
10462
0
        rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&sigAlgsBuf),
10463
0
                                  SSL_BUFFER_LEN(&sigAlgsBuf));
10464
0
        if (rv != SECSuccess) {
10465
0
            return rv; /* err set by AppendHandshake. */
10466
0
        }
10467
0
    }
10468
0
    rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
10469
0
    if (rv != SECSuccess) {
10470
0
        return rv; /* err set by AppendHandshake. */
10471
0
    }
10472
0
    for (i = 0, name = names; i < nnames; i++, name++) {
10473
0
        rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
10474
0
        if (rv != SECSuccess) {
10475
0
            return rv; /* err set by AppendHandshake. */
10476
0
        }
10477
0
    }
10478
10479
0
    return SECSuccess;
10480
0
}
10481
10482
static SECStatus
10483
ssl3_SendServerHelloDone(sslSocket *ss)
10484
0
{
10485
0
    SECStatus rv;
10486
10487
0
    SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
10488
0
                SSL_GETPID(), ss->fd));
10489
10490
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10491
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10492
10493
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello_done, 0);
10494
0
    if (rv != SECSuccess) {
10495
0
        return rv; /* err set by AppendHandshake. */
10496
0
    }
10497
0
    rv = ssl3_FlushHandshake(ss, 0);
10498
0
    if (rv != SECSuccess) {
10499
0
        return rv; /* error code set by ssl3_FlushHandshake */
10500
0
    }
10501
0
    return SECSuccess;
10502
0
}
10503
10504
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10505
 * a complete ssl3 Certificate Verify message
10506
 * Caller must hold Handshake and RecvBuf locks.
10507
 */
10508
static SECStatus
10509
ssl3_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
10510
0
{
10511
0
    SECItem signed_hash = { siBuffer, NULL, 0 };
10512
0
    SECStatus rv;
10513
0
    int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
10514
0
    SSL3AlertDescription desc = handshake_failure;
10515
0
    PRBool isTLS;
10516
0
    SSLSignatureScheme sigScheme;
10517
0
    SSL3Hashes hashes;
10518
0
    const PRUint8 *savedMsg = b;
10519
0
    const PRUint32 savedLen = length;
10520
10521
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
10522
0
                SSL_GETPID(), ss->fd));
10523
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10524
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10525
10526
0
    if (ss->ssl3.hs.ws != wait_cert_verify) {
10527
0
        desc = unexpected_message;
10528
0
        errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
10529
0
        goto alert_loser;
10530
0
    }
10531
10532
    /* TLS 1.3 is handled by tls13_HandleCertificateVerify */
10533
0
    PORT_Assert(ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2);
10534
10535
0
    if (ss->ssl3.prSpec->version == SSL_LIBRARY_VERSION_TLS_1_2) {
10536
0
        PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_record);
10537
0
        rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
10538
0
        if (rv != SECSuccess) {
10539
0
            if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
10540
0
                errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
10541
0
            }
10542
0
            goto loser; /* alert already sent */
10543
0
        }
10544
0
        rv = ssl_CheckSignatureSchemeConsistency(
10545
0
            ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo);
10546
0
        if (rv != SECSuccess) {
10547
0
            errCode = PORT_GetError();
10548
0
            desc = illegal_parameter;
10549
0
            goto alert_loser;
10550
0
        }
10551
10552
0
        rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
10553
0
                                       ss->ssl3.hs.messages.len,
10554
0
                                       ssl_SignatureSchemeToHashType(sigScheme),
10555
0
                                       &hashes);
10556
0
    } else {
10557
0
        PORT_Assert(ss->ssl3.hs.hashType != handshake_hash_record);
10558
0
        sigScheme = ssl_sig_none;
10559
0
        rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.prSpec, &hashes, 0);
10560
0
    }
10561
10562
0
    if (rv != SECSuccess) {
10563
0
        errCode = SSL_ERROR_DIGEST_FAILURE;
10564
0
        desc = decrypt_error;
10565
0
        goto alert_loser;
10566
0
    }
10567
10568
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
10569
0
    if (rv != SECSuccess) {
10570
0
        goto loser; /* malformed. */
10571
0
    }
10572
10573
0
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
10574
10575
    /* XXX verify that the key & kea match */
10576
0
    rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signed_hash);
10577
0
    if (rv != SECSuccess) {
10578
0
        errCode = PORT_GetError();
10579
0
        desc = isTLS ? decrypt_error : handshake_failure;
10580
0
        goto alert_loser;
10581
0
    }
10582
10583
0
    signed_hash.data = NULL;
10584
10585
0
    if (length != 0) {
10586
0
        desc = isTLS ? decode_error : illegal_parameter;
10587
0
        goto alert_loser; /* malformed */
10588
0
    }
10589
10590
0
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify,
10591
0
                                  savedMsg, savedLen);
10592
0
    if (rv != SECSuccess) {
10593
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10594
0
        return rv;
10595
0
    }
10596
10597
0
    ss->ssl3.hs.ws = wait_change_cipher;
10598
0
    return SECSuccess;
10599
10600
0
alert_loser:
10601
0
    SSL3_SendAlert(ss, alert_fatal, desc);
10602
0
loser:
10603
0
    PORT_SetError(errCode);
10604
0
    return SECFailure;
10605
0
}
10606
10607
/* find a slot that is able to generate a PMS and wrap it with RSA.
10608
 * Then generate and return the PMS.
10609
 * If the serverKeySlot parameter is non-null, this function will use
10610
 * that slot to do the job, otherwise it will find a slot.
10611
 *
10612
 * Called from  ssl3_DeriveConnectionKeys()  (above)
10613
 *      ssl3_SendRSAClientKeyExchange()     (above)
10614
 *      ssl3_HandleRSAClientKeyExchange()  (below)
10615
 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
10616
 */
10617
static PK11SymKey *
10618
ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
10619
                    PK11SlotInfo *serverKeySlot)
10620
1.63k
{
10621
1.63k
    PK11SymKey *pms = NULL;
10622
1.63k
    PK11SlotInfo *slot = serverKeySlot;
10623
1.63k
    void *pwArg = ss->pkcs11PinArg;
10624
1.63k
    SECItem param;
10625
1.63k
    CK_VERSION version;
10626
1.63k
    CK_MECHANISM_TYPE mechanism_array[3];
10627
10628
1.63k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10629
10630
1.63k
    if (slot == NULL) {
10631
1.63k
        SSLCipherAlgorithm calg;
10632
        /* The specReadLock would suffice here, but we cannot assert on
10633
        ** read locks.  Also, all the callers who call with a non-null
10634
        ** slot already hold the SpecWriteLock.
10635
        */
10636
1.63k
        PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
10637
1.63k
        PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
10638
10639
1.63k
        calg = spec->cipherDef->calg;
10640
10641
        /* First get an appropriate slot.  */
10642
1.63k
        mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
10643
1.63k
        mechanism_array[1] = CKM_RSA_PKCS;
10644
1.63k
        mechanism_array[2] = ssl3_Alg2Mech(calg);
10645
10646
1.63k
        slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
10647
1.63k
        if (slot == NULL) {
10648
            /* can't find a slot with all three, find a slot with the minimum */
10649
349
            slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
10650
349
            if (slot == NULL) {
10651
0
                PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
10652
0
                return pms; /* which is NULL */
10653
0
            }
10654
349
        }
10655
1.63k
    }
10656
10657
    /* Generate the pre-master secret ...  */
10658
1.63k
    if (IS_DTLS(ss)) {
10659
0
        SSL3ProtocolVersion temp;
10660
10661
0
        temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
10662
0
        version.major = MSB(temp);
10663
0
        version.minor = LSB(temp);
10664
1.63k
    } else {
10665
1.63k
        version.major = MSB(ss->clientHelloVersion);
10666
1.63k
        version.minor = LSB(ss->clientHelloVersion);
10667
1.63k
    }
10668
10669
1.63k
    param.data = (unsigned char *)&version;
10670
1.63k
    param.len = sizeof version;
10671
10672
1.63k
    pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
10673
1.63k
    if (!serverKeySlot)
10674
1.63k
        PK11_FreeSlot(slot);
10675
1.63k
    if (pms == NULL) {
10676
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10677
0
    }
10678
1.63k
    return pms;
10679
1.63k
}
10680
10681
static void
10682
ssl3_CSwapPK11SymKey(PK11SymKey **x, PK11SymKey **y, PRBool c)
10683
0
{
10684
0
    uintptr_t mask = (uintptr_t)c;
10685
0
    unsigned int i;
10686
0
    for (i = 1; i < sizeof(uintptr_t) * 8; i <<= 1) {
10687
0
        mask |= mask << i;
10688
0
    }
10689
0
    uintptr_t x_ptr = (uintptr_t)*x;
10690
0
    uintptr_t y_ptr = (uintptr_t)*y;
10691
0
    uintptr_t tmp = (x_ptr ^ y_ptr) & mask;
10692
0
    x_ptr = x_ptr ^ tmp;
10693
0
    y_ptr = y_ptr ^ tmp;
10694
0
    *x = (PK11SymKey *)x_ptr;
10695
0
    *y = (PK11SymKey *)y_ptr;
10696
0
}
10697
10698
/* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
10699
 * return any indication of failure of the Client Key Exchange message,
10700
 * where that failure is caused by the content of the client's message.
10701
 * This function must not return SECFailure for any reason that is directly
10702
 * or indirectly caused by the content of the client's encrypted PMS.
10703
 * We must not send an alert and also not drop the connection.
10704
 * Instead, we generate a random PMS.  This will cause a failure
10705
 * in the processing the finished message, which is exactly where
10706
 * the failure must occur.
10707
 *
10708
 * Called from ssl3_HandleClientKeyExchange
10709
 */
10710
static SECStatus
10711
ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
10712
                                PRUint8 *b,
10713
                                PRUint32 length,
10714
                                sslKeyPair *serverKeyPair)
10715
0
{
10716
0
    SECStatus rv;
10717
0
    SECItem enc_pms;
10718
0
    PK11SymKey *pms = NULL;
10719
0
    PK11SymKey *fauxPms = NULL;
10720
0
    PK11SlotInfo *slot = NULL;
10721
10722
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10723
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10724
0
    PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
10725
10726
0
    enc_pms.data = b;
10727
0
    enc_pms.len = length;
10728
10729
0
    if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
10730
0
        PRUint32 kLen;
10731
0
        rv = ssl3_ConsumeHandshakeNumber(ss, &kLen, 2, &enc_pms.data, &enc_pms.len);
10732
0
        if (rv != SECSuccess) {
10733
0
            PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10734
0
            return SECFailure;
10735
0
        }
10736
0
        if ((unsigned)kLen < enc_pms.len) {
10737
0
            enc_pms.len = kLen;
10738
0
        }
10739
0
    }
10740
10741
    /*
10742
     * Get as close to algorithm 2 from RFC 5246; Section 7.4.7.1
10743
     * as we can within the constraints of the PKCS#11 interface.
10744
     *
10745
     * 1. Unconditionally generate a bogus PMS (what RFC 5246
10746
     *    calls R).
10747
     * 2. Attempt the RSA decryption to recover the PMS (what
10748
     *    RFC 5246 calls M).
10749
     * 3. Set PMS = (M == NULL) ? R : M
10750
     * 4. Use ssl3_ComputeMasterSecret(PMS) to attempt to derive
10751
     *    the MS from PMS. This includes performing the version
10752
     *    check and length check.
10753
     * 5. If either the initial RSA decryption failed or
10754
     *    ssl3_ComputeMasterSecret(PMS) failed, then discard
10755
     *    M and set PMS = R. Else, discard R and set PMS = M.
10756
     *
10757
     * We do two derivations here because we can't rely on having
10758
     * a function that only performs the PMS version and length
10759
     * check. The only redundant cost is that this runs the PRF,
10760
     * which isn't necessary here.
10761
     */
10762
10763
    /* Generate the bogus PMS (R) */
10764
0
    slot = PK11_GetSlotFromPrivateKey(serverKeyPair->privKey);
10765
0
    if (!slot) {
10766
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10767
0
        return SECFailure;
10768
0
    }
10769
10770
0
    if (!PK11_DoesMechanism(slot, CKM_SSL3_MASTER_KEY_DERIVE)) {
10771
0
        PK11_FreeSlot(slot);
10772
0
        slot = PK11_GetBestSlot(CKM_SSL3_MASTER_KEY_DERIVE, NULL);
10773
0
        if (!slot) {
10774
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10775
0
            return SECFailure;
10776
0
        }
10777
0
    }
10778
10779
0
    ssl_GetSpecWriteLock(ss);
10780
0
    fauxPms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
10781
0
    ssl_ReleaseSpecWriteLock(ss);
10782
0
    PK11_FreeSlot(slot);
10783
10784
0
    if (fauxPms == NULL) {
10785
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10786
0
        return SECFailure;
10787
0
    }
10788
10789
    /*
10790
     * unwrap pms out of the incoming buffer
10791
     * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
10792
     *  the unwrap.  Rather, it is the mechanism with which the
10793
     *      unwrapped pms will be used.
10794
     */
10795
0
    pms = PK11_PubUnwrapSymKey(serverKeyPair->privKey, &enc_pms,
10796
0
                               CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
10797
    /* Temporarily use the PMS if unwrapping the real PMS fails. */
10798
0
    ssl3_CSwapPK11SymKey(&pms, &fauxPms, pms == NULL);
10799
10800
    /* Attempt to derive the MS from the PMS. This is the only way to
10801
     * check the version field in the RSA PMS. If this fails, we
10802
     * then use the faux PMS in place of the PMS. Note that this
10803
     * operation should never fail if we are using the faux PMS
10804
     * since it is correctly formatted. */
10805
0
    rv = ssl3_ComputeMasterSecret(ss, pms, NULL);
10806
10807
    /* If we succeeded, then select the true PMS, else select the FPMS. */
10808
0
    ssl3_CSwapPK11SymKey(&pms, &fauxPms, (rv != SECSuccess) & (fauxPms != NULL));
10809
10810
    /* This step will derive the MS from the PMS, among other things. */
10811
0
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
10812
10813
    /* Clear both PMS. */
10814
0
    PK11_FreeSymKey(pms);
10815
0
    PK11_FreeSymKey(fauxPms);
10816
10817
0
    if (rv != SECSuccess) {
10818
0
        (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10819
0
        return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
10820
0
    }
10821
10822
0
    return SECSuccess;
10823
0
}
10824
10825
static SECStatus
10826
ssl3_HandleDHClientKeyExchange(sslSocket *ss,
10827
                               PRUint8 *b,
10828
                               PRUint32 length,
10829
                               sslKeyPair *serverKeyPair)
10830
0
{
10831
0
    PK11SymKey *pms;
10832
0
    SECStatus rv;
10833
0
    SECKEYPublicKey clntPubKey;
10834
0
    CK_MECHANISM_TYPE target;
10835
0
    PRBool isTLS;
10836
10837
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10838
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10839
10840
0
    clntPubKey.keyType = dhKey;
10841
0
    clntPubKey.u.dh.prime.len = serverKeyPair->pubKey->u.dh.prime.len;
10842
0
    clntPubKey.u.dh.prime.data = serverKeyPair->pubKey->u.dh.prime.data;
10843
0
    clntPubKey.u.dh.base.len = serverKeyPair->pubKey->u.dh.base.len;
10844
0
    clntPubKey.u.dh.base.data = serverKeyPair->pubKey->u.dh.base.data;
10845
10846
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.dh.publicValue,
10847
0
                                       2, &b, &length);
10848
0
    if (rv != SECSuccess) {
10849
0
        return SECFailure;
10850
0
    }
10851
10852
0
    if (!ssl_IsValidDHEShare(&serverKeyPair->pubKey->u.dh.prime,
10853
0
                             &clntPubKey.u.dh.publicValue)) {
10854
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE);
10855
0
        return SECFailure;
10856
0
    }
10857
10858
0
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
10859
10860
0
    if (isTLS)
10861
0
        target = CKM_TLS_MASTER_KEY_DERIVE_DH;
10862
0
    else
10863
0
        target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
10864
10865
    /* Determine the PMS */
10866
0
    pms = PK11_PubDerive(serverKeyPair->privKey, &clntPubKey, PR_FALSE, NULL, NULL,
10867
0
                         CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
10868
0
    if (pms == NULL) {
10869
0
        ssl_FreeEphemeralKeyPairs(ss);
10870
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10871
0
        return SECFailure;
10872
0
    }
10873
10874
0
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
10875
0
    PK11_FreeSymKey(pms);
10876
0
    ssl_FreeEphemeralKeyPairs(ss);
10877
0
    return rv;
10878
0
}
10879
10880
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10881
 * a complete ssl3 ClientKeyExchange message from the remote client
10882
 * Caller must hold Handshake and RecvBuf locks.
10883
 */
10884
static SECStatus
10885
ssl3_HandleClientKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
10886
0
{
10887
0
    sslKeyPair *serverKeyPair = NULL;
10888
0
    SECStatus rv;
10889
0
    const ssl3KEADef *kea_def;
10890
10891
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
10892
0
                SSL_GETPID(), ss->fd));
10893
10894
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10895
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10896
10897
0
    if (ss->ssl3.hs.ws != wait_client_key) {
10898
0
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10899
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
10900
0
        return SECFailure;
10901
0
    }
10902
10903
0
    kea_def = ss->ssl3.hs.kea_def;
10904
10905
0
    if (kea_def->ephemeral) {
10906
0
        sslEphemeralKeyPair *keyPair;
10907
        /* There should be exactly one pair. */
10908
0
        PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
10909
0
        PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==
10910
0
                    PR_NEXT_LINK(&ss->ephemeralKeyPairs));
10911
0
        keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs);
10912
0
        serverKeyPair = keyPair->keys;
10913
0
        ss->sec.keaKeyBits =
10914
0
            SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
10915
0
    } else {
10916
0
        serverKeyPair = ss->sec.serverCert->serverKeyPair;
10917
0
        ss->sec.keaKeyBits = ss->sec.serverCert->serverKeyBits;
10918
0
    }
10919
10920
0
    if (!serverKeyPair) {
10921
0
        SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10922
0
        PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
10923
0
        return SECFailure;
10924
0
    }
10925
0
    PORT_Assert(serverKeyPair->pubKey);
10926
0
    PORT_Assert(serverKeyPair->privKey);
10927
10928
0
    ss->sec.keaType = kea_def->exchKeyType;
10929
10930
0
    switch (kea_def->exchKeyType) {
10931
0
        case ssl_kea_rsa:
10932
0
            rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKeyPair);
10933
0
            break;
10934
10935
0
        case ssl_kea_dh:
10936
0
            rv = ssl3_HandleDHClientKeyExchange(ss, b, length, serverKeyPair);
10937
0
            break;
10938
10939
0
        case ssl_kea_ecdh:
10940
0
            rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, serverKeyPair);
10941
0
            break;
10942
10943
0
        default:
10944
0
            (void)ssl3_HandshakeFailure(ss);
10945
0
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
10946
0
            return SECFailure;
10947
0
    }
10948
0
    ssl_FreeEphemeralKeyPairs(ss);
10949
0
    if (rv == SECSuccess) {
10950
0
        ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
10951
0
    } else {
10952
        /* PORT_SetError has been called by all the Handle*ClientKeyExchange
10953
         * functions above.  However, not all error paths result in an alert, so
10954
         * this ensures that the server knows about the error.  Note that if an
10955
         * alert was already sent, SSL3_SendAlert() is a noop. */
10956
0
        PRErrorCode errCode = PORT_GetError();
10957
0
        (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10958
0
        PORT_SetError(errCode);
10959
0
    }
10960
0
    return rv;
10961
0
}
10962
10963
/* This is TLS's equivalent of sending a no_certificate alert. */
10964
SECStatus
10965
ssl3_SendEmptyCertificate(sslSocket *ss)
10966
11
{
10967
11
    SECStatus rv;
10968
11
    unsigned int len = 0;
10969
11
    PRBool isTLS13 = PR_FALSE;
10970
11
    const SECItem *context;
10971
10972
11
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
10973
0
        PORT_Assert(ss->ssl3.hs.clientCertRequested);
10974
0
        context = &ss->xtnData.certReqContext;
10975
0
        len = context->len + 1;
10976
0
        isTLS13 = PR_TRUE;
10977
0
    }
10978
10979
11
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate, len + 3);
10980
11
    if (rv != SECSuccess) {
10981
0
        return rv;
10982
0
    }
10983
10984
11
    if (isTLS13) {
10985
0
        rv = ssl3_AppendHandshakeVariable(ss, context->data, context->len, 1);
10986
0
        if (rv != SECSuccess) {
10987
0
            return rv;
10988
0
        }
10989
0
    }
10990
10991
11
    return ssl3_AppendHandshakeNumber(ss, 0, 3);
10992
11
}
10993
10994
/*
10995
 * NewSessionTicket
10996
 * Called from ssl3_HandleFinished
10997
 */
10998
static SECStatus
10999
ssl3_SendNewSessionTicket(sslSocket *ss)
11000
0
{
11001
0
    SECItem ticket = { 0, NULL, 0 };
11002
0
    SECStatus rv;
11003
0
    NewSessionTicket nticket = { 0 };
11004
11005
0
    rv = ssl3_EncodeSessionTicket(ss, &nticket, NULL, 0,
11006
0
                                  ss->ssl3.pwSpec->masterSecret, &ticket);
11007
0
    if (rv != SECSuccess)
11008
0
        goto loser;
11009
11010
    /* Serialize the handshake message. Length =
11011
     * lifetime (4) + ticket length (2) + ticket. */
11012
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
11013
0
                                    4 + 2 + ticket.len);
11014
0
    if (rv != SECSuccess)
11015
0
        goto loser;
11016
11017
    /* This is a fixed value. */
11018
0
    rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
11019
0
    if (rv != SECSuccess)
11020
0
        goto loser;
11021
11022
    /* Encode the ticket. */
11023
0
    rv = ssl3_AppendHandshakeVariable(ss, ticket.data, ticket.len, 2);
11024
0
    if (rv != SECSuccess)
11025
0
        goto loser;
11026
11027
0
    rv = SECSuccess;
11028
11029
0
loser:
11030
0
    if (ticket.data) {
11031
0
        SECITEM_FreeItem(&ticket, PR_FALSE);
11032
0
    }
11033
0
    return rv;
11034
0
}
11035
11036
static SECStatus
11037
ssl3_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
11038
6
{
11039
6
    SECStatus rv;
11040
6
    SECItem ticketData;
11041
6
    PRUint32 temp;
11042
11043
6
    SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
11044
6
                SSL_GETPID(), ss->fd));
11045
11046
6
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11047
6
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11048
11049
6
    PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
11050
6
    PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket);
11051
11052
6
    if (ss->ssl3.hs.ws != wait_new_session_ticket) {
11053
6
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11054
6
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
11055
6
        return SECFailure;
11056
6
    }
11057
11058
    /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid
11059
     * until it has verified the server's Finished message." See the comment in
11060
     * ssl3_FinishHandshake for more details.
11061
     */
11062
0
    ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(ss);
11063
0
    if (length < 4) {
11064
0
        (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
11065
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
11066
0
        return SECFailure;
11067
0
    }
11068
11069
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 4, &b, &length);
11070
0
    if (rv != SECSuccess) {
11071
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
11072
0
        return SECFailure;
11073
0
    }
11074
0
    ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = temp;
11075
11076
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length);
11077
0
    if (rv != SECSuccess || length != 0) {
11078
0
        (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
11079
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
11080
0
        return SECFailure; /* malformed */
11081
0
    }
11082
    /* If the server sent a zero-length ticket, ignore it and keep the
11083
     * existing ticket. */
11084
0
    if (ticketData.len != 0) {
11085
0
        rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket,
11086
0
                              &ticketData);
11087
0
        if (rv != SECSuccess) {
11088
0
            return rv;
11089
0
        }
11090
0
        ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE;
11091
0
    }
11092
11093
0
    ss->ssl3.hs.ws = wait_change_cipher;
11094
0
    return SECSuccess;
11095
0
}
11096
11097
#ifdef NISCC_TEST
11098
static PRInt32 connNum = 0;
11099
11100
static SECStatus
11101
get_fake_cert(SECItem *pCertItem, int *pIndex)
11102
{
11103
    PRFileDesc *cf;
11104
    char *testdir;
11105
    char *startat;
11106
    char *stopat;
11107
    const char *extension;
11108
    int fileNum;
11109
    PRInt32 numBytes = 0;
11110
    PRStatus prStatus;
11111
    PRFileInfo info;
11112
    char cfn[100];
11113
11114
    pCertItem->data = 0;
11115
    if ((testdir = PR_GetEnvSecure("NISCC_TEST")) == NULL) {
11116
        return SECSuccess;
11117
    }
11118
    *pIndex = (NULL != strstr(testdir, "root"));
11119
    extension = (strstr(testdir, "simple") ? "" : ".der");
11120
    fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1;
11121
    if ((startat = PR_GetEnvSecure("START_AT")) != NULL) {
11122
        fileNum += atoi(startat);
11123
    }
11124
    if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL &&
11125
        fileNum >= atoi(stopat)) {
11126
        *pIndex = -1;
11127
        return SECSuccess;
11128
    }
11129
    snprintf(cfn, sizeof(cfn), "%s/%08d%s", testdir, fileNum, extension);
11130
    cf = PR_Open(cfn, PR_RDONLY, 0);
11131
    if (!cf) {
11132
        goto loser;
11133
    }
11134
    prStatus = PR_GetOpenFileInfo(cf, &info);
11135
    if (prStatus != PR_SUCCESS) {
11136
        PR_Close(cf);
11137
        goto loser;
11138
    }
11139
    pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
11140
    if (pCertItem) {
11141
        numBytes = PR_Read(cf, pCertItem->data, info.size);
11142
    }
11143
    PR_Close(cf);
11144
    if (numBytes != info.size) {
11145
        SECITEM_FreeItem(pCertItem, PR_FALSE);
11146
        PORT_SetError(SEC_ERROR_IO);
11147
        goto loser;
11148
    }
11149
    fprintf(stderr, "using %s\n", cfn);
11150
    return SECSuccess;
11151
11152
loser:
11153
    fprintf(stderr, "failed to use %s\n", cfn);
11154
    *pIndex = -1;
11155
    return SECFailure;
11156
}
11157
#endif
11158
11159
/*
11160
 * Used by both client and server.
11161
 * Called from HandleServerHelloDone and from SendServerHelloSequence.
11162
 */
11163
static SECStatus
11164
ssl3_SendCertificate(sslSocket *ss)
11165
0
{
11166
0
    SECStatus rv;
11167
0
    CERTCertificateList *certChain;
11168
0
    int certChainLen = 0;
11169
0
    int i;
11170
#ifdef NISCC_TEST
11171
    SECItem fakeCert;
11172
    int ndex = -1;
11173
#endif
11174
0
    PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
11175
0
    SECItem context = { siBuffer, NULL, 0 };
11176
0
    unsigned int contextLen = 0;
11177
11178
0
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
11179
0
                SSL_GETPID(), ss->fd));
11180
11181
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11182
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11183
0
    PR_ASSERT(!ss->ssl3.hs.clientCertificatePending);
11184
11185
0
    if (ss->sec.localCert)
11186
0
        CERT_DestroyCertificate(ss->sec.localCert);
11187
0
    if (ss->sec.isServer) {
11188
        /* A server certificate is selected in ssl3_HandleClientHello. */
11189
0
        PORT_Assert(ss->sec.serverCert);
11190
11191
0
        certChain = ss->sec.serverCert->serverCertChain;
11192
0
        ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
11193
0
    } else {
11194
0
        certChain = ss->ssl3.clientCertChain;
11195
0
        ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
11196
0
    }
11197
11198
#ifdef NISCC_TEST
11199
    rv = get_fake_cert(&fakeCert, &ndex);
11200
#endif
11201
11202
0
    if (isTLS13) {
11203
0
        contextLen = 1; /* Size of the context length */
11204
0
        if (!ss->sec.isServer) {
11205
0
            PORT_Assert(ss->ssl3.hs.clientCertRequested);
11206
0
            context = ss->xtnData.certReqContext;
11207
0
            contextLen += context.len;
11208
0
        }
11209
0
    }
11210
0
    if (certChain) {
11211
0
        for (i = 0; i < certChain->len; i++) {
11212
#ifdef NISCC_TEST
11213
            if (fakeCert.len > 0 && i == ndex) {
11214
                certChainLen += fakeCert.len + 3;
11215
            } else {
11216
                certChainLen += certChain->certs[i].len + 3;
11217
            }
11218
#else
11219
0
            certChainLen += certChain->certs[i].len + 3;
11220
0
#endif
11221
0
        }
11222
0
    }
11223
11224
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate,
11225
0
                                    contextLen + certChainLen + 3);
11226
0
    if (rv != SECSuccess) {
11227
0
        return rv; /* err set by AppendHandshake. */
11228
0
    }
11229
11230
0
    if (isTLS13) {
11231
0
        rv = ssl3_AppendHandshakeVariable(ss, context.data,
11232
0
                                          context.len, 1);
11233
0
        if (rv != SECSuccess) {
11234
0
            return rv; /* err set by AppendHandshake. */
11235
0
        }
11236
0
    }
11237
11238
0
    rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3);
11239
0
    if (rv != SECSuccess) {
11240
0
        return rv; /* err set by AppendHandshake. */
11241
0
    }
11242
0
    if (certChain) {
11243
0
        for (i = 0; i < certChain->len; i++) {
11244
#ifdef NISCC_TEST
11245
            if (fakeCert.len > 0 && i == ndex) {
11246
                rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
11247
                                                  fakeCert.len, 3);
11248
                SECITEM_FreeItem(&fakeCert, PR_FALSE);
11249
            } else {
11250
                rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
11251
                                                  certChain->certs[i].len, 3);
11252
            }
11253
#else
11254
0
            rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
11255
0
                                              certChain->certs[i].len, 3);
11256
0
#endif
11257
0
            if (rv != SECSuccess) {
11258
0
                return rv; /* err set by AppendHandshake. */
11259
0
            }
11260
0
        }
11261
0
    }
11262
11263
0
    return SECSuccess;
11264
0
}
11265
11266
/*
11267
 * Used by server only.
11268
 * single-stapling, send only a single cert status
11269
 */
11270
SECStatus
11271
ssl3_SendCertificateStatus(sslSocket *ss)
11272
0
{
11273
0
    SECStatus rv;
11274
0
    int len = 0;
11275
0
    SECItemArray *statusToSend = NULL;
11276
0
    const sslServerCert *serverCert;
11277
11278
0
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
11279
0
                SSL_GETPID(), ss->fd));
11280
11281
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11282
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11283
0
    PORT_Assert(ss->sec.isServer);
11284
11285
0
    if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
11286
0
        return SECSuccess;
11287
11288
    /* Use certStatus based on the cert being used. */
11289
0
    serverCert = ss->sec.serverCert;
11290
0
    if (serverCert->certStatusArray && serverCert->certStatusArray->len) {
11291
0
        statusToSend = serverCert->certStatusArray;
11292
0
    }
11293
0
    if (!statusToSend)
11294
0
        return SECSuccess;
11295
11296
    /* Use the array's first item only (single stapling) */
11297
0
    len = 1 + statusToSend->items[0].len + 3;
11298
11299
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_status, len);
11300
0
    if (rv != SECSuccess) {
11301
0
        return rv; /* err set by AppendHandshake. */
11302
0
    }
11303
0
    rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
11304
0
    if (rv != SECSuccess)
11305
0
        return rv; /* err set by AppendHandshake. */
11306
11307
0
    rv = ssl3_AppendHandshakeVariable(ss,
11308
0
                                      statusToSend->items[0].data,
11309
0
                                      statusToSend->items[0].len,
11310
0
                                      3);
11311
0
    if (rv != SECSuccess)
11312
0
        return rv; /* err set by AppendHandshake. */
11313
11314
0
    return SECSuccess;
11315
0
}
11316
11317
/* This is used to delete the CA certificates in the peer certificate chain
11318
 * from the cert database after they've been validated.
11319
 */
11320
void
11321
ssl3_CleanupPeerCerts(sslSocket *ss)
11322
14.1k
{
11323
14.1k
    PLArenaPool *arena = ss->ssl3.peerCertArena;
11324
14.1k
    ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
11325
11326
19.9k
    for (; certs; certs = certs->next) {
11327
5.84k
        CERT_DestroyCertificate(certs->cert);
11328
5.84k
    }
11329
14.1k
    if (arena)
11330
9.04k
        PORT_FreeArena(arena, PR_FALSE);
11331
14.1k
    ss->ssl3.peerCertArena = NULL;
11332
14.1k
    ss->ssl3.peerCertChain = NULL;
11333
11334
14.1k
    if (ss->sec.peerCert != NULL) {
11335
4.02k
        if (ss->sec.peerKey) {
11336
0
            SECKEY_DestroyPublicKey(ss->sec.peerKey);
11337
0
            ss->sec.peerKey = NULL;
11338
0
        }
11339
4.02k
        CERT_DestroyCertificate(ss->sec.peerCert);
11340
4.02k
        ss->sec.peerCert = NULL;
11341
4.02k
    }
11342
14.1k
}
11343
11344
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11345
 * a complete ssl3 CertificateStatus message.
11346
 * Caller must hold Handshake and RecvBuf locks.
11347
 */
11348
static SECStatus
11349
ssl3_HandleCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
11350
2
{
11351
2
    SECStatus rv;
11352
11353
2
    if (ss->ssl3.hs.ws != wait_certificate_status) {
11354
2
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11355
2
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
11356
2
        return SECFailure;
11357
2
    }
11358
11359
0
    rv = ssl_ReadCertificateStatus(ss, b, length);
11360
0
    if (rv != SECSuccess) {
11361
0
        return SECFailure; /* code already set */
11362
0
    }
11363
11364
0
    return ssl3_AuthCertificate(ss);
11365
0
}
11366
11367
SECStatus
11368
ssl_ReadCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
11369
0
{
11370
0
    PRUint32 status, len;
11371
0
    SECStatus rv;
11372
11373
0
    PORT_Assert(!ss->sec.isServer);
11374
11375
    /* Consume the CertificateStatusType enum */
11376
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &status, 1, &b, &length);
11377
0
    if (rv != SECSuccess || status != 1 /* ocsp */) {
11378
0
        return ssl3_DecodeError(ss);
11379
0
    }
11380
11381
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &len, 3, &b, &length);
11382
0
    if (rv != SECSuccess || len != length) {
11383
0
        return ssl3_DecodeError(ss);
11384
0
    }
11385
11386
0
#define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */
11387
0
    if (length > MAX_CERTSTATUS_LEN) {
11388
0
        ssl3_DecodeError(ss); /* sets error code */
11389
0
        return SECFailure;
11390
0
    }
11391
0
#undef MAX_CERTSTATUS_LEN
11392
11393
    /* Array size 1, because we currently implement single-stapling only */
11394
0
    SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
11395
0
    if (!ss->sec.ci.sid->peerCertStatus.items)
11396
0
        return SECFailure; /* code already set */
11397
11398
0
    ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
11399
11400
0
    if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
11401
0
        SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
11402
0
        return SECFailure; /* code already set */
11403
0
    }
11404
11405
0
    PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
11406
0
    ss->sec.ci.sid->peerCertStatus.items[0].len = length;
11407
0
    ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
11408
0
    return SECSuccess;
11409
0
}
11410
11411
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11412
 * a complete ssl3 Certificate message.
11413
 * Caller must hold Handshake and RecvBuf locks.
11414
 */
11415
static SECStatus
11416
ssl3_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
11417
9.08k
{
11418
9.08k
    SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
11419
9.08k
                SSL_GETPID(), ss->fd));
11420
9.08k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11421
9.08k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11422
11423
9.08k
    if ((ss->sec.isServer && ss->ssl3.hs.ws != wait_client_cert) ||
11424
9.08k
        (!ss->sec.isServer && ss->ssl3.hs.ws != wait_server_cert)) {
11425
8
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11426
8
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE);
11427
8
        return SECFailure;
11428
8
    }
11429
11430
9.07k
    if (ss->sec.isServer) {
11431
0
        dtls_ReceivedFirstMessageInFlight(ss);
11432
0
    }
11433
11434
9.07k
    return ssl3_CompleteHandleCertificate(ss, b, length);
11435
9.08k
}
11436
11437
/* Called from ssl3_HandleCertificate
11438
 */
11439
SECStatus
11440
ssl3_CompleteHandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
11441
9.07k
{
11442
9.07k
    ssl3CertNode *c;
11443
9.07k
    ssl3CertNode *lastCert = NULL;
11444
9.07k
    PRUint32 remaining = 0;
11445
9.07k
    PRUint32 size;
11446
9.07k
    SECStatus rv;
11447
9.07k
    PRBool isServer = ss->sec.isServer;
11448
9.07k
    PRBool isTLS;
11449
9.07k
    SSL3AlertDescription desc;
11450
9.07k
    int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
11451
9.07k
    SECItem certItem;
11452
11453
9.07k
    ssl3_CleanupPeerCerts(ss);
11454
9.07k
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
11455
11456
    /* It is reported that some TLS client sends a Certificate message
11457
    ** with a zero-length message body.  We'll treat that case like a
11458
    ** normal no_certificates message to maximize interoperability.
11459
    */
11460
9.07k
    if (length) {
11461
9.07k
        rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 3, &b, &length);
11462
9.07k
        if (rv != SECSuccess)
11463
2
            goto loser; /* fatal alert already sent by ConsumeHandshake. */
11464
9.07k
        if (remaining > length)
11465
25
            goto decode_loser;
11466
9.07k
    }
11467
11468
9.04k
    if (!remaining) {
11469
2
        if (!(isTLS && isServer)) {
11470
2
            desc = bad_certificate;
11471
2
            goto alert_loser;
11472
2
        }
11473
        /* This is TLS's version of a no_certificate alert. */
11474
        /* I'm a server. I've requested a client cert. He hasn't got one. */
11475
0
        rv = ssl3_HandleNoCertificate(ss);
11476
0
        if (rv != SECSuccess) {
11477
0
            errCode = PORT_GetError();
11478
0
            goto loser;
11479
0
        }
11480
11481
0
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11482
0
            ss->ssl3.hs.ws = wait_client_key;
11483
0
        } else {
11484
0
            TLS13_SET_HS_STATE(ss, wait_finished);
11485
0
        }
11486
0
        return SECSuccess;
11487
0
    }
11488
11489
9.04k
    ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
11490
9.04k
    if (ss->ssl3.peerCertArena == NULL) {
11491
0
        goto loser; /* don't send alerts on memory errors */
11492
0
    }
11493
11494
    /* First get the peer cert. */
11495
9.04k
    if (remaining < 3)
11496
1
        goto decode_loser;
11497
11498
9.04k
    remaining -= 3;
11499
9.04k
    rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
11500
9.04k
    if (rv != SECSuccess)
11501
0
        goto loser; /* fatal alert already sent by ConsumeHandshake. */
11502
9.04k
    if (size == 0 || remaining < size)
11503
24
        goto decode_loser;
11504
11505
9.02k
    certItem.data = b;
11506
9.02k
    certItem.len = size;
11507
9.02k
    b += size;
11508
9.02k
    length -= size;
11509
9.02k
    remaining -= size;
11510
11511
9.02k
    ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
11512
9.02k
                                               PR_FALSE, PR_TRUE);
11513
9.02k
    if (ss->sec.peerCert == NULL) {
11514
        /* We should report an alert if the cert was bad, but not if the
11515
         * problem was just some local problem, like memory error.
11516
         */
11517
117
        goto ambiguous_err;
11518
117
    }
11519
11520
    /* Now get all of the CA certs. */
11521
14.7k
    while (remaining > 0) {
11522
6.47k
        if (remaining < 3)
11523
5
            goto decode_loser;
11524
11525
6.46k
        remaining -= 3;
11526
6.46k
        rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
11527
6.46k
        if (rv != SECSuccess)
11528
0
            goto loser; /* fatal alert already sent by ConsumeHandshake. */
11529
6.46k
        if (size == 0 || remaining < size)
11530
340
            goto decode_loser;
11531
11532
6.12k
        certItem.data = b;
11533
6.12k
        certItem.len = size;
11534
6.12k
        b += size;
11535
6.12k
        length -= size;
11536
6.12k
        remaining -= size;
11537
11538
6.12k
        c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
11539
6.12k
        if (c == NULL) {
11540
0
            goto loser; /* don't send alerts on memory errors */
11541
0
        }
11542
11543
6.12k
        c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
11544
6.12k
                                          PR_FALSE, PR_TRUE);
11545
6.12k
        if (c->cert == NULL) {
11546
279
            goto ambiguous_err;
11547
279
        }
11548
11549
5.84k
        c->next = NULL;
11550
5.84k
        if (lastCert) {
11551
4.66k
            lastCert->next = c;
11552
4.66k
        } else {
11553
1.18k
            ss->ssl3.peerCertChain = c;
11554
1.18k
        }
11555
5.84k
        lastCert = c;
11556
5.84k
    }
11557
11558
8.28k
    SECKEY_UpdateCertPQG(ss->sec.peerCert);
11559
11560
8.28k
    if (!isServer &&
11561
8.28k
        ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
11562
8.28k
        ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
11563
0
        ss->ssl3.hs.ws = wait_certificate_status;
11564
0
        rv = SECSuccess;
11565
8.28k
    } else {
11566
8.28k
        rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
11567
8.28k
    }
11568
11569
8.28k
    return rv;
11570
11571
396
ambiguous_err:
11572
396
    errCode = PORT_GetError();
11573
396
    switch (errCode) {
11574
0
        case PR_OUT_OF_MEMORY_ERROR:
11575
0
        case SEC_ERROR_BAD_DATABASE:
11576
0
        case SEC_ERROR_NO_MEMORY:
11577
0
            if (isTLS) {
11578
0
                desc = internal_error;
11579
0
                goto alert_loser;
11580
0
            }
11581
0
            goto loser;
11582
396
    }
11583
396
    ssl3_SendAlertForCertError(ss, errCode);
11584
396
    goto loser;
11585
11586
395
decode_loser:
11587
395
    desc = isTLS ? decode_error : bad_certificate;
11588
11589
397
alert_loser:
11590
397
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
11591
11592
795
loser:
11593
795
    (void)ssl_MapLowLevelError(errCode);
11594
795
    return SECFailure;
11595
397
}
11596
11597
SECStatus
11598
ssl_SetAuthKeyBits(sslSocket *ss, const SECKEYPublicKey *pubKey)
11599
8.06k
{
11600
8.06k
    SECStatus rv;
11601
8.06k
    PRUint32 minKey = 0;
11602
8.06k
    PRInt32 optval;
11603
8.06k
    PRBool usePolicyLength = PR_TRUE;
11604
11605
8.06k
    rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS, &optval);
11606
8.06k
    if (rv == SECSuccess) {
11607
8.06k
        usePolicyLength = (PRBool)((optval & NSS_KEY_SIZE_POLICY_SSL_FLAG) == NSS_KEY_SIZE_POLICY_SSL_FLAG);
11608
8.06k
    }
11609
11610
8.06k
    ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(pubKey);
11611
8.06k
    switch (SECKEY_GetPublicKeyType(pubKey)) {
11612
2.96k
        case rsaKey:
11613
2.96k
        case rsaPssKey:
11614
2.96k
        case rsaOaepKey:
11615
2.96k
            rv = usePolicyLength ? NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &optval)
11616
2.96k
                                 : SECFailure;
11617
2.96k
            if (rv == SECSuccess && optval > 0) {
11618
2.96k
                minKey = (PRUint32)optval;
11619
2.96k
            } else {
11620
0
                minKey = SSL_RSA_MIN_MODULUS_BITS;
11621
0
            }
11622
2.96k
            break;
11623
11624
532
        case dsaKey:
11625
532
            rv = usePolicyLength ? NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &optval)
11626
532
                                 : SECFailure;
11627
532
            if (rv == SECSuccess && optval > 0) {
11628
532
                minKey = (PRUint32)optval;
11629
532
            } else {
11630
0
                minKey = SSL_DSA_MIN_P_BITS;
11631
0
            }
11632
532
            break;
11633
11634
3
        case dhKey:
11635
3
            rv = usePolicyLength ? NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &optval)
11636
3
                                 : SECFailure;
11637
3
            if (rv == SECSuccess && optval > 0) {
11638
3
                minKey = (PRUint32)optval;
11639
3
            } else {
11640
0
                minKey = SSL_DH_MIN_P_BITS;
11641
0
            }
11642
3
            break;
11643
11644
4.56k
        case ecKey:
11645
4.56k
            rv = usePolicyLength ? NSS_OptionGet(NSS_ECC_MIN_KEY_SIZE, &optval)
11646
4.56k
                                 : SECFailure;
11647
4.56k
            if (rv == SECSuccess && optval > 0) {
11648
4.56k
                minKey = (PRUint32)optval;
11649
4.56k
            } else {
11650
                /* Don't check EC strength here on the understanding that we
11651
                 * only support curves we like. */
11652
0
                minKey = ss->sec.authKeyBits;
11653
0
            }
11654
4.56k
            break;
11655
11656
0
        default:
11657
0
            FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
11658
0
            return SECFailure;
11659
8.06k
    }
11660
11661
    /* Too small: not good enough. Send a fatal alert. */
11662
8.06k
    if (ss->sec.authKeyBits < minKey) {
11663
104
        FATAL_ERROR(ss, SSL_ERROR_WEAK_SERVER_CERT_KEY,
11664
104
                    ss->version >= SSL_LIBRARY_VERSION_TLS_1_0
11665
104
                        ? insufficient_security
11666
104
                        : illegal_parameter);
11667
104
        return SECFailure;
11668
104
    }
11669
11670
    /* PreliminaryChannelInfo.authKeyBits, scheme, and peerDelegCred are now valid. */
11671
7.96k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_peer_auth;
11672
11673
7.96k
    return SECSuccess;
11674
8.06k
}
11675
11676
SECStatus
11677
ssl3_HandleServerSpki(sslSocket *ss)
11678
8.28k
{
11679
8.28k
    PORT_Assert(!ss->sec.isServer);
11680
8.28k
    SECKEYPublicKey *pubKey;
11681
11682
8.28k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
11683
8.28k
        tls13_IsVerifyingWithDelegatedCredential(ss)) {
11684
0
        sslDelegatedCredential *dc = ss->xtnData.peerDelegCred;
11685
0
        pubKey = SECKEY_ExtractPublicKey(dc->spki);
11686
0
        if (!pubKey) {
11687
0
            PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
11688
0
            return SECFailure;
11689
0
        }
11690
11691
        /* Because we have only a single authType (ssl_auth_tls13_any)
11692
         * for TLS 1.3 at this point, set the scheme so that the
11693
         * callback can interpret |authKeyBits| correctly.
11694
         */
11695
0
        ss->sec.signatureScheme = dc->expectedCertVerifyAlg;
11696
8.28k
    } else {
11697
8.28k
        pubKey = CERT_ExtractPublicKey(ss->sec.peerCert);
11698
8.28k
        if (!pubKey) {
11699
213
            PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
11700
213
            return SECFailure;
11701
213
        }
11702
8.28k
    }
11703
11704
8.06k
    SECStatus rv = ssl_SetAuthKeyBits(ss, pubKey);
11705
8.06k
    SECKEY_DestroyPublicKey(pubKey);
11706
8.06k
    if (rv != SECSuccess) {
11707
104
        return rv; /* Alert sent and code set. */
11708
104
    }
11709
11710
7.96k
    return SECSuccess;
11711
8.06k
}
11712
11713
SECStatus
11714
ssl3_AuthCertificate(sslSocket *ss)
11715
8.28k
{
11716
8.28k
    SECStatus rv;
11717
8.28k
    PRBool isServer = ss->sec.isServer;
11718
8.28k
    int errCode;
11719
11720
8.28k
    ss->ssl3.hs.authCertificatePending = PR_FALSE;
11721
11722
8.28k
    PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
11723
8.28k
                ssl_preinfo_all);
11724
11725
8.28k
    if (!ss->sec.isServer) {
11726
        /* Set the |spki| used to verify the handshake. When verifying with a
11727
         * delegated credential (DC), this corresponds to the DC public key;
11728
         * otherwise it correspond to the public key of the peer's end-entity
11729
         * certificate. */
11730
8.28k
        rv = ssl3_HandleServerSpki(ss);
11731
8.28k
        if (rv != SECSuccess) {
11732
            /* Alert sent and code set (if not SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE).
11733
             * In either case, we're done here. */
11734
317
            errCode = PORT_GetError();
11735
317
            goto loser;
11736
317
        }
11737
11738
7.96k
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11739
7.96k
            ss->sec.authType = ss->ssl3.hs.kea_def->authKeyType;
11740
7.96k
            ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
11741
7.96k
        }
11742
7.96k
    }
11743
11744
    /*
11745
     * Ask caller-supplied callback function to validate cert chain.
11746
     */
11747
7.96k
    rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
11748
7.96k
                                           PR_TRUE, isServer);
11749
7.96k
    if (rv != SECSuccess) {
11750
41
        errCode = PORT_GetError();
11751
41
        if (errCode == 0) {
11752
0
            errCode = SSL_ERROR_BAD_CERTIFICATE;
11753
0
        }
11754
41
        if (rv != SECWouldBlock) {
11755
41
            if (ss->handleBadCert) {
11756
0
                rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
11757
0
            }
11758
41
        }
11759
11760
41
        if (rv == SECWouldBlock) {
11761
0
            if (ss->sec.isServer) {
11762
0
                errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
11763
0
                goto loser;
11764
0
            }
11765
11766
0
            ss->ssl3.hs.authCertificatePending = PR_TRUE;
11767
0
            rv = SECSuccess;
11768
0
        }
11769
11770
41
        if (rv != SECSuccess) {
11771
41
            ssl3_SendAlertForCertError(ss, errCode);
11772
41
            goto loser;
11773
41
        }
11774
41
    }
11775
11776
7.92k
    if (ss->sec.ci.sid->peerCert) {
11777
0
        CERT_DestroyCertificate(ss->sec.ci.sid->peerCert);
11778
0
    }
11779
7.92k
    ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
11780
11781
7.92k
    if (!ss->sec.isServer) {
11782
7.92k
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
11783
0
            TLS13_SET_HS_STATE(ss, wait_cert_verify);
11784
7.92k
        } else {
11785
            /* Ephemeral suites require ServerKeyExchange. */
11786
7.92k
            if (ss->ssl3.hs.kea_def->ephemeral) {
11787
                /* require server_key_exchange */
11788
3.04k
                ss->ssl3.hs.ws = wait_server_key;
11789
4.88k
            } else {
11790
                /* disallow server_key_exchange */
11791
4.88k
                ss->ssl3.hs.ws = wait_cert_request;
11792
                /* This is static RSA key exchange so set the key exchange
11793
                 * details to compensate for that. */
11794
4.88k
                ss->sec.keaKeyBits = ss->sec.authKeyBits;
11795
4.88k
                ss->sec.signatureScheme = ssl_sig_none;
11796
4.88k
                ss->sec.keaGroup = NULL;
11797
4.88k
            }
11798
7.92k
        }
11799
7.92k
    } else {
11800
        /* Server */
11801
0
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11802
0
            ss->ssl3.hs.ws = wait_client_key;
11803
0
        } else {
11804
0
            TLS13_SET_HS_STATE(ss, wait_cert_verify);
11805
0
        }
11806
0
    }
11807
11808
7.92k
    PORT_Assert(rv == SECSuccess);
11809
7.92k
    if (rv != SECSuccess) {
11810
0
        errCode = SEC_ERROR_LIBRARY_FAILURE;
11811
0
        goto loser;
11812
0
    }
11813
11814
7.92k
    return SECSuccess;
11815
11816
358
loser:
11817
358
    (void)ssl_MapLowLevelError(errCode);
11818
358
    return SECFailure;
11819
7.92k
}
11820
11821
static SECStatus ssl3_FinishHandshake(sslSocket *ss);
11822
11823
static SECStatus
11824
ssl3_AlwaysFail(sslSocket *ss)
11825
0
{
11826
    /* The caller should have cleared the callback. */
11827
0
    ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
11828
0
    PORT_SetError(PR_INVALID_STATE_ERROR);
11829
0
    return SECFailure;
11830
0
}
11831
11832
/* Caller must hold 1stHandshakeLock.
11833
 */
11834
SECStatus
11835
ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
11836
0
{
11837
0
    SECStatus rv;
11838
11839
0
    PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
11840
11841
0
    if (ss->sec.isServer) {
11842
0
        PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
11843
0
        return SECFailure;
11844
0
    }
11845
11846
0
    ssl_GetRecvBufLock(ss);
11847
0
    ssl_GetSSL3HandshakeLock(ss);
11848
11849
0
    if (!ss->ssl3.hs.authCertificatePending) {
11850
0
        PORT_SetError(PR_INVALID_STATE_ERROR);
11851
0
        rv = SECFailure;
11852
0
        goto done;
11853
0
    }
11854
11855
0
    ss->ssl3.hs.authCertificatePending = PR_FALSE;
11856
11857
0
    if (error != 0) {
11858
0
        ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
11859
0
        ssl3_SendAlertForCertError(ss, error);
11860
0
        rv = SECSuccess;
11861
0
    } else if (ss->ssl3.hs.restartTarget != NULL) {
11862
0
        sslRestartTarget target = ss->ssl3.hs.restartTarget;
11863
0
        ss->ssl3.hs.restartTarget = NULL;
11864
11865
0
        if (target == ssl3_FinishHandshake) {
11866
0
            SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication lost the race"
11867
0
                        " with peer's finished message",
11868
0
                        SSL_GETPID(), ss->fd));
11869
0
        }
11870
11871
0
        rv = target(ss);
11872
0
    } else {
11873
0
        SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with"
11874
0
                    " peer's finished message",
11875
0
                    SSL_GETPID(), ss->fd));
11876
11877
0
        PORT_Assert(!ss->ssl3.hs.isResuming);
11878
0
        PORT_Assert(ss->ssl3.hs.ws != idle_handshake);
11879
11880
0
        if (ss->opt.enableFalseStart &&
11881
0
            !ss->firstHsDone &&
11882
0
            !ss->ssl3.hs.isResuming &&
11883
0
            ssl3_WaitingForServerSecondRound(ss)) {
11884
            /* ssl3_SendClientSecondRound deferred the false start check because
11885
             * certificate authentication was pending, so we do it now if we still
11886
             * haven't received all of the server's second round yet.
11887
             */
11888
0
            rv = ssl3_CheckFalseStart(ss);
11889
0
        } else {
11890
0
            rv = SECSuccess;
11891
0
        }
11892
0
    }
11893
11894
0
done:
11895
0
    ssl_ReleaseSSL3HandshakeLock(ss);
11896
0
    ssl_ReleaseRecvBufLock(ss);
11897
11898
0
    return rv;
11899
0
}
11900
11901
static SECStatus
11902
ssl3_ComputeTLSFinished(sslSocket *ss, ssl3CipherSpec *spec,
11903
                        PRBool isServer,
11904
                        const SSL3Hashes *hashes,
11905
                        TLSFinished *tlsFinished)
11906
8.92k
{
11907
8.92k
    SECStatus rv;
11908
8.92k
    CK_TLS_MAC_PARAMS tls_mac_params;
11909
8.92k
    SECItem param = { siBuffer, NULL, 0 };
11910
8.92k
    PK11Context *prf_context;
11911
8.92k
    unsigned int retLen;
11912
11913
8.92k
    PORT_Assert(spec->masterSecret);
11914
8.92k
    if (!spec->masterSecret) {
11915
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11916
0
        return SECFailure;
11917
0
    }
11918
11919
8.92k
    if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) {
11920
5.98k
        tls_mac_params.prfHashMechanism = CKM_TLS_PRF;
11921
5.98k
    } else {
11922
2.94k
        tls_mac_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
11923
2.94k
    }
11924
8.92k
    tls_mac_params.ulMacLength = 12;
11925
8.92k
    tls_mac_params.ulServerOrClient = isServer ? 1 : 2;
11926
8.92k
    param.data = (unsigned char *)&tls_mac_params;
11927
8.92k
    param.len = sizeof(tls_mac_params);
11928
8.92k
    prf_context = PK11_CreateContextBySymKey(CKM_TLS_MAC, CKA_SIGN,
11929
8.92k
                                             spec->masterSecret, &param);
11930
8.92k
    if (!prf_context)
11931
0
        return SECFailure;
11932
11933
8.92k
    rv = PK11_DigestBegin(prf_context);
11934
8.92k
    rv |= PK11_DigestOp(prf_context, hashes->u.raw, hashes->len);
11935
8.92k
    rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data, &retLen,
11936
8.92k
                           sizeof tlsFinished->verify_data);
11937
8.92k
    PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data);
11938
11939
8.92k
    PK11_DestroyContext(prf_context, PR_TRUE);
11940
11941
8.92k
    return rv;
11942
8.92k
}
11943
11944
/* The calling function must acquire and release the appropriate
11945
 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
11946
 * ss->ssl3.crSpec).
11947
 */
11948
SECStatus
11949
ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec,
11950
                            const char *label, unsigned int labelLen,
11951
                            const unsigned char *val, unsigned int valLen,
11952
                            unsigned char *out, unsigned int outLen)
11953
0
{
11954
0
    SECItem param = { siBuffer, NULL, 0 };
11955
0
    CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
11956
0
    PK11Context *prf_context;
11957
0
    unsigned int retLen;
11958
0
    SECStatus rv;
11959
11960
0
    if (!spec->masterSecret) {
11961
0
        PORT_Assert(spec->masterSecret);
11962
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11963
0
        return SECFailure;
11964
0
    }
11965
11966
0
    if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
11967
        /* Bug 1312976 non-SHA256 exporters are broken. */
11968
0
        if (ssl3_GetPrfHashMechanism(ss) != CKM_SHA256) {
11969
0
            PORT_Assert(0);
11970
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11971
0
            return SECFailure;
11972
0
        }
11973
0
        mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
11974
0
    }
11975
0
    prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
11976
0
                                             spec->masterSecret, &param);
11977
0
    if (!prf_context)
11978
0
        return SECFailure;
11979
11980
0
    rv = PK11_DigestBegin(prf_context);
11981
0
    rv |= PK11_DigestOp(prf_context, (unsigned char *)label, labelLen);
11982
0
    rv |= PK11_DigestOp(prf_context, val, valLen);
11983
0
    rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
11984
0
    PORT_Assert(rv != SECSuccess || retLen == outLen);
11985
11986
0
    PK11_DestroyContext(prf_context, PR_TRUE);
11987
0
    return rv;
11988
0
}
11989
11990
/* called from ssl3_SendClientSecondRound
11991
 *             ssl3_HandleFinished
11992
 */
11993
static SECStatus
11994
ssl3_SendNextProto(sslSocket *ss)
11995
0
{
11996
0
    SECStatus rv;
11997
0
    int padding_len;
11998
0
    static const unsigned char padding[32] = { 0 };
11999
12000
0
    if (ss->xtnData.nextProto.len == 0 ||
12001
0
        ss->xtnData.nextProtoState == SSL_NEXT_PROTO_SELECTED) {
12002
0
        return SECSuccess;
12003
0
    }
12004
12005
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
12006
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12007
12008
0
    padding_len = 32 - ((ss->xtnData.nextProto.len + 2) % 32);
12009
12010
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_next_proto, ss->xtnData.nextProto.len + 2 + padding_len);
12011
0
    if (rv != SECSuccess) {
12012
0
        return rv; /* error code set by AppendHandshakeHeader */
12013
0
    }
12014
0
    rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.nextProto.data,
12015
0
                                      ss->xtnData.nextProto.len, 1);
12016
0
    if (rv != SECSuccess) {
12017
0
        return rv; /* error code set by AppendHandshake */
12018
0
    }
12019
0
    rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
12020
0
    if (rv != SECSuccess) {
12021
0
        return rv; /* error code set by AppendHandshake */
12022
0
    }
12023
0
    return rv;
12024
0
}
12025
12026
/* called from ssl3_SendFinished and tls13_DeriveSecret.
12027
 *
12028
 * This function is simply a debugging aid and therefore does not return a
12029
 * SECStatus. */
12030
void
12031
ssl3_RecordKeyLog(sslSocket *ss, const char *label, PK11SymKey *secret)
12032
4.66k
{
12033
4.66k
#ifdef NSS_ALLOW_SSLKEYLOGFILE
12034
4.66k
    SECStatus rv;
12035
4.66k
    SECItem *keyData;
12036
    /* Longest label is "CLIENT_HANDSHAKE_TRAFFIC_SECRET", master secret is 48
12037
     * bytes which happens to be the largest in TLS 1.3 as well (SHA384).
12038
     * Maximum line length: "CLIENT_HANDSHAKE_TRAFFIC_SECRET" (31) + " " (1) +
12039
     * client_random (32*2) + " " (1) +
12040
     * traffic_secret (48*2) + "\n" (1) = 194. */
12041
4.66k
    char buf[200];
12042
4.66k
    unsigned int offset, len;
12043
12044
4.66k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12045
12046
4.66k
    if (!ssl_keylog_iob)
12047
4.66k
        return;
12048
12049
0
    rv = PK11_ExtractKeyValue(secret);
12050
0
    if (rv != SECSuccess)
12051
0
        return;
12052
12053
    /* keyData does not need to be freed. */
12054
0
    keyData = PK11_GetKeyData(secret);
12055
0
    if (!keyData || !keyData->data)
12056
0
        return;
12057
12058
0
    len = strlen(label) + 1 +          /* label + space */
12059
0
          SSL3_RANDOM_LENGTH * 2 + 1 + /* client random (hex) + space */
12060
0
          keyData->len * 2 + 1;        /* secret (hex) + newline */
12061
0
    PORT_Assert(len <= sizeof(buf));
12062
0
    if (len > sizeof(buf))
12063
0
        return;
12064
12065
    /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
12066
12067
    /* There could be multiple, concurrent writers to the
12068
     * keylog, so we have to do everything in a single call to
12069
     * fwrite. */
12070
12071
0
    strcpy(buf, label);
12072
0
    offset = strlen(label);
12073
0
    buf[offset++] += ' ';
12074
0
    hexEncode(buf + offset, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
12075
0
    offset += SSL3_RANDOM_LENGTH * 2;
12076
0
    buf[offset++] = ' ';
12077
0
    hexEncode(buf + offset, keyData->data, keyData->len);
12078
0
    offset += keyData->len * 2;
12079
0
    buf[offset++] = '\n';
12080
12081
0
    PORT_Assert(offset == len);
12082
12083
0
    PZ_Lock(ssl_keylog_lock);
12084
0
    if (fwrite(buf, len, 1, ssl_keylog_iob) == 1)
12085
0
        fflush(ssl_keylog_iob);
12086
0
    PZ_Unlock(ssl_keylog_lock);
12087
0
#endif
12088
0
}
12089
12090
/* called from ssl3_SendClientSecondRound
12091
 *             ssl3_HandleClientHello
12092
 *             ssl3_HandleFinished
12093
 */
12094
static SECStatus
12095
ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
12096
4.66k
{
12097
4.66k
    ssl3CipherSpec *cwSpec;
12098
4.66k
    PRBool isTLS;
12099
4.66k
    PRBool isServer = ss->sec.isServer;
12100
4.66k
    SECStatus rv;
12101
4.66k
    SSL3Sender sender = isServer ? sender_server : sender_client;
12102
4.66k
    SSL3Hashes hashes;
12103
4.66k
    TLSFinished tlsFinished;
12104
12105
4.66k
    SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
12106
12107
4.66k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
12108
4.66k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12109
4.66k
    PR_ASSERT(!ss->ssl3.hs.clientCertificatePending);
12110
12111
4.66k
    ssl_GetSpecReadLock(ss);
12112
4.66k
    cwSpec = ss->ssl3.cwSpec;
12113
4.66k
    isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
12114
4.66k
    rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
12115
4.66k
    if (isTLS && rv == SECSuccess) {
12116
4.66k
        rv = ssl3_ComputeTLSFinished(ss, cwSpec, isServer, &hashes, &tlsFinished);
12117
4.66k
    }
12118
4.66k
    ssl_ReleaseSpecReadLock(ss);
12119
4.66k
    if (rv != SECSuccess) {
12120
0
        goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */
12121
0
    }
12122
12123
4.66k
    if (isTLS) {
12124
4.66k
        if (isServer)
12125
0
            ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
12126
4.66k
        else
12127
4.66k
            ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
12128
4.66k
        ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
12129
4.66k
        rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof tlsFinished);
12130
4.66k
        if (rv != SECSuccess)
12131
0
            goto fail; /* err set by AppendHandshake. */
12132
4.66k
        rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
12133
4.66k
        if (rv != SECSuccess)
12134
0
            goto fail; /* err set by AppendHandshake. */
12135
4.66k
    } else {
12136
0
        if (isServer)
12137
0
            ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
12138
0
        else
12139
0
            ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
12140
0
        PORT_Assert(hashes.len == sizeof hashes.u.s);
12141
0
        ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
12142
0
        rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof hashes.u.s);
12143
0
        if (rv != SECSuccess)
12144
0
            goto fail; /* err set by AppendHandshake. */
12145
0
        rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
12146
0
        if (rv != SECSuccess)
12147
0
            goto fail; /* err set by AppendHandshake. */
12148
0
    }
12149
4.66k
    rv = ssl3_FlushHandshake(ss, flags);
12150
4.66k
    if (rv != SECSuccess) {
12151
0
        goto fail; /* error code set by ssl3_FlushHandshake */
12152
0
    }
12153
12154
4.66k
    ssl3_RecordKeyLog(ss, "CLIENT_RANDOM", ss->ssl3.cwSpec->masterSecret);
12155
12156
4.66k
    return SECSuccess;
12157
12158
0
fail:
12159
0
    return rv;
12160
4.66k
}
12161
12162
/* wrap the master secret, and put it into the SID.
12163
 * Caller holds the Spec read lock.
12164
 */
12165
SECStatus
12166
ssl3_CacheWrappedSecret(sslSocket *ss, sslSessionID *sid,
12167
                        PK11SymKey *secret)
12168
1.65k
{
12169
1.65k
    PK11SymKey *wrappingKey = NULL;
12170
1.65k
    PK11SlotInfo *symKeySlot;
12171
1.65k
    void *pwArg = ss->pkcs11PinArg;
12172
1.65k
    SECStatus rv = SECFailure;
12173
1.65k
    PRBool isServer = ss->sec.isServer;
12174
1.65k
    CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
12175
12176
1.65k
    symKeySlot = PK11_GetSlotFromKey(secret);
12177
1.65k
    if (!isServer) {
12178
1.65k
        int wrapKeyIndex;
12179
1.65k
        int incarnation;
12180
12181
        /* these next few functions are mere accessors and don't fail. */
12182
1.65k
        sid->u.ssl3.masterWrapIndex = wrapKeyIndex =
12183
1.65k
            PK11_GetCurrentWrapIndex(symKeySlot);
12184
1.65k
        PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
12185
12186
1.65k
        sid->u.ssl3.masterWrapSeries = incarnation =
12187
1.65k
            PK11_GetSlotSeries(symKeySlot);
12188
1.65k
        sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot);
12189
1.65k
        sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
12190
1.65k
        sid->u.ssl3.masterValid = PR_TRUE;
12191
        /* Get the default wrapping key, for wrapping the master secret before
12192
         * placing it in the SID cache entry. */
12193
1.65k
        wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
12194
1.65k
                                      CKM_INVALID_MECHANISM, incarnation,
12195
1.65k
                                      pwArg);
12196
1.65k
        if (wrappingKey) {
12197
1.43k
            mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
12198
1.43k
        } else {
12199
216
            int keyLength;
12200
            /* if the wrappingKey doesn't exist, attempt to create it.
12201
             * Note: we intentionally ignore errors here.  If we cannot
12202
             * generate a wrapping key, it is not fatal to this SSL connection,
12203
             * but we will not be able to restart this session.
12204
             */
12205
216
            mechanism = PK11_GetBestWrapMechanism(symKeySlot);
12206
216
            keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
12207
            /* Zero length means fixed key length algorithm, or error.
12208
             * It's ambiguous.
12209
             */
12210
216
            wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
12211
216
                                      keyLength, pwArg);
12212
216
            if (wrappingKey) {
12213
                /* The thread safety characteristics of PK11_[SG]etWrapKey is
12214
                 * abominable.  This protects against races in calling
12215
                 * PK11_SetWrapKey by dropping and re-acquiring the canonical
12216
                 * value once it is set.  The mutex in PK11_[SG]etWrapKey will
12217
                 * ensure that races produce the same value in the end. */
12218
216
                PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
12219
216
                PK11_FreeSymKey(wrappingKey);
12220
216
                wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
12221
216
                                              CKM_INVALID_MECHANISM, incarnation, pwArg);
12222
216
                if (!wrappingKey) {
12223
0
                    PK11_FreeSlot(symKeySlot);
12224
0
                    return SECFailure;
12225
0
                }
12226
216
            }
12227
216
        }
12228
1.65k
    } else {
12229
        /* server socket using session cache. */
12230
0
        mechanism = PK11_GetBestWrapMechanism(symKeySlot);
12231
0
        if (mechanism != CKM_INVALID_MECHANISM) {
12232
0
            wrappingKey =
12233
0
                ssl3_GetWrappingKey(ss, symKeySlot, mechanism, pwArg);
12234
0
            if (wrappingKey) {
12235
0
                mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
12236
0
            }
12237
0
        }
12238
0
    }
12239
12240
1.65k
    sid->u.ssl3.masterWrapMech = mechanism;
12241
1.65k
    PK11_FreeSlot(symKeySlot);
12242
12243
1.65k
    if (wrappingKey) {
12244
1.65k
        SECItem wmsItem;
12245
12246
1.65k
        wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
12247
1.65k
        wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret;
12248
1.65k
        rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
12249
1.65k
                             secret, &wmsItem);
12250
        /* rv is examined below. */
12251
1.65k
        sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
12252
1.65k
        PK11_FreeSymKey(wrappingKey);
12253
1.65k
    }
12254
1.65k
    return rv;
12255
1.65k
}
12256
12257
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
12258
 * a complete ssl3 Finished message from the peer.
12259
 * Caller must hold Handshake and RecvBuf locks.
12260
 */
12261
static SECStatus
12262
ssl3_HandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
12263
4.26k
{
12264
4.26k
    SECStatus rv = SECSuccess;
12265
4.26k
    PRBool isServer = ss->sec.isServer;
12266
4.26k
    PRBool isTLS;
12267
4.26k
    SSL3Hashes hashes;
12268
12269
4.26k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12270
4.26k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12271
12272
4.26k
    SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
12273
4.26k
                SSL_GETPID(), ss->fd));
12274
12275
4.26k
    if (ss->ssl3.hs.ws != wait_finished) {
12276
6
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12277
6
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
12278
6
        return SECFailure;
12279
6
    }
12280
12281
4.26k
    if (!ss->sec.isServer || !ss->opt.requestCertificate) {
12282
4.26k
        dtls_ReceivedFirstMessageInFlight(ss);
12283
4.26k
    }
12284
12285
4.26k
    rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.crSpec, &hashes,
12286
4.26k
                                     isServer ? sender_client : sender_server);
12287
4.26k
    if (rv != SECSuccess) {
12288
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12289
0
        return SECFailure;
12290
0
    }
12291
12292
4.26k
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
12293
4.26k
    if (rv != SECSuccess) {
12294
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12295
0
        return rv;
12296
0
    }
12297
12298
4.26k
    isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
12299
4.26k
    if (isTLS) {
12300
4.26k
        TLSFinished tlsFinished;
12301
12302
4.26k
        if (length != sizeof(tlsFinished)) {
12303
#ifndef UNSAFE_FUZZER_MODE
12304
            (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
12305
            PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12306
            return SECFailure;
12307
#endif
12308
4.23k
        }
12309
4.26k
        rv = ssl3_ComputeTLSFinished(ss, ss->ssl3.crSpec, !isServer,
12310
4.26k
                                     &hashes, &tlsFinished);
12311
4.26k
        if (!isServer)
12312
4.26k
            ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
12313
0
        else
12314
0
            ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
12315
4.26k
        ss->ssl3.hs.finishedBytes = sizeof(tlsFinished);
12316
4.26k
        if (rv != SECSuccess ||
12317
4.26k
            0 != NSS_SecureMemcmp(&tlsFinished, b,
12318
4.26k
                                  PR_MIN(length, ss->ssl3.hs.finishedBytes))) {
12319
#ifndef UNSAFE_FUZZER_MODE
12320
            (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
12321
            PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12322
            return SECFailure;
12323
#endif
12324
34
        }
12325
4.26k
    } else {
12326
0
        if (length != sizeof(SSL3Finished)) {
12327
0
            (void)ssl3_IllegalParameter(ss);
12328
0
            PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12329
0
            return SECFailure;
12330
0
        }
12331
12332
0
        if (!isServer)
12333
0
            ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
12334
0
        else
12335
0
            ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
12336
0
        PORT_Assert(hashes.len == sizeof hashes.u.s);
12337
0
        ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
12338
0
        if (0 != NSS_SecureMemcmp(&hashes.u.s, b, length)) {
12339
0
            (void)ssl3_HandshakeFailure(ss);
12340
0
            PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12341
0
            return SECFailure;
12342
0
        }
12343
0
    }
12344
12345
4.26k
    ssl_GetXmitBufLock(ss); /*************************************/
12346
12347
4.26k
    if ((isServer && !ss->ssl3.hs.isResuming) ||
12348
4.26k
        (!isServer && ss->ssl3.hs.isResuming)) {
12349
0
        PRInt32 flags = 0;
12350
12351
        /* Send a NewSessionTicket message if the client sent us
12352
         * either an empty session ticket, or one that did not verify.
12353
         * (Note that if either of these conditions was met, then the
12354
         * server has sent a SessionTicket extension in the
12355
         * ServerHello message.)
12356
         */
12357
0
        if (isServer && !ss->ssl3.hs.isResuming &&
12358
0
            ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
12359
0
            ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
12360
            /* RFC 5077 Section 3.3: "In the case of a full handshake, the
12361
             * server MUST verify the client's Finished message before sending
12362
             * the ticket." Presumably, this also means that the client's
12363
             * certificate, if any, must be verified beforehand too.
12364
             */
12365
0
            rv = ssl3_SendNewSessionTicket(ss);
12366
0
            if (rv != SECSuccess) {
12367
0
                goto xmit_loser;
12368
0
            }
12369
0
        }
12370
12371
0
        rv = ssl3_SendChangeCipherSpecs(ss);
12372
0
        if (rv != SECSuccess) {
12373
0
            goto xmit_loser; /* err is set. */
12374
0
        }
12375
        /* If this thread is in SSL_SecureSend (trying to write some data)
12376
        ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
12377
        ** last two handshake messages (change cipher spec and finished)
12378
        ** will be sent in the same send/write call as the application data.
12379
        */
12380
0
        if (ss->writerThread == PR_GetCurrentThread()) {
12381
0
            flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
12382
0
        }
12383
12384
0
        if (!isServer && !ss->firstHsDone) {
12385
0
            rv = ssl3_SendNextProto(ss);
12386
0
            if (rv != SECSuccess) {
12387
0
                goto xmit_loser; /* err code was set. */
12388
0
            }
12389
0
        }
12390
12391
0
        if (IS_DTLS(ss)) {
12392
0
            flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
12393
0
        }
12394
12395
0
        rv = ssl3_SendFinished(ss, flags);
12396
0
        if (rv != SECSuccess) {
12397
0
            goto xmit_loser; /* err is set. */
12398
0
        }
12399
0
    }
12400
12401
4.26k
xmit_loser:
12402
4.26k
    ssl_ReleaseXmitBufLock(ss); /*************************************/
12403
4.26k
    if (rv != SECSuccess) {
12404
0
        return rv;
12405
0
    }
12406
12407
4.26k
    if (ss->ssl3.hs.authCertificatePending) {
12408
0
        if (ss->ssl3.hs.restartTarget) {
12409
0
            PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
12410
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12411
0
            return SECFailure;
12412
0
        }
12413
12414
0
        ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
12415
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
12416
0
        return SECFailure;
12417
0
    }
12418
12419
4.26k
    rv = ssl3_FinishHandshake(ss);
12420
4.26k
    return rv;
12421
4.26k
}
12422
12423
SECStatus
12424
ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid, PK11SymKey *secret)
12425
1.65k
{
12426
1.65k
    PORT_Assert(secret);
12427
12428
    /* fill in the sid */
12429
1.65k
    sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
12430
1.65k
    sid->u.ssl3.policy = ss->ssl3.policy;
12431
1.65k
    sid->version = ss->version;
12432
1.65k
    sid->authType = ss->sec.authType;
12433
1.65k
    sid->authKeyBits = ss->sec.authKeyBits;
12434
1.65k
    sid->keaType = ss->sec.keaType;
12435
1.65k
    sid->keaKeyBits = ss->sec.keaKeyBits;
12436
1.65k
    if (ss->sec.keaGroup) {
12437
1.23k
        sid->keaGroup = ss->sec.keaGroup->name;
12438
1.23k
    } else {
12439
418
        sid->keaGroup = ssl_grp_none;
12440
418
    }
12441
1.65k
    sid->sigScheme = ss->sec.signatureScheme;
12442
1.65k
    sid->lastAccessTime = sid->creationTime = ssl_Time(ss);
12443
1.65k
    sid->expirationTime = sid->creationTime + (ssl_ticket_lifetime * PR_USEC_PER_SEC);
12444
1.65k
    sid->localCert = CERT_DupCertificate(ss->sec.localCert);
12445
1.65k
    if (ss->sec.isServer) {
12446
0
        sid->namedCurve = ss->sec.serverCert->namedCurve;
12447
0
    }
12448
12449
1.65k
    if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
12450
1.65k
        ss->xtnData.nextProto.data) {
12451
0
        SECITEM_FreeItem(&sid->u.ssl3.alpnSelection, PR_FALSE);
12452
0
        if (SECITEM_CopyItem(
12453
0
                NULL, &sid->u.ssl3.alpnSelection, &ss->xtnData.nextProto) != SECSuccess) {
12454
0
            return SECFailure; /* error already set. */
12455
0
        }
12456
0
    }
12457
12458
    /* Copy the master secret (wrapped or unwrapped) into the sid */
12459
1.65k
    return ssl3_CacheWrappedSecret(ss, ss->sec.ci.sid, secret);
12460
1.65k
}
12461
12462
/* The return type is SECStatus instead of void because this function needs
12463
 * to have type sslRestartTarget.
12464
 */
12465
SECStatus
12466
ssl3_FinishHandshake(sslSocket *ss)
12467
4.26k
{
12468
4.26k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12469
4.26k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12470
4.26k
    PORT_Assert(ss->ssl3.hs.restartTarget == NULL);
12471
4.26k
    sslSessionID *sid = ss->sec.ci.sid;
12472
4.26k
    SECStatus sidRv = SECFailure;
12473
12474
    /* The first handshake is now completed. */
12475
4.26k
    ss->handshake = NULL;
12476
12477
4.26k
    if (sid->cached == never_cached && !ss->opt.noCache) {
12478
        /* If the wrap fails, don't cache the sid. The connection proceeds
12479
         * normally, so the rv is only used to determine whether we cache. */
12480
1.65k
        sidRv = ssl3_FillInCachedSID(ss, sid, ss->ssl3.crSpec->masterSecret);
12481
1.65k
    }
12482
12483
    /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid
12484
     * until it has verified the server's Finished message." When the server
12485
     * sends a NewSessionTicket in a resumption handshake, we must wait until
12486
     * the handshake is finished (we have verified the server's Finished
12487
     * AND the server's certificate) before we update the ticket in the sid.
12488
     *
12489
     * This must be done before we call ssl_CacheSessionID(ss)
12490
     * because CacheSID requires the session ticket to already be set, and also
12491
     * because of the lazy lock creation scheme used by CacheSID and
12492
     * ssl3_SetSIDSessionTicket. */
12493
4.26k
    if (ss->ssl3.hs.receivedNewSessionTicket) {
12494
0
        PORT_Assert(!ss->sec.isServer);
12495
0
        if (sidRv == SECSuccess) {
12496
            /* The sid takes over the ticket data */
12497
0
            ssl3_SetSIDSessionTicket(ss->sec.ci.sid,
12498
0
                                     &ss->ssl3.hs.newSessionTicket);
12499
0
        } else {
12500
0
            PORT_Assert(ss->ssl3.hs.newSessionTicket.ticket.data);
12501
0
            SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket,
12502
0
                             PR_FALSE);
12503
0
        }
12504
0
        PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
12505
0
        ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
12506
0
    }
12507
4.26k
    if (sidRv == SECSuccess) {
12508
1.65k
        PORT_Assert(ss->sec.ci.sid->cached == never_cached);
12509
1.65k
        ssl_CacheSessionID(ss);
12510
1.65k
    }
12511
12512
4.26k
    ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */
12513
4.26k
    ss->ssl3.hs.ws = idle_handshake;
12514
12515
4.26k
    return ssl_FinishHandshake(ss);
12516
4.26k
}
12517
12518
SECStatus
12519
ssl_HashHandshakeMessageInt(sslSocket *ss, SSLHandshakeType ct,
12520
                            PRUint32 dtlsSeq,
12521
                            const PRUint8 *b, PRUint32 length,
12522
                            sslUpdateHandshakeHashes updateHashes)
12523
34.2k
{
12524
34.2k
    PRUint8 hdr[4];
12525
34.2k
    PRUint8 dtlsData[8];
12526
34.2k
    SECStatus rv;
12527
12528
34.2k
    PRINT_BUF(50, (ss, "Hash handshake message:", b, length));
12529
12530
34.2k
    hdr[0] = (PRUint8)ct;
12531
34.2k
    hdr[1] = (PRUint8)(length >> 16);
12532
34.2k
    hdr[2] = (PRUint8)(length >> 8);
12533
34.2k
    hdr[3] = (PRUint8)(length);
12534
12535
34.2k
    rv = updateHashes(ss, (unsigned char *)hdr, 4);
12536
34.2k
    if (rv != SECSuccess)
12537
0
        return rv; /* err code already set. */
12538
12539
    /* Extra data to simulate a complete DTLS handshake fragment */
12540
34.2k
    if (IS_DTLS_1_OR_12(ss)) {
12541
        /* Sequence number */
12542
0
        dtlsData[0] = MSB(dtlsSeq);
12543
0
        dtlsData[1] = LSB(dtlsSeq);
12544
12545
        /* Fragment offset */
12546
0
        dtlsData[2] = 0;
12547
0
        dtlsData[3] = 0;
12548
0
        dtlsData[4] = 0;
12549
12550
        /* Fragment length */
12551
0
        dtlsData[5] = (PRUint8)(length >> 16);
12552
0
        dtlsData[6] = (PRUint8)(length >> 8);
12553
0
        dtlsData[7] = (PRUint8)(length);
12554
12555
0
        rv = updateHashes(ss, (unsigned char *)dtlsData, sizeof(dtlsData));
12556
0
        if (rv != SECSuccess)
12557
0
            return rv; /* err code already set. */
12558
0
    }
12559
12560
    /* The message body */
12561
34.2k
    rv = updateHashes(ss, b, length);
12562
34.2k
    if (rv != SECSuccess)
12563
0
        return rv; /* err code already set. */
12564
12565
34.2k
    return SECSuccess;
12566
34.2k
}
12567
12568
SECStatus
12569
ssl_HashHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
12570
                         const PRUint8 *b, PRUint32 length)
12571
34.2k
{
12572
34.2k
    return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12573
34.2k
                                       b, length, ssl3_UpdateHandshakeHashes);
12574
34.2k
}
12575
12576
SECStatus
12577
ssl_HashHandshakeMessageDefault(sslSocket *ss, SSLHandshakeType ct,
12578
                                const PRUint8 *b, PRUint32 length)
12579
56
{
12580
56
    return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12581
56
                                       b, length, ssl3_UpdateDefaultHandshakeHashes);
12582
56
}
12583
SECStatus
12584
ssl_HashHandshakeMessageEchInner(sslSocket *ss, SSLHandshakeType ct,
12585
                                 const PRUint8 *b, PRUint32 length)
12586
0
{
12587
0
    return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12588
0
                                       b, length, ssl3_UpdateInnerHandshakeHashes);
12589
0
}
12590
12591
SECStatus
12592
ssl_HashPostHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
12593
                             const PRUint8 *b, PRUint32 length)
12594
0
{
12595
0
    return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12596
0
                                       b, length, ssl3_UpdatePostHandshakeHashes);
12597
0
}
12598
12599
/* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
12600
 * handshake message.
12601
 * Caller must hold Handshake and RecvBuf locks.
12602
 */
12603
SECStatus
12604
ssl3_HandleHandshakeMessage(sslSocket *ss, PRUint8 *b, PRUint32 length,
12605
                            PRBool endOfRecord)
12606
41.8k
{
12607
41.8k
    SECStatus rv = SECSuccess;
12608
41.8k
    PRUint16 epoch;
12609
12610
41.8k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12611
41.8k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12612
12613
41.8k
    SSL_TRC(30, ("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
12614
41.8k
                 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
12615
12616
    /* Start new handshake hashes when we start a new handshake. */
12617
41.8k
    if (ss->ssl3.hs.msg_type == ssl_hs_client_hello) {
12618
7
        ssl3_RestartHandshakeHashes(ss);
12619
7
    }
12620
41.8k
    switch (ss->ssl3.hs.msg_type) {
12621
6.91k
        case ssl_hs_hello_request:
12622
6.91k
        case ssl_hs_hello_verify_request:
12623
            /* We don't include hello_request and hello_verify_request messages
12624
             * in the handshake hashes */
12625
6.91k
            break;
12626
12627
        /* Defer hashing of these messages until the message handlers. */
12628
7
        case ssl_hs_client_hello:
12629
12.9k
        case ssl_hs_server_hello:
12630
12.9k
        case ssl_hs_certificate_verify:
12631
17.2k
        case ssl_hs_finished:
12632
17.2k
            break;
12633
12634
17.6k
        default:
12635
17.6k
            if (!tls13_IsPostHandshake(ss)) {
12636
17.6k
                rv = ssl_HashHandshakeMessage(ss, ss->ssl3.hs.msg_type, b, length);
12637
17.6k
                if (rv != SECSuccess) {
12638
0
                    return SECFailure;
12639
0
                }
12640
17.6k
            }
12641
41.8k
    }
12642
12643
41.8k
    PORT_SetError(0); /* each message starts with no error. */
12644
12645
41.8k
    if (ss->ssl3.hs.ws == wait_certificate_status &&
12646
41.8k
        ss->ssl3.hs.msg_type != ssl_hs_certificate_status) {
12647
        /* If we negotiated the certificate_status extension then we deferred
12648
         * certificate validation until we get the CertificateStatus messsage.
12649
         * But the CertificateStatus message is optional. If the server did
12650
         * not send it then we need to validate the certificate now. If the
12651
         * server does send the CertificateStatus message then we will
12652
         * authenticate the certificate in ssl3_HandleCertificateStatus.
12653
         */
12654
0
        rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
12655
0
        if (rv != SECSuccess) {
12656
            /* This can't block. */
12657
0
            PORT_Assert(PORT_GetError() != PR_WOULD_BLOCK_ERROR);
12658
0
            return SECFailure;
12659
0
        }
12660
0
    }
12661
12662
41.8k
    epoch = ss->ssl3.crSpec->epoch;
12663
41.8k
    switch (ss->ssl3.hs.msg_type) {
12664
7
        case ssl_hs_client_hello:
12665
7
            if (!ss->sec.isServer) {
12666
7
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12667
7
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
12668
7
                return SECFailure;
12669
7
            }
12670
0
            rv = ssl3_HandleClientHello(ss, b, length);
12671
0
            break;
12672
12.9k
        case ssl_hs_server_hello:
12673
12.9k
            if (ss->sec.isServer) {
12674
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12675
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
12676
0
                return SECFailure;
12677
0
            }
12678
12.9k
            rv = ssl3_HandleServerHello(ss, b, length);
12679
12.9k
            break;
12680
28.8k
        default:
12681
28.8k
            if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
12682
28.8k
                rv = ssl3_HandlePostHelloHandshakeMessage(ss, b, length);
12683
28.8k
            } else {
12684
10
                rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length);
12685
10
            }
12686
28.8k
            break;
12687
41.8k
    }
12688
41.8k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
12689
41.8k
        (epoch != ss->ssl3.crSpec->epoch) && !endOfRecord) {
12690
        /* If we changed read cipher states, there must not be any
12691
         * data in the input queue. */
12692
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12693
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
12694
0
        return SECFailure;
12695
0
    }
12696
    /* We consider the record to have been handled if SECSuccess or else WOULD_BLOCK is set
12697
     * Whoever set WOULD_BLOCK must handle any remaining actions required to finsih processing the record.
12698
     * e.g. by setting restartTarget.
12699
     */
12700
41.8k
    if (IS_DTLS(ss) && (rv == SECSuccess || (rv == SECFailure && PR_GetError() == PR_WOULD_BLOCK_ERROR))) {
12701
        /* Increment the expected sequence number */
12702
0
        ss->ssl3.hs.recvMessageSeq++;
12703
0
    }
12704
12705
    /* Taint the message so that it's easier to detect UAFs. */
12706
41.8k
    PORT_Memset(b, 'N', length);
12707
12708
41.8k
    return rv;
12709
41.8k
}
12710
12711
static SECStatus
12712
ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b,
12713
                                     PRUint32 length)
12714
28.8k
{
12715
28.8k
    SECStatus rv;
12716
28.8k
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
12717
12718
28.8k
    switch (ss->ssl3.hs.msg_type) {
12719
6.91k
        case ssl_hs_hello_request:
12720
6.91k
            if (length != 0) {
12721
14
                (void)ssl3_DecodeError(ss);
12722
14
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
12723
14
                return SECFailure;
12724
14
            }
12725
6.90k
            if (ss->sec.isServer) {
12726
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12727
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
12728
0
                return SECFailure;
12729
0
            }
12730
6.90k
            rv = ssl3_HandleHelloRequest(ss);
12731
6.90k
            break;
12732
12733
1
        case ssl_hs_hello_verify_request:
12734
1
            if (!IS_DTLS(ss) || ss->sec.isServer) {
12735
1
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12736
1
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
12737
1
                return SECFailure;
12738
1
            }
12739
0
            rv = dtls_HandleHelloVerifyRequest(ss, b, length);
12740
0
            break;
12741
9.08k
        case ssl_hs_certificate:
12742
9.08k
            rv = ssl3_HandleCertificate(ss, b, length);
12743
9.08k
            break;
12744
2
        case ssl_hs_certificate_status:
12745
2
            rv = ssl3_HandleCertificateStatus(ss, b, length);
12746
2
            break;
12747
3.01k
        case ssl_hs_server_key_exchange:
12748
3.01k
            if (ss->sec.isServer) {
12749
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12750
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
12751
0
                return SECFailure;
12752
0
            }
12753
3.01k
            rv = ssl3_HandleServerKeyExchange(ss, b, length);
12754
3.01k
            break;
12755
173
        case ssl_hs_certificate_request:
12756
173
            if (ss->sec.isServer) {
12757
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12758
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
12759
0
                return SECFailure;
12760
0
            }
12761
173
            rv = ssl3_HandleCertificateRequest(ss, b, length);
12762
173
            break;
12763
5.36k
        case ssl_hs_server_hello_done:
12764
5.36k
            if (length != 0) {
12765
6
                (void)ssl3_DecodeError(ss);
12766
6
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
12767
6
                return SECFailure;
12768
6
            }
12769
5.35k
            if (ss->sec.isServer) {
12770
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12771
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
12772
0
                return SECFailure;
12773
0
            }
12774
5.35k
            rv = ssl3_HandleServerHelloDone(ss);
12775
5.35k
            break;
12776
1
        case ssl_hs_certificate_verify:
12777
1
            if (!ss->sec.isServer) {
12778
1
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12779
1
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
12780
1
                return SECFailure;
12781
1
            }
12782
0
            rv = ssl3_HandleCertificateVerify(ss, b, length);
12783
0
            break;
12784
4
        case ssl_hs_client_key_exchange:
12785
4
            if (!ss->sec.isServer) {
12786
4
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12787
4
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
12788
4
                return SECFailure;
12789
4
            }
12790
0
            rv = ssl3_HandleClientKeyExchange(ss, b, length);
12791
0
            break;
12792
6
        case ssl_hs_new_session_ticket:
12793
6
            if (ss->sec.isServer) {
12794
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12795
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
12796
0
                return SECFailure;
12797
0
            }
12798
6
            rv = ssl3_HandleNewSessionTicket(ss, b, length);
12799
6
            break;
12800
4.26k
        case ssl_hs_finished:
12801
4.26k
            rv = ssl3_HandleFinished(ss, b, length);
12802
4.26k
            break;
12803
15
        default:
12804
15
            (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12805
15
            PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
12806
15
            rv = SECFailure;
12807
28.8k
    }
12808
12809
28.8k
    return rv;
12810
28.8k
}
12811
12812
/* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
12813
 * origBuf is the decrypted ssl record content.
12814
 * Caller must hold the handshake and RecvBuf locks.
12815
 */
12816
static SECStatus
12817
ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
12818
44.9k
{
12819
44.9k
    sslBuffer buf = *origBuf; /* Work from a copy. */
12820
44.9k
    SECStatus rv;
12821
12822
44.9k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12823
44.9k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12824
12825
232k
    while (buf.len > 0) {
12826
211k
        if (ss->ssl3.hs.header_bytes < 4) {
12827
169k
            PRUint8 t;
12828
169k
            t = *(buf.buf++);
12829
169k
            buf.len--;
12830
169k
            if (ss->ssl3.hs.header_bytes++ == 0)
12831
42.5k
                ss->ssl3.hs.msg_type = (SSLHandshakeType)t;
12832
126k
            else
12833
126k
                ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
12834
169k
            if (ss->ssl3.hs.header_bytes < 4)
12835
127k
                continue;
12836
12837
42.2k
#define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
12838
42.2k
            if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
12839
244
                (void)ssl3_DecodeError(ss);
12840
244
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
12841
244
                goto loser;
12842
244
            }
12843
41.9k
#undef MAX_HANDSHAKE_MSG_LEN
12844
12845
            /* If msg_len is zero, be sure we fall through,
12846
            ** even if buf.len is zero.
12847
            */
12848
41.9k
            if (ss->ssl3.hs.msg_len > 0)
12849
25.4k
                continue;
12850
41.9k
        }
12851
12852
        /*
12853
         * Header has been gathered and there is at least one byte of new
12854
         * data available for this message. If it can be done right out
12855
         * of the original buffer, then use it from there.
12856
         */
12857
59.1k
        if (ss->ssl3.hs.msg_body.len == 0 && buf.len >= ss->ssl3.hs.msg_len) {
12858
            /* handle it from input buffer */
12859
37.1k
            rv = ssl3_HandleHandshakeMessage(ss, buf.buf, ss->ssl3.hs.msg_len,
12860
37.1k
                                             buf.len == ss->ssl3.hs.msg_len);
12861
37.1k
            buf.buf += ss->ssl3.hs.msg_len;
12862
37.1k
            buf.len -= ss->ssl3.hs.msg_len;
12863
37.1k
            ss->ssl3.hs.msg_len = 0;
12864
37.1k
            ss->ssl3.hs.header_bytes = 0;
12865
37.1k
            if (rv != SECSuccess) {
12866
5.22k
                goto loser;
12867
5.22k
            }
12868
37.1k
        } else {
12869
            /* must be copied to msg_body and dealt with from there */
12870
21.9k
            unsigned int bytes;
12871
12872
21.9k
            PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
12873
21.9k
            bytes = PR_MIN(buf.len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
12874
12875
            /* Grow the buffer if needed */
12876
21.9k
            rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
12877
21.9k
            if (rv != SECSuccess) {
12878
                /* sslBuffer_Grow has set a memory error code. */
12879
0
                goto loser;
12880
0
            }
12881
12882
21.9k
            PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
12883
21.9k
                        buf.buf, bytes);
12884
21.9k
            ss->ssl3.hs.msg_body.len += bytes;
12885
21.9k
            buf.buf += bytes;
12886
21.9k
            buf.len -= bytes;
12887
12888
21.9k
            PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
12889
12890
            /* if we have a whole message, do it */
12891
21.9k
            if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
12892
4.63k
                rv = ssl3_HandleHandshakeMessage(
12893
4.63k
                    ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len,
12894
4.63k
                    buf.len == 0);
12895
4.63k
                ss->ssl3.hs.msg_body.len = 0;
12896
4.63k
                ss->ssl3.hs.msg_len = 0;
12897
4.63k
                ss->ssl3.hs.header_bytes = 0;
12898
4.63k
                if (rv != SECSuccess) {
12899
1.49k
                    goto loser;
12900
1.49k
                }
12901
17.2k
            } else {
12902
17.2k
                PORT_Assert(buf.len == 0);
12903
17.2k
                break;
12904
17.2k
            }
12905
21.9k
        }
12906
59.1k
    } /* end loop */
12907
12908
37.9k
    origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
12909
37.9k
    return SECSuccess;
12910
12911
6.96k
loser : {
12912
    /* Make sure to remove any data that was consumed. */
12913
6.96k
    unsigned int consumed = origBuf->len - buf.len;
12914
6.96k
    PORT_Assert(consumed == buf.buf - origBuf->buf);
12915
6.96k
    if (consumed > 0) {
12916
6.96k
        memmove(origBuf->buf, origBuf->buf + consumed, buf.len);
12917
6.96k
        origBuf->len = buf.len;
12918
6.96k
    }
12919
6.96k
}
12920
6.96k
    return SECFailure;
12921
44.9k
}
12922
12923
/* SECStatusToMask returns, in constant time, a mask value of all ones if
12924
 * rv == SECSuccess.  Otherwise it returns zero. */
12925
static unsigned int
12926
SECStatusToMask(SECStatus rv)
12927
0
{
12928
0
    return PORT_CT_EQ(rv, SECSuccess);
12929
0
}
12930
12931
/* ssl_ConstantTimeGE returns 0xffffffff if a>=b and 0x00 otherwise. */
12932
static unsigned char
12933
ssl_ConstantTimeGE(unsigned int a, unsigned int b)
12934
0
{
12935
0
    return PORT_CT_GE(a, b);
12936
0
}
12937
12938
/* ssl_ConstantTimeEQ returns 0xffffffff if a==b and 0x00 otherwise. */
12939
static unsigned char
12940
ssl_ConstantTimeEQ(unsigned char a, unsigned char b)
12941
0
{
12942
0
    return PORT_CT_EQ(a, b);
12943
0
}
12944
12945
/* ssl_constantTimeSelect return a if mask is 0xFF and b if mask is 0x00 */
12946
static unsigned char
12947
ssl_constantTimeSelect(unsigned char mask, unsigned char a, unsigned char b)
12948
0
{
12949
0
    return (mask & a) | (~mask & b);
12950
0
}
12951
12952
static SECStatus
12953
ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
12954
                          unsigned int blockSize,
12955
                          unsigned int macSize)
12956
0
{
12957
0
    unsigned int paddingLength, good;
12958
0
    const unsigned int overhead = 1 /* padding length byte */ + macSize;
12959
0
12960
0
    /* These lengths are all public so we can test them in non-constant
12961
0
     * time. */
12962
0
    if (overhead > plaintext->len) {
12963
0
        return SECFailure;
12964
0
    }
12965
0
12966
0
    paddingLength = plaintext->buf[plaintext->len - 1];
12967
0
    /* SSLv3 padding bytes are random and cannot be checked. */
12968
0
    good = PORT_CT_GE(plaintext->len, paddingLength + overhead);
12969
0
    /* SSLv3 requires that the padding is minimal. */
12970
0
    good &= PORT_CT_GE(blockSize, paddingLength + 1);
12971
0
    plaintext->len -= good & (paddingLength + 1);
12972
0
    return (good & SECSuccess) | (~good & SECFailure);
12973
0
}
12974
12975
SECStatus
12976
ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
12977
0
{
12978
0
    unsigned int paddingLength, good, toCheck, i;
12979
0
    const unsigned int overhead = 1 /* padding length byte */ + macSize;
12980
12981
    /* These lengths are all public so we can test them in non-constant
12982
     * time. */
12983
0
    if (overhead > plaintext->len) {
12984
0
        return SECFailure;
12985
0
    }
12986
12987
0
    paddingLength = plaintext->buf[plaintext->len - 1];
12988
0
    good = PORT_CT_GE(plaintext->len, paddingLength + overhead);
12989
12990
    /* The padding consists of a length byte at the end of the record and then
12991
     * that many bytes of padding, all with the same value as the length byte.
12992
     * Thus, with the length byte included, there are paddingLength+1 bytes of
12993
     * padding.
12994
     *
12995
     * We can't check just |paddingLength+1| bytes because that leaks
12996
     * decrypted information. Therefore we always have to check the maximum
12997
     * amount of padding possible. (Again, the length of the record is
12998
     * public information so we can use it.) */
12999
0
    toCheck = 256; /* maximum amount of padding + 1. */
13000
0
    if (toCheck > plaintext->len) {
13001
0
        toCheck = plaintext->len;
13002
0
    }
13003
13004
0
    for (i = 0; i < toCheck; i++) {
13005
        /* If i <= paddingLength then the MSB of t is zero and mask is
13006
         * 0xff.  Otherwise, mask is 0. */
13007
0
        unsigned char mask = PORT_CT_LE(i, paddingLength);
13008
0
        unsigned char b = plaintext->buf[plaintext->len - 1 - i];
13009
        /* The final |paddingLength+1| bytes should all have the value
13010
         * |paddingLength|. Therefore the XOR should be zero. */
13011
0
        good &= ~(mask & (paddingLength ^ b));
13012
0
    }
13013
13014
    /* If any of the final |paddingLength+1| bytes had the wrong value,
13015
     * one or more of the lower eight bits of |good| will be cleared. We
13016
     * AND the bottom 8 bits together and duplicate the result to all the
13017
     * bits. */
13018
0
    good &= good >> 4;
13019
0
    good &= good >> 2;
13020
0
    good &= good >> 1;
13021
0
    good <<= sizeof(good) * 8 - 1;
13022
0
    good = PORT_CT_DUPLICATE_MSB_TO_ALL(good);
13023
13024
0
    plaintext->len -= good & (paddingLength + 1);
13025
0
    return (good & SECSuccess) | (~good & SECFailure);
13026
0
}
13027
13028
/* On entry:
13029
 *   originalLength >= macSize
13030
 *   macSize <= MAX_MAC_LENGTH
13031
 *   plaintext->len >= macSize
13032
 */
13033
static void
13034
ssl_CBCExtractMAC(sslBuffer *plaintext,
13035
                  unsigned int originalLength,
13036
                  PRUint8 *out,
13037
                  unsigned int macSize)
13038
0
{
13039
0
    unsigned char rotatedMac[MAX_MAC_LENGTH];
13040
0
    /* macEnd is the index of |plaintext->buf| just after the end of the
13041
0
     * MAC. */
13042
0
    unsigned macEnd = plaintext->len;
13043
0
    unsigned macStart = macEnd - macSize;
13044
0
    /* scanStart contains the number of bytes that we can ignore because
13045
0
     * the MAC's position can only vary by 255 bytes. */
13046
0
    unsigned scanStart = 0;
13047
0
    unsigned i, j;
13048
0
    unsigned char rotateOffset;
13049
0
13050
0
    if (originalLength > macSize + 255 + 1) {
13051
0
        scanStart = originalLength - (macSize + 255 + 1);
13052
0
    }
13053
0
13054
0
    /* We want to compute
13055
0
     * rotateOffset = (macStart - scanStart) % macSize
13056
0
     * But the time to compute this varies based on the amount of padding. Thus
13057
0
     * we explicitely handle all mac sizes with (hopefully) constant time modulo
13058
0
     * using Barrett reduction:
13059
0
     *  q := (rotateOffset * m) >> k
13060
0
     *  rotateOffset -= q * n
13061
0
     *  if (n <= rotateOffset) rotateOffset -= n
13062
0
     */
13063
0
    rotateOffset = macStart - scanStart;
13064
0
    /* rotateOffset < 255 + 1 + 48 = 304 */
13065
0
    if (macSize == 16) {
13066
0
        rotateOffset &= 15;
13067
0
    } else if (macSize == 20) {
13068
0
        /*
13069
0
         * Correctness: rotateOffset * ( 1/20 - 25/2^9 ) < 1
13070
0
         *              with rotateOffset <= 853
13071
0
         */
13072
0
        unsigned q = (rotateOffset * 25) >> 9;
13073
0
        rotateOffset -= q * 20;
13074
0
        rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 20),
13075
0
                                               20, 0);
13076
0
    } else if (macSize == 32) {
13077
0
        rotateOffset &= 31;
13078
0
    } else if (macSize == 48) {
13079
0
        /*
13080
0
         * Correctness: rotateOffset * ( 1/48 - 10/2^9 ) < 1
13081
0
         *              with rotateOffset < 768
13082
0
         */
13083
0
        unsigned q = (rotateOffset * 10) >> 9;
13084
0
        rotateOffset -= q * 48;
13085
0
        rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 48),
13086
0
                                               48, 0);
13087
0
    } else {
13088
0
        /*
13089
0
         * SHA384 (macSize == 48) is the largest we support. We should never
13090
0
         * get here.
13091
0
         */
13092
0
        PORT_Assert(0);
13093
0
        rotateOffset = rotateOffset % macSize;
13094
0
    }
13095
0
13096
0
    memset(rotatedMac, 0, macSize);
13097
0
    for (i = scanStart; i < originalLength;) {
13098
0
        for (j = 0; j < macSize && i < originalLength; i++, j++) {
13099
0
            unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
13100
0
            unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
13101
0
            unsigned char b = 0;
13102
0
            b = plaintext->buf[i];
13103
0
            rotatedMac[j] |= b & macStarted & ~macEnded;
13104
0
        }
13105
0
    }
13106
0
13107
0
    /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
13108
0
     * we could line-align |rotatedMac| and rotate in place. */
13109
0
    memset(out, 0, macSize);
13110
0
    rotateOffset = macSize - rotateOffset;
13111
0
    rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
13112
0
                                          0, rotateOffset);
13113
0
    for (i = 0; i < macSize; i++) {
13114
0
        for (j = 0; j < macSize; j++) {
13115
0
            out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ(j, rotateOffset);
13116
0
        }
13117
0
        rotateOffset++;
13118
0
        rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
13119
0
                                              0, rotateOffset);
13120
0
    }
13121
0
}
13122
13123
/* MAX_EXPANSION is the amount by which a record might plausibly be expanded
13124
 * when protected.  It's the worst case estimate, so the sum of block cipher
13125
 * padding (up to 256 octets), HMAC (48 octets for SHA-384), and IV (16
13126
 * octets for AES). */
13127
#define MAX_EXPANSION (256 + 48 + 16)
13128
13129
/* Unprotect an SSL3 record and leave the result in plaintext.
13130
 *
13131
 * If SECFailure is returned, we:
13132
 * 1. Set |*alert| to the alert to be sent.
13133
 * 2. Call PORT_SetError() with an appropriate code.
13134
 *
13135
 * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
13136
 * Therefore, we MUST not call SSL3_SendAlert().
13137
 *
13138
 */
13139
static SECStatus
13140
ssl3_UnprotectRecord(sslSocket *ss,
13141
                     ssl3CipherSpec *spec,
13142
                     SSL3Ciphertext *cText, sslBuffer *plaintext,
13143
                     SSL3AlertDescription *alert)
13144
0
{
13145
0
    const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
13146
0
    PRBool isTLS;
13147
0
    unsigned int good;
13148
0
    unsigned int ivLen = 0;
13149
0
    SSLContentType rType;
13150
0
    SSL3ProtocolVersion rVersion;
13151
0
    unsigned int minLength;
13152
0
    unsigned int originalLen = 0;
13153
0
    PRUint8 headerBuf[13];
13154
0
    sslBuffer header = SSL_BUFFER(headerBuf);
13155
0
    PRUint8 hash[MAX_MAC_LENGTH];
13156
0
    PRUint8 givenHashBuf[MAX_MAC_LENGTH];
13157
0
    PRUint8 *givenHash;
13158
0
    unsigned int hashBytes = MAX_MAC_LENGTH + 1;
13159
0
    SECStatus rv;
13160
0
13161
0
    PORT_Assert(spec->direction == ssl_secret_read);
13162
0
13163
0
    good = ~0U;
13164
0
    minLength = spec->macDef->mac_size;
13165
0
    if (cipher_def->type == type_block) {
13166
0
        /* CBC records have a padding length byte at the end. */
13167
0
        minLength++;
13168
0
        if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
13169
0
            /* With >= TLS 1.1, CBC records have an explicit IV. */
13170
0
            minLength += cipher_def->iv_size;
13171
0
        }
13172
0
    } else if (cipher_def->type == type_aead) {
13173
0
        minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
13174
0
    }
13175
0
13176
0
    /* We can perform this test in variable time because the record's total
13177
0
     * length and the ciphersuite are both public knowledge. */
13178
0
    if (cText->buf->len < minLength) {
13179
0
        goto decrypt_loser;
13180
0
    }
13181
0
13182
0
    if (cipher_def->type == type_block &&
13183
0
        spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
13184
0
        /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
13185
0
         * "The receiver decrypts the entire GenericBlockCipher structure and
13186
0
         * then discards the first cipher block corresponding to the IV
13187
0
         * component." Instead, we decrypt the first cipher block and then
13188
0
         * discard it before decrypting the rest.
13189
0
         */
13190
0
        PRUint8 iv[MAX_IV_LENGTH];
13191
0
        unsigned int decoded;
13192
0
13193
0
        ivLen = cipher_def->iv_size;
13194
0
        if (ivLen < 8 || ivLen > sizeof(iv)) {
13195
0
            *alert = internal_error;
13196
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
13197
0
            return SECFailure;
13198
0
        }
13199
0
13200
0
        PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
13201
0
13202
0
        /* The decryption result is garbage, but since we just throw away
13203
0
         * the block it doesn't matter.  The decryption of the next block
13204
0
         * depends only on the ciphertext of the IV block.
13205
0
         */
13206
0
        rv = spec->cipher(spec->cipherContext, iv, &decoded,
13207
0
                          sizeof(iv), cText->buf->buf, ivLen);
13208
0
13209
0
        good &= SECStatusToMask(rv);
13210
0
    }
13211
0
13212
0
    PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
13213
0
                   cText->buf->len - ivLen));
13214
0
13215
0
    /* Check if the ciphertext can be valid if we assume maximum plaintext and
13216
0
     * add the maximum possible ciphersuite expansion.
13217
0
     * This way we detect overlong plaintexts/padding before decryption.
13218
0
     * This check enforces size limitations more strict than the RFC.
13219
0
     * [RFC5246, Section 6.2.3] */
13220
0
    if (cText->buf->len > (spec->recordSizeLimit + MAX_EXPANSION)) {
13221
0
        *alert = record_overflow;
13222
0
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13223
0
        return SECFailure;
13224
0
    }
13225
0
13226
0
    isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
13227
0
    rType = (SSLContentType)cText->hdr[0];
13228
0
    rVersion = ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
13229
0
               (SSL3ProtocolVersion)cText->hdr[2];
13230
0
    if (cipher_def->type == type_aead) {
13231
0
        /* XXX For many AEAD ciphers, the plaintext is shorter than the
13232
0
         * ciphertext by a fixed byte count, but it is not true in general.
13233
0
         * Each AEAD cipher should provide a function that returns the
13234
0
         * plaintext length for a given ciphertext. */
13235
0
        const unsigned int explicitNonceLen = cipher_def->explicit_nonce_size;
13236
0
        const unsigned int tagLen = cipher_def->tag_size;
13237
0
        unsigned int nonceLen = explicitNonceLen;
13238
0
        unsigned int decryptedLen = cText->buf->len - nonceLen - tagLen;
13239
0
        /* even though read doesn't return and IV, we still need a space to put
13240
0
         * the combined iv/nonce n the gcm 1.2 case*/
13241
0
        unsigned char ivOut[MAX_IV_LENGTH];
13242
0
        unsigned char *iv = NULL;
13243
0
        unsigned char *nonce = NULL;
13244
0
13245
0
        ivLen = cipher_def->iv_size;
13246
0
13247
0
        rv = ssl3_BuildRecordPseudoHeader(
13248
0
            spec->epoch, cText->seqNum,
13249
0
            rType, isTLS, rVersion, IS_DTLS(ss), decryptedLen, &header, spec->version);
13250
0
        PORT_Assert(rv == SECSuccess);
13251
0
13252
0
        /* build the iv */
13253
0
        if (explicitNonceLen == 0) {
13254
0
            nonceLen = sizeof(cText->seqNum);
13255
0
            iv = spec->keyMaterial.iv;
13256
0
            nonce = SSL_BUFFER_BASE(&header);
13257
0
        } else {
13258
0
            PORT_Memcpy(ivOut, spec->keyMaterial.iv, ivLen);
13259
0
            PORT_Memset(ivOut + ivLen, 0, explicitNonceLen);
13260
0
            iv = ivOut;
13261
0
            nonce = cText->buf->buf;
13262
0
            nonceLen = explicitNonceLen;
13263
0
        }
13264
0
        rv = tls13_AEAD(spec->cipherContext, PR_TRUE,
13265
0
                        CKG_NO_GENERATE, 0,       /* iv generator params
13266
0
                                                   * (not used in decrypt)*/
13267
0
                        iv,                       /* iv in */
13268
0
                        NULL,                     /* iv out */
13269
0
                        ivLen + explicitNonceLen, /* full iv length */
13270
0
                        nonce, nonceLen,          /* nonce in */
13271
0
                        SSL_BUFFER_BASE(&header), /* aad */
13272
0
                        SSL_BUFFER_LEN(&header),  /* aadlen */
13273
0
                        plaintext->buf,           /* output  */
13274
0
                        &plaintext->len,          /* out len */
13275
0
                        plaintext->space,         /* max out */
13276
0
                        tagLen,
13277
0
                        cText->buf->buf + explicitNonceLen,  /* input */
13278
0
                        cText->buf->len - explicitNonceLen); /* input len */
13279
0
        if (rv != SECSuccess) {
13280
0
            good = 0;
13281
0
        }
13282
0
    } else {
13283
0
        if (cipher_def->type == type_block &&
13284
0
            ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
13285
0
            goto decrypt_loser;
13286
0
        }
13287
0
13288
0
        /* decrypt from cText buf to plaintext. */
13289
0
        rv = spec->cipher(
13290
0
            spec->cipherContext, plaintext->buf, &plaintext->len,
13291
0
            plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
13292
0
        if (rv != SECSuccess) {
13293
0
            goto decrypt_loser;
13294
0
        }
13295
0
13296
0
        PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
13297
0
13298
0
        originalLen = plaintext->len;
13299
0
13300
0
        /* If it's a block cipher, check and strip the padding. */
13301
0
        if (cipher_def->type == type_block) {
13302
0
            const unsigned int blockSize = cipher_def->block_size;
13303
0
            const unsigned int macSize = spec->macDef->mac_size;
13304
0
13305
0
            if (!isTLS) {
13306
0
                good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
13307
0
                    plaintext, blockSize, macSize));
13308
0
            } else {
13309
0
                good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
13310
0
                    plaintext, macSize));
13311
0
            }
13312
0
        }
13313
0
13314
0
        /* compute the MAC */
13315
0
        rv = ssl3_BuildRecordPseudoHeader(
13316
0
            spec->epoch, cText->seqNum,
13317
0
            rType, isTLS, rVersion, IS_DTLS(ss),
13318
0
            plaintext->len - spec->macDef->mac_size, &header, spec->version);
13319
0
        PORT_Assert(rv == SECSuccess);
13320
0
        if (cipher_def->type == type_block) {
13321
0
            rv = ssl3_ComputeRecordMACConstantTime(
13322
0
                spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
13323
0
                plaintext->buf, plaintext->len, originalLen,
13324
0
                hash, &hashBytes);
13325
0
13326
0
            ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
13327
0
                              spec->macDef->mac_size);
13328
0
            givenHash = givenHashBuf;
13329
0
13330
0
            /* plaintext->len will always have enough space to remove the MAC
13331
0
             * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
13332
0
             * plaintext->len if the result has enough space for the MAC and we
13333
0
             * tested the unadjusted size against minLength, above. */
13334
0
            plaintext->len -= spec->macDef->mac_size;
13335
0
        } else {
13336
0
            /* This is safe because we checked the minLength above. */
13337
0
            plaintext->len -= spec->macDef->mac_size;
13338
0
13339
0
            rv = ssl3_ComputeRecordMAC(
13340
0
                spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
13341
0
                plaintext->buf, plaintext->len, hash, &hashBytes);
13342
0
13343
0
            /* We can read the MAC directly from the record because its location
13344
0
             * is public when a stream cipher is used. */
13345
0
            givenHash = plaintext->buf + plaintext->len;
13346
0
        }
13347
0
13348
0
        good &= SECStatusToMask(rv);
13349
0
13350
0
        if (hashBytes != (unsigned)spec->macDef->mac_size ||
13351
0
            NSS_SecureMemcmp(givenHash, hash, spec->macDef->mac_size) != 0) {
13352
0
            /* We're allowed to leak whether or not the MAC check was correct */
13353
0
            good = 0;
13354
0
        }
13355
0
    }
13356
0
13357
0
    if (good == 0) {
13358
0
    decrypt_loser:
13359
0
        /* always log mac error, in case attacker can read server logs. */
13360
0
        PORT_SetError(SSL_ERROR_BAD_MAC_READ);
13361
0
        *alert = bad_record_mac;
13362
0
        return SECFailure;
13363
0
    }
13364
0
    return SECSuccess;
13365
0
}
13366
13367
SECStatus
13368
ssl3_HandleNonApplicationData(sslSocket *ss, SSLContentType rType,
13369
                              DTLSEpoch epoch, sslSequenceNumber seqNum,
13370
                              sslBuffer *databuf)
13371
58.4k
{
13372
58.4k
    SECStatus rv;
13373
13374
    /* check for Token Presence */
13375
58.4k
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13376
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13377
0
        return SECFailure;
13378
0
    }
13379
13380
58.4k
    ssl_GetSSL3HandshakeLock(ss);
13381
13382
    /* All the functions called in this switch MUST set error code if
13383
    ** they return SECFailure.
13384
    */
13385
58.4k
    switch (rType) {
13386
4.52k
        case ssl_ct_change_cipher_spec:
13387
4.52k
            rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
13388
4.52k
            break;
13389
8.92k
        case ssl_ct_alert:
13390
8.92k
            rv = ssl3_HandleAlert(ss, databuf);
13391
8.92k
            break;
13392
44.9k
        case ssl_ct_handshake:
13393
44.9k
            if (!IS_DTLS(ss)) {
13394
44.9k
                rv = ssl3_HandleHandshake(ss, databuf);
13395
44.9k
            } else {
13396
0
                rv = dtls_HandleHandshake(ss, epoch, seqNum, databuf);
13397
0
            }
13398
44.9k
            break;
13399
2
        case ssl_ct_ack:
13400
2
            if (IS_DTLS(ss) && tls13_MaybeTls13(ss)) {
13401
0
                rv = dtls13_HandleAck(ss, databuf);
13402
0
                break;
13403
0
            }
13404
        /* Fall through. */
13405
48
        default:
13406
            /* If a TLS implementation receives an unexpected record type,
13407
             * it MUST terminate the connection with an "unexpected_message"
13408
             * alert [RFC8446, Section 5].
13409
             *
13410
             * For TLS 1.3 the outer content type is checked before in
13411
             * tls13con.c/tls13_UnprotectRecord(),
13412
             * For DTLS 1.3 the outer content type is checked before in
13413
             * ssl3gthr.c/dtls_GatherData.
13414
             * The inner content types will be checked here.
13415
             *
13416
             * In DTLS generally invalid records SHOULD be silently discarded,
13417
             * no alert is sent [RFC6347, Section 4.1.2.7].
13418
             */
13419
48
            if (!IS_DTLS(ss)) {
13420
48
                SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13421
48
            }
13422
48
            PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
13423
48
            SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
13424
48
                     SSL_GETPID(), ss->fd, rType));
13425
48
            rv = SECFailure;
13426
48
            break;
13427
58.4k
    }
13428
13429
58.4k
    ssl_ReleaseSSL3HandshakeLock(ss);
13430
58.4k
    return rv;
13431
58.4k
}
13432
13433
/* Find the cipher spec to use for a given record. For TLS, this
13434
 * is the current cipherspec. For DTLS, we look up by epoch.
13435
 * In DTLS < 1.3 this just means the current epoch or nothing,
13436
 * but in DTLS >= 1.3, we keep multiple reading cipherspecs.
13437
 * Returns NULL if no appropriate cipher spec is found.
13438
 */
13439
static ssl3CipherSpec *
13440
ssl3_GetCipherSpec(sslSocket *ss, SSL3Ciphertext *cText)
13441
61.0k
{
13442
61.0k
    ssl3CipherSpec *crSpec = ss->ssl3.crSpec;
13443
61.0k
    ssl3CipherSpec *newSpec = NULL;
13444
61.0k
    DTLSEpoch epoch;
13445
13446
61.0k
    if (!IS_DTLS(ss)) {
13447
61.0k
        return crSpec;
13448
61.0k
    }
13449
0
    epoch = dtls_ReadEpoch(crSpec->version, crSpec->epoch, cText->hdr);
13450
0
    if (crSpec->epoch == epoch) {
13451
0
        return crSpec;
13452
0
    }
13453
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
13454
        /* Try to find the cipher spec. */
13455
0
        newSpec = ssl_FindCipherSpecByEpoch(ss, ssl_secret_read,
13456
0
                                            epoch);
13457
0
        if (newSpec != NULL) {
13458
0
            return newSpec;
13459
0
        }
13460
0
    }
13461
0
    SSL_TRC(10, ("%d: DTLS[%d]: %s couldn't find cipherspec from epoch %d",
13462
0
                 SSL_GETPID(), ss->fd, SSL_ROLE(ss), epoch));
13463
0
    return NULL;
13464
0
}
13465
13466
/* if cText is non-null, then decipher and check the MAC of the
13467
 * SSL record from cText->buf (typically gs->inbuf)
13468
 * into databuf (typically gs->buf), and any previous contents of databuf
13469
 * is lost.  Then handle databuf according to its SSL record type,
13470
 * unless it's an application record.
13471
 *
13472
 * If cText is NULL, then the ciphertext has previously been deciphered and
13473
 * checked, and is already sitting in databuf.  It is processed as an SSL
13474
 * Handshake message.
13475
 *
13476
 * DOES NOT process the decrypted application data.
13477
 * On return, databuf contains the decrypted record.
13478
 *
13479
 * Called from ssl3_GatherCompleteHandshake
13480
 *             ssl3_RestartHandshakeAfterCertReq
13481
 *
13482
 * Caller must hold the RecvBufLock.
13483
 *
13484
 * This function aquires and releases the SSL3Handshake Lock, holding the
13485
 * lock around any calls to functions that handle records other than
13486
 * Application Data records.
13487
 */
13488
SECStatus
13489
ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText)
13490
61.0k
{
13491
61.0k
    SECStatus rv = SECFailure;
13492
61.0k
    PRBool isTLS, isTLS13;
13493
61.0k
    DTLSEpoch epoch;
13494
61.0k
    ssl3CipherSpec *spec = NULL;
13495
61.0k
    PRUint16 recordSizeLimit, cTextSizeLimit;
13496
61.0k
    PRBool outOfOrderSpec = PR_FALSE;
13497
61.0k
    SSLContentType rType;
13498
61.0k
    sslBuffer *plaintext = &ss->gs.buf;
13499
61.0k
    SSL3AlertDescription alert = internal_error;
13500
61.0k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
13501
13502
    /* check for Token Presence */
13503
61.0k
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13504
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13505
0
        return SECFailure;
13506
0
    }
13507
13508
    /* Clear out the buffer in case this exits early.  Any data then won't be
13509
     * processed twice. */
13510
61.0k
    plaintext->len = 0;
13511
13512
    /* We're waiting for another ClientHello, which will appear unencrypted.
13513
     * Use the content type to tell whether this should be discarded. */
13514
61.0k
    if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr &&
13515
61.0k
        cText->hdr[0] == ssl_ct_application_data) {
13516
0
        PORT_Assert(ss->ssl3.hs.ws == wait_client_hello);
13517
0
        return SECSuccess;
13518
0
    }
13519
13520
61.0k
    ssl_GetSpecReadLock(ss); /******************************************/
13521
61.0k
    spec = ssl3_GetCipherSpec(ss, cText);
13522
61.0k
    if (!spec) {
13523
0
        PORT_Assert(IS_DTLS(ss));
13524
0
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13525
0
        return SECSuccess;
13526
0
    }
13527
61.0k
    if (spec != ss->ssl3.crSpec) {
13528
0
        PORT_Assert(IS_DTLS(ss));
13529
0
        SSL_TRC(3, ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d",
13530
0
                    SSL_GETPID(), ss->fd, spec->epoch));
13531
0
        outOfOrderSpec = PR_TRUE;
13532
0
    }
13533
61.0k
    isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
13534
61.0k
    if (IS_DTLS(ss)) {
13535
0
        if (dtls13_MaskSequenceNumber(ss, spec, cText->hdr,
13536
0
                                      SSL_BUFFER_BASE(cText->buf), SSL_BUFFER_LEN(cText->buf)) != SECSuccess) {
13537
0
            ssl_ReleaseSpecReadLock(ss); /*****************************/
13538
            /* code already set. */
13539
0
            return SECFailure;
13540
0
        }
13541
0
        if (!dtls_IsRelevant(ss, spec, cText, &cText->seqNum)) {
13542
0
            ssl_ReleaseSpecReadLock(ss); /*****************************/
13543
0
            return SECSuccess;
13544
0
        }
13545
61.0k
    } else {
13546
61.0k
        cText->seqNum = spec->nextSeqNum;
13547
61.0k
    }
13548
61.0k
    if (cText->seqNum >= spec->cipherDef->max_records) {
13549
0
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13550
0
        SSL_TRC(3, ("%d: SSL[%d]: read sequence number at limit 0x%0llx",
13551
0
                    SSL_GETPID(), ss->fd, cText->seqNum));
13552
0
        PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
13553
0
        return SECFailure;
13554
0
    }
13555
13556
61.0k
    isTLS13 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
13557
61.0k
    recordSizeLimit = spec->recordSizeLimit;
13558
61.0k
    cTextSizeLimit = recordSizeLimit;
13559
61.0k
    cTextSizeLimit += (isTLS13) ? TLS_1_3_MAX_EXPANSION : TLS_1_2_MAX_EXPANSION;
13560
13561
    /* Check if the specified recordSizeLimit and the RFC8446 specified max
13562
     * expansion are respected. recordSizeLimit is probably at the default for
13563
     * the first (hello) handshake message and then set to a smaller size by
13564
     * the Record Size Limit Extension.
13565
     * Stricter expansion size checks dependent on implemented cipher suites
13566
     * are performed in ssl3con.c/ssl3_UnprotectRecord() OR
13567
     * tls13con.c/tls13_UnprotextRecord().
13568
     * After Decryption the plaintext size is checked (l. 13424). This also
13569
     * applies to unencrypted records. */
13570
61.0k
    if (cText->buf->len > cTextSizeLimit) {
13571
0
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13572
        /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
13573
0
        if (IS_DTLS(ss)) {
13574
0
            return SECSuccess;
13575
0
        }
13576
0
        SSL3_SendAlert(ss, alert_fatal, record_overflow);
13577
0
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13578
0
        return SECFailure;
13579
0
    }
13580
13581
61.0k
#ifdef DEBUG
13582
    /* In debug builds the gather buffers are freed after the handling of each
13583
     * record for advanced ASAN coverage. Allocate the buffer again to the
13584
     * maximum possibly needed size as on gather initialization in
13585
     * ssl3gthr.c/ssl3_InitGather(). */
13586
61.0k
    PR_ASSERT(sslBuffer_Grow(plaintext, TLS_1_2_MAX_CTEXT_LENGTH) == SECSuccess);
13587
61.0k
#endif
13588
    /* This replaces a dynamic plaintext buffer size check, since the buffer is
13589
     * allocated to the maximum size in ssl3gthr.c/ssl3_InitGather(). The buffer
13590
     * was always grown to the maximum size at first record gathering before. */
13591
61.0k
    PR_ASSERT(plaintext->space >= cTextSizeLimit);
13592
13593
    /* Most record types aside from protected TLS 1.3 records carry the content
13594
     * type in the first octet. TLS 1.3 will override this value later. */
13595
61.0k
    rType = cText->hdr[0];
13596
    /* Encrypted application data records could arrive before the handshake
13597
     * completes in DTLS 1.3. These can look like valid TLS 1.2 application_data
13598
     * records in epoch 0, which is never valid. Pretend they didn't decrypt. */
13599
61.0k
    if (spec->epoch == 0 && ((IS_DTLS(ss) &&
13600
38.2k
                              dtls_IsDtls13Ciphertext(0, rType)) ||
13601
38.2k
                             rType == ssl_ct_application_data)) {
13602
4
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
13603
4
        alert = unexpected_message;
13604
4
        rv = SECFailure;
13605
61.0k
    } else {
13606
61.0k
#ifdef UNSAFE_FUZZER_MODE
13607
61.0k
        rv = Null_Cipher(NULL, plaintext->buf, &plaintext->len,
13608
61.0k
                         plaintext->space, cText->buf->buf, cText->buf->len);
13609
#else
13610
        /* IMPORTANT:
13611
         * Unprotect functions MUST NOT send alerts
13612
         * because we still hold the spec read lock. Instead, if they
13613
         * return SECFailure, they set *alert to the alert to be sent.
13614
         * Additionaly, this is used to silently drop DTLS encryption/record
13615
         * errors/alerts using the error handling below as suggested in the
13616
         * DTLS specification [RFC6347, Section 4.1.2.7]. */
13617
        if (spec->cipherDef->cipher == cipher_null && cText->buf->len == 0) {
13618
            /* Handle a zero-length unprotected record
13619
             * In this case, we treat it as a no-op and let later functions decide
13620
             * whether to ignore or alert accordingly. */
13621
            PR_ASSERT(plaintext->len == 0);
13622
            rv = SECSuccess;
13623
        } else if (spec->version < SSL_LIBRARY_VERSION_TLS_1_3 || spec->epoch == 0) {
13624
            rv = ssl3_UnprotectRecord(ss, spec, cText, plaintext, &alert);
13625
        } else {
13626
            rv = tls13_UnprotectRecord(ss, spec, cText, plaintext, &rType,
13627
                                       &alert);
13628
        }
13629
#endif
13630
61.0k
    }
13631
13632
    /* Error/Alert handling for ssl3/tls13_UnprotectRecord */
13633
61.0k
    if (rv != SECSuccess) {
13634
4
        ssl_ReleaseSpecReadLock(ss); /***************************/
13635
13636
4
        SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
13637
13638
        /* Ensure that we don't process this data again. */
13639
4
        plaintext->len = 0;
13640
13641
        /* Ignore a CCS if compatibility mode is negotiated.  Note that this
13642
         * will fail if the server fails to negotiate compatibility mode in a
13643
         * 0-RTT session that is resumed from a session that did negotiate it.
13644
         * We don't care about that corner case right now. */
13645
4
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
13646
4
            cText->hdr[0] == ssl_ct_change_cipher_spec &&
13647
4
            ss->ssl3.hs.ws != idle_handshake &&
13648
4
            cText->buf->len == 1 &&
13649
4
            cText->buf->buf[0] == change_cipher_spec_choice) {
13650
0
            if (!ss->ssl3.hs.rejectCcs) {
13651
                /* Allow only the first CCS. */
13652
0
                ss->ssl3.hs.rejectCcs = PR_TRUE;
13653
0
                return SECSuccess;
13654
0
            } else {
13655
0
                alert = unexpected_message;
13656
0
                PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
13657
0
            }
13658
0
        }
13659
13660
        /* All errors/alerts that might occur during unprotection are related
13661
         * to invalid records (e.g. invalid formatting, length, MAC, ...).
13662
         * Following the DTLS specification such errors/alerts SHOULD be
13663
         * dropped silently [RFC9147, Section 4.5.2].
13664
         * This is done below. */
13665
13666
4
        if ((IS_DTLS(ss) && !dtls13_AeadLimitReached(spec)) ||
13667
4
            (!IS_DTLS(ss) && ss->sec.isServer &&
13668
4
             ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_trial)) {
13669
            /* Silently drop the packet unless we set ss->ssl3.fatalAlertSent.
13670
             * (Manually or by using functions like
13671
             * SSL3_SendAlert(.., alert_fatal,..))
13672
             * This is not currently used in the unprotection functions since
13673
             * all TLS and DTLS errors are propagated to this handler. */
13674
0
            if (ss->ssl3.fatalAlertSent) {
13675
0
                return SECFailure;
13676
0
            }
13677
0
            return SECSuccess;
13678
0
        }
13679
13680
4
        int errCode = PORT_GetError();
13681
4
        SSL3_SendAlert(ss, alert_fatal, alert);
13682
        /* Reset the error code in case SSL3_SendAlert called
13683
         * PORT_SetError(). */
13684
4
        PORT_SetError(errCode);
13685
4
        return SECFailure;
13686
4
    }
13687
13688
    /* SECSuccess */
13689
61.0k
    if (IS_DTLS(ss)) {
13690
0
        dtls_RecordSetRecvd(&spec->recvdRecords, cText->seqNum);
13691
0
        spec->nextSeqNum = PR_MAX(spec->nextSeqNum, cText->seqNum + 1);
13692
61.0k
    } else {
13693
61.0k
        ++spec->nextSeqNum;
13694
61.0k
    }
13695
61.0k
    epoch = spec->epoch;
13696
13697
61.0k
    ssl_ReleaseSpecReadLock(ss); /*****************************************/
13698
13699
    /*
13700
     * The decrypted data is now in plaintext.
13701
     */
13702
13703
    /* IMPORTANT: We are in DTLS 1.3 mode and we have processed something
13704
     * from the wrong epoch. Divert to a divert processing function to make
13705
     * sure we don't accidentally use the data unsafely. */
13706
13707
    /* We temporary allowed reading the records from the previous epoch n-1
13708
    until the moment we get a message from the new epoch n. */
13709
13710
61.0k
    if (outOfOrderSpec) {
13711
0
        PORT_Assert(IS_DTLS(ss) && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
13712
0
        ssl_GetSSL3HandshakeLock(ss);
13713
0
        if (ss->ssl3.hs.allowPreviousEpoch && spec->epoch == ss->ssl3.crSpec->epoch - 1) {
13714
0
            SSL_TRC(30, ("%d: DTLS13[%d]: Out of order message %d is accepted",
13715
0
                         SSL_GETPID(), ss->fd, spec->epoch));
13716
0
            ssl_ReleaseSSL3HandshakeLock(ss);
13717
0
        } else {
13718
0
            ssl_ReleaseSSL3HandshakeLock(ss);
13719
0
            return dtls13_HandleOutOfEpochRecord(ss, spec, rType, plaintext);
13720
0
        }
13721
61.0k
    } else {
13722
61.0k
        ssl_GetSSL3HandshakeLock(ss);
13723
        /* Forbid (application) messages from the previous epoch.
13724
           From now, messages that arrive out of order will be discarded. */
13725
61.0k
        ss->ssl3.hs.allowPreviousEpoch = PR_FALSE;
13726
61.0k
        ssl_ReleaseSSL3HandshakeLock(ss);
13727
61.0k
    }
13728
13729
    /* Check the length of the plaintext. */
13730
61.0k
    if (isTLS && plaintext->len > recordSizeLimit) {
13731
10
        plaintext->len = 0;
13732
        /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
13733
10
        if (IS_DTLS(ss)) {
13734
0
            return SECSuccess;
13735
0
        }
13736
10
        SSL3_SendAlert(ss, alert_fatal, record_overflow);
13737
10
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13738
10
        return SECFailure;
13739
10
    }
13740
13741
    /* Application data records are processed by the caller of this
13742
    ** function, not by this function.
13743
    */
13744
61.0k
    if (rType == ssl_ct_application_data) {
13745
2.61k
        if (ss->firstHsDone)
13746
2.61k
            return SECSuccess;
13747
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
13748
0
            ss->sec.isServer &&
13749
0
            ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
13750
0
            return tls13_HandleEarlyApplicationData(ss, plaintext);
13751
0
        }
13752
0
        plaintext->len = 0;
13753
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13754
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
13755
0
        return SECFailure;
13756
0
    }
13757
13758
58.4k
    rv = ssl3_HandleNonApplicationData(ss, rType, epoch, cText->seqNum,
13759
58.4k
                                       plaintext);
13760
13761
58.4k
#ifdef DEBUG
13762
    /* In Debug builds free and zero gather plaintext buffer after its content
13763
     * has been used/copied for advanced ASAN coverage/utilization.
13764
     * This frees buffer for non application data records, for application data
13765
     * records it is freed in sslsecur.c/DoRecv(). */
13766
58.4k
    sslBuffer_Clear(&ss->gs.buf);
13767
58.4k
#endif
13768
13769
58.4k
    return rv;
13770
61.0k
}
13771
13772
/*
13773
 * Initialization functions
13774
 */
13775
13776
void
13777
ssl_InitSecState(sslSecurityInfo *sec)
13778
9.52k
{
13779
9.52k
    sec->authType = ssl_auth_null;
13780
9.52k
    sec->authKeyBits = 0;
13781
9.52k
    sec->signatureScheme = ssl_sig_none;
13782
9.52k
    sec->keaType = ssl_kea_null;
13783
9.52k
    sec->keaKeyBits = 0;
13784
9.52k
    sec->keaGroup = NULL;
13785
9.52k
}
13786
13787
SECStatus
13788
ssl3_InitState(sslSocket *ss)
13789
9.52k
{
13790
9.52k
    SECStatus rv;
13791
13792
9.52k
    ss->ssl3.policy = SSL_ALLOWED;
13793
13794
9.52k
    ssl_InitSecState(&ss->sec);
13795
13796
9.52k
    ssl_GetSpecWriteLock(ss);
13797
9.52k
    PR_INIT_CLIST(&ss->ssl3.hs.cipherSpecs);
13798
9.52k
    rv = ssl_SetupNullCipherSpec(ss, ssl_secret_read);
13799
9.52k
    rv |= ssl_SetupNullCipherSpec(ss, ssl_secret_write);
13800
9.52k
    ss->ssl3.pwSpec = ss->ssl3.prSpec = NULL;
13801
9.52k
    ssl_ReleaseSpecWriteLock(ss);
13802
9.52k
    if (rv != SECSuccess) {
13803
        /* Rely on ssl_CreateNullCipherSpec() to set error code. */
13804
0
        return SECFailure;
13805
0
    }
13806
13807
9.52k
    ss->ssl3.hs.sendingSCSV = PR_FALSE;
13808
9.52k
    ss->ssl3.hs.preliminaryInfo = 0;
13809
9.52k
    ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : idle_handshake;
13810
13811
9.52k
    ssl3_ResetExtensionData(&ss->xtnData, ss);
13812
9.52k
    PR_INIT_CLIST(&ss->ssl3.hs.remoteExtensions);
13813
9.52k
    PR_INIT_CLIST(&ss->ssl3.hs.echOuterExtensions);
13814
9.52k
    if (IS_DTLS(ss)) {
13815
0
        ss->ssl3.hs.sendMessageSeq = 0;
13816
0
        ss->ssl3.hs.recvMessageSeq = 0;
13817
0
        ss->ssl3.hs.rtTimer->timeout = DTLS_RETRANSMIT_INITIAL_MS;
13818
0
        ss->ssl3.hs.rtRetries = 0;
13819
0
        ss->ssl3.hs.recvdHighWater = -1;
13820
0
        PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
13821
0
        dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
13822
0
    }
13823
13824
9.52k
    ss->ssl3.hs.currentSecret = NULL;
13825
9.52k
    ss->ssl3.hs.resumptionMasterSecret = NULL;
13826
9.52k
    ss->ssl3.hs.dheSecret = NULL;
13827
9.52k
    ss->ssl3.hs.clientEarlyTrafficSecret = NULL;
13828
9.52k
    ss->ssl3.hs.clientHsTrafficSecret = NULL;
13829
9.52k
    ss->ssl3.hs.serverHsTrafficSecret = NULL;
13830
9.52k
    ss->ssl3.hs.clientTrafficSecret = NULL;
13831
9.52k
    ss->ssl3.hs.serverTrafficSecret = NULL;
13832
9.52k
    ss->ssl3.hs.echHpkeCtx = NULL;
13833
9.52k
    ss->ssl3.hs.greaseEchSize = 100;
13834
9.52k
    ss->ssl3.hs.echAccepted = PR_FALSE;
13835
9.52k
    ss->ssl3.hs.echDecided = PR_FALSE;
13836
13837
9.52k
    ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
13838
9.52k
    ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
13839
13840
9.52k
    PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
13841
9.52k
    ss->ssl3.hs.messages.buf = NULL;
13842
9.52k
    ss->ssl3.hs.messages.space = 0;
13843
13844
9.52k
    ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
13845
9.52k
    PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0,
13846
9.52k
                sizeof(ss->ssl3.hs.newSessionTicket));
13847
13848
9.52k
    ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
13849
9.52k
    return SECSuccess;
13850
9.52k
}
13851
13852
/* record the export policy for this cipher suite */
13853
SECStatus
13854
ssl3_SetPolicy(ssl3CipherSuite which, int policy)
13855
0
{
13856
0
    ssl3CipherSuiteCfg *suite;
13857
13858
0
    suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
13859
0
    if (suite == NULL) {
13860
0
        return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13861
0
    }
13862
0
    suite->policy = policy;
13863
13864
0
    return SECSuccess;
13865
0
}
13866
13867
SECStatus
13868
ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
13869
0
{
13870
0
    const ssl3CipherSuiteCfg *suite;
13871
0
    PRInt32 policy;
13872
0
    SECStatus rv;
13873
13874
0
    suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13875
0
    if (suite) {
13876
0
        policy = suite->policy;
13877
0
        rv = SECSuccess;
13878
0
    } else {
13879
0
        policy = SSL_NOT_ALLOWED;
13880
0
        rv = SECFailure; /* err code was set by Lookup. */
13881
0
    }
13882
0
    *oPolicy = policy;
13883
0
    return rv;
13884
0
}
13885
13886
/* record the user preference for this suite */
13887
SECStatus
13888
ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
13889
0
{
13890
0
    ssl3CipherSuiteCfg *suite;
13891
13892
0
    suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
13893
0
    if (suite == NULL) {
13894
0
        return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13895
0
    }
13896
0
    suite->enabled = enabled;
13897
0
    return SECSuccess;
13898
0
}
13899
13900
/* return the user preference for this suite */
13901
SECStatus
13902
ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
13903
0
{
13904
0
    const ssl3CipherSuiteCfg *suite;
13905
0
    PRBool pref;
13906
0
    SECStatus rv;
13907
13908
0
    suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13909
0
    if (suite) {
13910
0
        pref = suite->enabled;
13911
0
        rv = SECSuccess;
13912
0
    } else {
13913
0
        pref = SSL_NOT_ALLOWED;
13914
0
        rv = SECFailure; /* err code was set by Lookup. */
13915
0
    }
13916
0
    *enabled = pref;
13917
0
    return rv;
13918
0
}
13919
13920
SECStatus
13921
ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
13922
676k
{
13923
676k
    ssl3CipherSuiteCfg *suite;
13924
13925
676k
    suite = ssl_LookupCipherSuiteCfgMutable(which, ss->cipherSuites);
13926
676k
    if (suite == NULL) {
13927
0
        return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13928
0
    }
13929
676k
    suite->enabled = enabled;
13930
676k
    return SECSuccess;
13931
676k
}
13932
13933
SECStatus
13934
ssl3_CipherPrefGet(const sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
13935
13.7k
{
13936
13.7k
    const ssl3CipherSuiteCfg *suite;
13937
13.7k
    PRBool pref;
13938
13.7k
    SECStatus rv;
13939
13940
13.7k
    suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
13941
13.7k
    if (suite) {
13942
13.7k
        pref = suite->enabled;
13943
13.7k
        rv = SECSuccess;
13944
13.7k
    } else {
13945
0
        pref = SSL_NOT_ALLOWED;
13946
0
        rv = SECFailure; /* err code was set by Lookup. */
13947
0
    }
13948
13.7k
    *enabled = pref;
13949
13.7k
    return rv;
13950
13.7k
}
13951
13952
SECStatus
13953
SSL_SignatureSchemePrefSet(PRFileDesc *fd, const SSLSignatureScheme *schemes,
13954
                           unsigned int count)
13955
0
{
13956
0
    sslSocket *ss;
13957
0
    unsigned int i;
13958
0
    unsigned int supported = 0;
13959
13960
0
    ss = ssl_FindSocket(fd);
13961
0
    if (!ss) {
13962
0
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefSet",
13963
0
                 SSL_GETPID(), fd));
13964
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
13965
0
        return SECFailure;
13966
0
    }
13967
13968
0
    if (!count) {
13969
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
13970
0
        return SECFailure;
13971
0
    }
13972
13973
0
    for (i = 0; i < count; ++i) {
13974
0
        if (ssl_IsSupportedSignatureScheme(schemes[i])) {
13975
0
            ++supported;
13976
0
        }
13977
0
    }
13978
    /* We don't check for duplicates, so it's possible to get too many. */
13979
0
    if (supported > MAX_SIGNATURE_SCHEMES) {
13980
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
13981
0
        return SECFailure;
13982
0
    }
13983
13984
0
    ss->ssl3.signatureSchemeCount = 0;
13985
0
    for (i = 0; i < count; ++i) {
13986
0
        if (!ssl_IsSupportedSignatureScheme(schemes[i])) {
13987
0
            SSL_DBG(("%d: SSL[%d]: invalid signature scheme %d ignored",
13988
0
                     SSL_GETPID(), fd, schemes[i]));
13989
0
            continue;
13990
0
        }
13991
13992
0
        ss->ssl3.signatureSchemes[ss->ssl3.signatureSchemeCount++] = schemes[i];
13993
0
    }
13994
13995
0
    if (ss->ssl3.signatureSchemeCount == 0) {
13996
0
        PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
13997
0
        return SECFailure;
13998
0
    }
13999
0
    return SECSuccess;
14000
0
}
14001
14002
SECStatus
14003
SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms,
14004
                     unsigned int count)
14005
0
{
14006
0
    SSLSignatureScheme schemes[MAX_SIGNATURE_SCHEMES];
14007
0
    unsigned int i;
14008
14009
0
    count = PR_MIN(PR_ARRAY_SIZE(schemes), count);
14010
0
    for (i = 0; i < count; ++i) {
14011
0
        schemes[i] = (algorithms[i].hashAlg << 8) | algorithms[i].sigAlg;
14012
0
    }
14013
0
    return SSL_SignatureSchemePrefSet(fd, schemes, count);
14014
0
}
14015
14016
SECStatus
14017
SSL_SignatureSchemePrefGet(PRFileDesc *fd, SSLSignatureScheme *schemes,
14018
                           unsigned int *count, unsigned int maxCount)
14019
0
{
14020
0
    sslSocket *ss;
14021
14022
0
    ss = ssl_FindSocket(fd);
14023
0
    if (!ss) {
14024
0
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefGet",
14025
0
                 SSL_GETPID(), fd));
14026
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14027
0
        return SECFailure;
14028
0
    }
14029
14030
0
    if (!schemes || !count ||
14031
0
        maxCount < ss->ssl3.signatureSchemeCount) {
14032
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14033
0
        return SECFailure;
14034
0
    }
14035
14036
0
    PORT_Memcpy(schemes, ss->ssl3.signatureSchemes,
14037
0
                ss->ssl3.signatureSchemeCount * sizeof(SSLSignatureScheme));
14038
0
    *count = ss->ssl3.signatureSchemeCount;
14039
0
    return SECSuccess;
14040
0
}
14041
14042
SECStatus
14043
SSL_SignaturePrefGet(PRFileDesc *fd, SSLSignatureAndHashAlg *algorithms,
14044
                     unsigned int *count, unsigned int maxCount)
14045
0
{
14046
0
    sslSocket *ss;
14047
0
    unsigned int i;
14048
14049
0
    ss = ssl_FindSocket(fd);
14050
0
    if (!ss) {
14051
0
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignaturePrefGet",
14052
0
                 SSL_GETPID(), fd));
14053
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14054
0
        return SECFailure;
14055
0
    }
14056
14057
0
    if (!algorithms || !count ||
14058
0
        maxCount < ss->ssl3.signatureSchemeCount) {
14059
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14060
0
        return SECFailure;
14061
0
    }
14062
14063
0
    for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
14064
0
        algorithms[i].hashAlg = (ss->ssl3.signatureSchemes[i] >> 8) & 0xff;
14065
0
        algorithms[i].sigAlg = ss->ssl3.signatureSchemes[i] & 0xff;
14066
0
    }
14067
0
    *count = ss->ssl3.signatureSchemeCount;
14068
0
    return SECSuccess;
14069
0
}
14070
14071
unsigned int
14072
SSL_SignatureMaxCount(void)
14073
0
{
14074
0
    return MAX_SIGNATURE_SCHEMES;
14075
0
}
14076
14077
/* copy global default policy into socket. */
14078
void
14079
ssl3_InitSocketPolicy(sslSocket *ss)
14080
9.52k
{
14081
9.52k
    PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof(cipherSuites));
14082
9.52k
    PORT_Memcpy(ss->ssl3.signatureSchemes, defaultSignatureSchemes,
14083
9.52k
                sizeof(defaultSignatureSchemes));
14084
9.52k
    ss->ssl3.signatureSchemeCount = PR_ARRAY_SIZE(defaultSignatureSchemes);
14085
9.52k
}
14086
14087
/*
14088
** If ssl3 socket has completed the first handshake, and is in idle state,
14089
** then start a new handshake.
14090
** If flushCache is true, the SID cache will be flushed first, forcing a
14091
** "Full" handshake (not a session restart handshake), to be done.
14092
**
14093
** called from SSL_RedoHandshake(), which already holds the handshake locks.
14094
*/
14095
SECStatus
14096
ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
14097
0
{
14098
0
    sslSessionID *sid = ss->sec.ci.sid;
14099
0
    SECStatus rv;
14100
14101
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
14102
14103
0
    if (!ss->firstHsDone || (ss->ssl3.hs.ws != idle_handshake)) {
14104
0
        PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
14105
0
        return SECFailure;
14106
0
    }
14107
14108
0
    if (IS_DTLS(ss)) {
14109
0
        dtls_RehandshakeCleanup(ss);
14110
0
    }
14111
14112
0
    if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER ||
14113
0
        ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
14114
0
        PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
14115
0
        return SECFailure;
14116
0
    }
14117
0
    if (ss->version > ss->vrange.max || ss->version < ss->vrange.min) {
14118
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
14119
0
        return SECFailure;
14120
0
    }
14121
14122
0
    if (sid && flushCache) {
14123
0
        ssl_UncacheSessionID(ss); /* remove it from whichever cache it's in. */
14124
0
        ssl_FreeSID(sid);         /* dec ref count and free if zero. */
14125
0
        ss->sec.ci.sid = NULL;
14126
0
    }
14127
14128
0
    ssl_GetXmitBufLock(ss); /**************************************/
14129
14130
    /* start off a new handshake. */
14131
0
    if (ss->sec.isServer) {
14132
0
        rv = ssl3_SendHelloRequest(ss);
14133
0
    } else {
14134
0
        rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
14135
0
    }
14136
14137
0
    ssl_ReleaseXmitBufLock(ss); /**************************************/
14138
0
    return rv;
14139
0
}
14140
14141
/* Called from ssl_DestroySocketContents() in sslsock.c */
14142
void
14143
ssl3_DestroySSL3Info(sslSocket *ss)
14144
9.52k
{
14145
14146
9.52k
    if (ss->ssl3.clientCertificate != NULL)
14147
0
        CERT_DestroyCertificate(ss->ssl3.clientCertificate);
14148
14149
9.52k
    if (ss->ssl3.clientPrivateKey != NULL)
14150
0
        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
14151
14152
9.52k
    if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL) {
14153
0
        PORT_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
14154
0
        ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
14155
0
        ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
14156
0
    }
14157
14158
9.52k
    if (ss->ssl3.peerCertArena != NULL)
14159
5.02k
        ssl3_CleanupPeerCerts(ss);
14160
14161
9.52k
    if (ss->ssl3.clientCertChain != NULL) {
14162
0
        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
14163
0
        ss->ssl3.clientCertChain = NULL;
14164
0
    }
14165
9.52k
    if (ss->ssl3.ca_list) {
14166
0
        CERT_FreeDistNames(ss->ssl3.ca_list);
14167
0
    }
14168
14169
    /* clean up handshake */
14170
9.52k
    if (ss->ssl3.hs.md5) {
14171
3.76k
        PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
14172
3.76k
    }
14173
9.52k
    if (ss->ssl3.hs.sha) {
14174
3.87k
        PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
14175
3.87k
    }
14176
9.52k
    if (ss->ssl3.hs.shaEchInner) {
14177
0
        PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
14178
0
    }
14179
9.52k
    if (ss->ssl3.hs.shaPostHandshake) {
14180
0
        PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
14181
0
    }
14182
9.52k
    if (ss->ssl3.hs.messages.buf) {
14183
5.64k
        sslBuffer_Clear(&ss->ssl3.hs.messages);
14184
5.64k
    }
14185
9.52k
    if (ss->ssl3.hs.echInnerMessages.buf) {
14186
0
        sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
14187
0
    }
14188
9.52k
    if (ss->ssl3.hs.dtls13ClientMessageBuffer.buf) {
14189
0
        sslBuffer_Clear(&ss->ssl3.hs.dtls13ClientMessageBuffer);
14190
0
    }
14191
14192
    /* free the SSL3Buffer (msg_body) */
14193
9.52k
    PORT_Free(ss->ssl3.hs.msg_body.buf);
14194
14195
9.52k
    SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
14196
9.52k
    SECITEM_FreeItem(&ss->ssl3.hs.srvVirtName, PR_FALSE);
14197
9.52k
    SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
14198
14199
    /* Destroy the DTLS data */
14200
9.52k
    if (IS_DTLS(ss)) {
14201
0
        dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
14202
0
        if (ss->ssl3.hs.recvdFragments.buf) {
14203
0
            PORT_Free(ss->ssl3.hs.recvdFragments.buf);
14204
0
        }
14205
0
    }
14206
14207
    /* Destroy remote extensions */
14208
9.52k
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
14209
9.52k
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.echOuterExtensions);
14210
9.52k
    ssl3_DestroyExtensionData(&ss->xtnData);
14211
14212
    /* Destroy cipher specs */
14213
9.52k
    ssl_DestroyCipherSpecs(&ss->ssl3.hs.cipherSpecs);
14214
14215
    /* Destroy TLS 1.3 keys */
14216
9.52k
    if (ss->ssl3.hs.currentSecret)
14217
0
        PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
14218
9.52k
    if (ss->ssl3.hs.resumptionMasterSecret)
14219
0
        PK11_FreeSymKey(ss->ssl3.hs.resumptionMasterSecret);
14220
9.52k
    if (ss->ssl3.hs.dheSecret)
14221
0
        PK11_FreeSymKey(ss->ssl3.hs.dheSecret);
14222
9.52k
    if (ss->ssl3.hs.clientEarlyTrafficSecret)
14223
0
        PK11_FreeSymKey(ss->ssl3.hs.clientEarlyTrafficSecret);
14224
9.52k
    if (ss->ssl3.hs.clientHsTrafficSecret)
14225
0
        PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
14226
9.52k
    if (ss->ssl3.hs.serverHsTrafficSecret)
14227
0
        PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
14228
9.52k
    if (ss->ssl3.hs.clientTrafficSecret)
14229
0
        PK11_FreeSymKey(ss->ssl3.hs.clientTrafficSecret);
14230
9.52k
    if (ss->ssl3.hs.serverTrafficSecret)
14231
0
        PK11_FreeSymKey(ss->ssl3.hs.serverTrafficSecret);
14232
9.52k
    if (ss->ssl3.hs.earlyExporterSecret)
14233
0
        PK11_FreeSymKey(ss->ssl3.hs.earlyExporterSecret);
14234
9.52k
    if (ss->ssl3.hs.exporterSecret)
14235
0
        PK11_FreeSymKey(ss->ssl3.hs.exporterSecret);
14236
14237
9.52k
    ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
14238
    /* Destroy TLS 1.3 buffered early data. */
14239
9.52k
    tls13_DestroyEarlyData(&ss->ssl3.hs.bufferedEarlyData);
14240
14241
    /* Destroy TLS 1.3 PSKs. */
14242
9.52k
    tls13_DestroyPskList(&ss->ssl3.hs.psks);
14243
14244
    /* TLS 1.3 ECH state. */
14245
9.52k
    PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE);
14246
9.52k
    PORT_Free((void *)ss->ssl3.hs.echPublicName); /* CONST */
14247
9.52k
    sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
14248
14249
    /* TLS 1.3 GREASE (client) state. */
14250
9.52k
    tls13_ClientGreaseDestroy(ss);
14251
14252
    /* TLS ClientHello Extension Permutation state. */
14253
9.52k
    tls_ClientHelloExtensionPermutationDestroy(ss);
14254
9.52k
}
14255
14256
/* check if the current cipher spec is FIPS. We only need to
14257
 * check the contexts here, if the kea, prf or keys were not FIPS,
14258
 * that status would have been rolled up in the create context
14259
 * call */
14260
static PRBool
14261
ssl_cipherSpecIsFips(ssl3CipherSpec *spec)
14262
0
{
14263
0
    if (!spec || !spec->cipherDef) {
14264
0
        return PR_FALSE;
14265
0
    }
14266
14267
0
    if (spec->cipherDef->type != type_aead) {
14268
0
        if (spec->keyMaterial.macContext == NULL) {
14269
0
            return PR_FALSE;
14270
0
        }
14271
0
        if (!PK11_ContextGetFIPSStatus(spec->keyMaterial.macContext)) {
14272
0
            return PR_FALSE;
14273
0
        }
14274
0
    }
14275
0
    if (!spec->cipherContext) {
14276
0
        return PR_FALSE;
14277
0
    }
14278
0
    return PK11_ContextGetFIPSStatus(spec->cipherContext);
14279
0
}
14280
14281
/* return true if the current operation is running in FIPS mode */
14282
PRBool
14283
ssl_isFIPS(sslSocket *ss)
14284
0
{
14285
0
    if (!ssl_cipherSpecIsFips(ss->ssl3.crSpec)) {
14286
0
        return PR_FALSE;
14287
0
    }
14288
0
    return ssl_cipherSpecIsFips(ss->ssl3.cwSpec);
14289
0
}
14290
14291
/*
14292
 * parse the policy value for a single algorithm in a cipher_suite,
14293
 *   return TRUE if we disallow by the cipher suite by policy
14294
 *   (we don't have to parse any more algorithm policies on this cipher suite),
14295
 *  otherwise return FALSE.
14296
 *   1. If we don't have the required policy, disable by default, disallow by
14297
 *      policy and return TRUE (no more processing needed).
14298
 *   2. If we have the required policy, and we are disabled, return FALSE,
14299
 *      (if we are disabled, we only need to parse policy, not default).
14300
 *   3. If we have the required policy, and we aren't adjusting the defaults
14301
 *      return FALSE. (only parsing the policy, not default).
14302
 *   4. We have the required policy and we are adjusting the defaults.
14303
 *      If we are setting default = FALSE, set isDisabled to true so that
14304
 *      we don't try to re-enable the cipher suite based on a different
14305
 *      algorithm.
14306
 */
14307
PRBool
14308
ssl_HandlePolicy(int cipher_suite, SECOidTag policyOid,
14309
                 PRUint32 requiredPolicy, PRBool *isDisabled)
14310
0
{
14311
0
    PRUint32 policy;
14312
0
    SECStatus rv;
14313
14314
    /* first fetch the policy for this algorithm */
14315
0
    rv = NSS_GetAlgorithmPolicy(policyOid, &policy);
14316
0
    if (rv != SECSuccess) {
14317
0
        return PR_FALSE; /* no policy value, continue to the next algorithm */
14318
0
    }
14319
    /* first, are we allowed by policy, if not turn off allow and disable */
14320
0
    if (!(policy & requiredPolicy)) {
14321
0
        ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE);
14322
0
        ssl_CipherPolicySet(cipher_suite, SSL_NOT_ALLOWED);
14323
0
        return PR_TRUE;
14324
0
    }
14325
    /* If we are already disabled, or the policy isn't setting a default
14326
     * we are done processing this algorithm */
14327
0
    if (*isDisabled || (policy & NSS_USE_DEFAULT_NOT_VALID)) {
14328
0
        return PR_FALSE;
14329
0
    }
14330
    /* set the default value for the cipher suite. If we disable the cipher
14331
     * suite, remember that so we don't process the next default. This has
14332
     * the effect of disabling the whole cipher suite if any of the
14333
     * algorithms it uses are disabled by default. We still have to
14334
     * process the upper level because the cipher suite is still allowed
14335
     * by policy, and we may still have to disallow it based on other
14336
     * algorithms in the cipher suite. */
14337
0
    if (policy & NSS_USE_DEFAULT_SSL_ENABLE) {
14338
0
        ssl_CipherPrefSetDefault(cipher_suite, PR_TRUE);
14339
0
    } else {
14340
0
        *isDisabled = PR_TRUE;
14341
0
        ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE);
14342
0
    }
14343
0
    return PR_FALSE;
14344
0
}
14345
14346
0
#define MAP_NULL(x) (((x) != 0) ? (x) : SEC_OID_NULL_CIPHER)
14347
14348
SECStatus
14349
ssl3_ApplyNSSPolicy(void)
14350
1
{
14351
1
    unsigned i;
14352
1
    SECStatus rv;
14353
1
    PRUint32 policy = 0;
14354
14355
1
    rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy);
14356
1
    if (rv != SECSuccess || !(policy & NSS_USE_POLICY_IN_SSL)) {
14357
1
        return SECSuccess; /* do nothing */
14358
1
    }
14359
14360
    /* disable every ciphersuite */
14361
0
    for (i = 1; i < PR_ARRAY_SIZE(cipher_suite_defs); ++i) {
14362
0
        const ssl3CipherSuiteDef *suite = &cipher_suite_defs[i];
14363
0
        SECOidTag policyOid;
14364
0
        PRBool isDisabled = PR_FALSE;
14365
14366
        /* if we haven't explicitly disabled it below enable by policy */
14367
0
        ssl_CipherPolicySet(suite->cipher_suite, SSL_ALLOWED);
14368
14369
        /* now check the various key exchange, ciphers and macs and
14370
         * if we ever disallow by policy, we are done, go to the next cipher
14371
         */
14372
0
        policyOid = MAP_NULL(kea_defs[suite->key_exchange_alg].oid);
14373
0
        if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14374
0
                             NSS_USE_ALG_IN_SSL_KX, &isDisabled)) {
14375
0
            continue;
14376
0
        }
14377
14378
0
        policyOid = MAP_NULL(ssl_GetBulkCipherDef(suite)->oid);
14379
0
        if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14380
0
                             NSS_USE_ALG_IN_SSL, &isDisabled)) {
14381
0
            continue;
14382
0
        }
14383
14384
0
        if (ssl_GetBulkCipherDef(suite)->type != type_aead) {
14385
0
            policyOid = MAP_NULL(ssl_GetMacDefByAlg(suite->mac_alg)->oid);
14386
0
            if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14387
0
                                 NSS_USE_ALG_IN_SSL, &isDisabled)) {
14388
0
                continue;
14389
0
            }
14390
0
        }
14391
0
    }
14392
14393
0
    rv = ssl3_ConstrainRangeByPolicy();
14394
14395
0
    return rv;
14396
1
}
14397
14398
/* End of ssl3con.c */