Coverage Report

Created: 2026-10-13 06:23

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/nss/lib/ssl/ssl3con.c
Line
Count
Source
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 <limits.h>
41
#include <stdio.h>
42
43
static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
44
                                       PK11SlotInfo *serverKeySlot);
45
static SECStatus ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
46
                                          PK11SymKey **msp);
47
static SECStatus ssl3_DeriveConnectionKeys(sslSocket *ss,
48
                                           PK11SymKey *masterSecret);
49
static SECStatus ssl3_HandshakeFailure(sslSocket *ss);
50
static SECStatus ssl3_SendCertificate(sslSocket *ss);
51
static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
52
static SECStatus ssl3_SendNextProto(sslSocket *ss);
53
static SECStatus ssl3_SendFinished(sslSocket *ss, PRInt32 flags);
54
static SECStatus ssl3_SendServerHelloDone(sslSocket *ss);
55
static SECStatus ssl3_SendServerKeyExchange(sslSocket *ss);
56
static SECStatus ssl3_HandleClientHelloPart2(sslSocket *ss,
57
                                             SECItem *suites,
58
                                             sslSessionID *sid,
59
                                             const PRUint8 *msg,
60
                                             unsigned int len);
61
static SECStatus ssl3_HandleServerHelloPart2(sslSocket *ss,
62
                                             const SECItem *sidBytes,
63
                                             int *retErrCode);
64
static SECStatus ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss,
65
                                                      PRUint8 *b,
66
                                                      PRUint32 length);
67
static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
68
static CK_MECHANISM_TYPE ssl3_GetHashMechanismByHashType(SSLHashType hashType);
69
static CK_MECHANISM_TYPE ssl3_GetMgfMechanismByHashType(SSLHashType hash);
70
PRBool ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme);
71
PRBool ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme);
72
PRBool ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme);
73
PRBool ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme);
74
PRBool ssl_IsMldsaSignatureScheme(SSLSignatureScheme scheme);
75
static SECStatus ssl3_UpdateDefaultHandshakeHashes(sslSocket *ss,
76
                                                   const unsigned char *b,
77
                                                   unsigned int l);
78
const PRUint32 kSSLSigSchemePolicy =
79
    NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_ANY_SIGNATURE;
80
81
const PRUint8 ssl_hello_retry_random[] = {
82
    0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
83
    0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
84
    0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
85
    0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
86
};
87
PR_STATIC_ASSERT(PR_ARRAY_SIZE(ssl_hello_retry_random) == SSL3_RANDOM_LENGTH);
88
89
/* This list of SSL3 cipher suites is sorted in descending order of
90
 * precedence (desirability).  It only includes cipher suites we implement.
91
 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
92
 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
93
 */
94
/* clang-format off */
95
static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
96
   /*      cipher_suite                     policy       enabled   isPresent */
97
 /* Special TLS 1.3 suites. */
98
 { TLS_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE },
99
 { TLS_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE },
100
 { TLS_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE },
101
102
 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
103
 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,   SSL_ALLOWED, PR_TRUE, PR_FALSE},
104
 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
105
 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,   SSL_ALLOWED, PR_TRUE, PR_FALSE},
106
 { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE},
107
 { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,   SSL_ALLOWED, PR_TRUE, PR_FALSE},
108
 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,    SSL_ALLOWED, PR_TRUE, PR_FALSE},
109
 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,      SSL_ALLOWED, PR_TRUE, PR_FALSE},
110
 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
111
 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,   SSL_ALLOWED, PR_TRUE, PR_FALSE},
112
 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,    SSL_ALLOWED, PR_TRUE, PR_FALSE},
113
 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,      SSL_ALLOWED, PR_TRUE, PR_FALSE},
114
 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE},
115
 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
116
 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
117
 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
118
 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,        SSL_ALLOWED, PR_FALSE, PR_FALSE},
119
 { TLS_ECDHE_RSA_WITH_RC4_128_SHA,          SSL_ALLOWED, PR_FALSE, PR_FALSE},
120
121
 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
122
 { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,SSL_ALLOWED,PR_TRUE,  PR_FALSE},
123
 { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
124
 { TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
125
 { TLS_DHE_DSS_WITH_AES_256_GCM_SHA384,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
126
 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
127
 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
128
 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
129
 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
130
 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
131
 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
132
 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
133
 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
134
 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
135
 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
136
 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
137
 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
138
 { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,       SSL_ALLOWED, PR_TRUE,  PR_FALSE},
139
 { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,       SSL_ALLOWED, PR_TRUE,  PR_FALSE},
140
 { TLS_DHE_DSS_WITH_RC4_128_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
141
142
 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
143
 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
144
 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
145
 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
146
 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,    SSL_ALLOWED, PR_FALSE, PR_FALSE},
147
 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
148
 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA,         SSL_ALLOWED, PR_FALSE, PR_FALSE},
149
 { TLS_ECDH_RSA_WITH_RC4_128_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
150
151
 /* RSA */
152
 { TLS_RSA_WITH_AES_128_GCM_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
153
 { TLS_RSA_WITH_AES_256_GCM_SHA384,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
154
 { TLS_RSA_WITH_AES_128_CBC_SHA,            SSL_ALLOWED, PR_TRUE,  PR_FALSE},
155
 { TLS_RSA_WITH_AES_128_CBC_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
156
 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
157
 { TLS_RSA_WITH_AES_256_CBC_SHA,            SSL_ALLOWED, PR_TRUE,  PR_FALSE},
158
 { TLS_RSA_WITH_AES_256_CBC_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
159
 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
160
 { TLS_RSA_WITH_SEED_CBC_SHA,               SSL_ALLOWED, PR_FALSE, PR_FALSE},
161
 { TLS_RSA_WITH_3DES_EDE_CBC_SHA,           SSL_ALLOWED, PR_TRUE,  PR_FALSE},
162
 { TLS_RSA_WITH_RC4_128_SHA,                SSL_ALLOWED, PR_TRUE,  PR_FALSE},
163
 { TLS_RSA_WITH_RC4_128_MD5,                SSL_ALLOWED, PR_TRUE,  PR_FALSE},
164
165
 /* 56-bit DES "domestic" cipher suites */
166
 { TLS_DHE_RSA_WITH_DES_CBC_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
167
 { TLS_DHE_DSS_WITH_DES_CBC_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
168
 { TLS_RSA_WITH_DES_CBC_SHA,                SSL_ALLOWED, PR_FALSE, PR_FALSE},
169
170
 /* ciphersuites with no encryption */
171
 { TLS_ECDHE_ECDSA_WITH_NULL_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
172
 { TLS_ECDHE_RSA_WITH_NULL_SHA,             SSL_ALLOWED, PR_FALSE, PR_FALSE},
173
 { TLS_ECDH_RSA_WITH_NULL_SHA,              SSL_ALLOWED, PR_FALSE, PR_FALSE},
174
 { TLS_ECDH_ECDSA_WITH_NULL_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
175
 { TLS_RSA_WITH_NULL_SHA,                   SSL_ALLOWED, PR_FALSE, PR_FALSE},
176
 { TLS_RSA_WITH_NULL_SHA256,                SSL_ALLOWED, PR_FALSE, PR_FALSE},
177
 { TLS_RSA_WITH_NULL_MD5,                   SSL_ALLOWED, PR_FALSE, PR_FALSE},
178
};
179
/* clang-format on */
180
181
/* This is the default supported set of signature schemes.  The order of the
182
 * hashes here is all that is important, since that will (sometimes) determine
183
 * which hash we use.  The key pair (i.e., cert) is the primary thing that
184
 * determines what we use and this doesn't affect how we select key pairs.  The
185
 * order of signature types is based on the same rules for ordering we use for
186
 * cipher suites just for consistency.
187
 */
188
static const SSLSignatureScheme defaultSignatureSchemes[] = {
189
    ssl_sig_ecdsa_secp256r1_sha256,
190
    ssl_sig_ecdsa_secp384r1_sha384,
191
    ssl_sig_ecdsa_secp521r1_sha512,
192
    ssl_sig_ecdsa_sha1,
193
    ssl_sig_rsa_pss_rsae_sha256,
194
    ssl_sig_rsa_pss_rsae_sha384,
195
    ssl_sig_rsa_pss_rsae_sha512,
196
    ssl_sig_rsa_pkcs1_sha256,
197
    ssl_sig_rsa_pkcs1_sha384,
198
    ssl_sig_rsa_pkcs1_sha512,
199
    ssl_sig_rsa_pkcs1_sha1,
200
    ssl_sig_dsa_sha256,
201
    ssl_sig_dsa_sha384,
202
    ssl_sig_dsa_sha512,
203
    ssl_sig_dsa_sha1,
204
    ssl_sig_mldsa44,
205
    ssl_sig_mldsa65,
206
    ssl_sig_mldsa87,
207
};
208
PR_STATIC_ASSERT(PR_ARRAY_SIZE(defaultSignatureSchemes) <=
209
                 MAX_SIGNATURE_SCHEMES);
210
211
/* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order.
212
 */
213
#ifdef DEBUG
214
void
215
ssl3_CheckCipherSuiteOrderConsistency()
216
9
{
217
9
    unsigned int i;
218
219
9
    PORT_Assert(SSL_NumImplementedCiphers == PR_ARRAY_SIZE(cipherSuites));
220
221
648
    for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) {
222
639
        PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite);
223
639
    }
224
9
}
225
#endif
226
227
static const /*SSL3ClientCertificateType */ PRUint8 certificate_types[] = {
228
    ct_RSA_sign,
229
    ct_ECDSA_sign,
230
    ct_DSS_sign,
231
};
232
233
static SSL3Statistics ssl3stats;
234
235
static const ssl3KEADef kea_defs[] = {
236
    /* indexed by SSL3KeyExchangeAlgorithm */
237
    /* kea            exchKeyType signKeyType authKeyType ephemeral  oid */
238
    { kea_null, ssl_kea_null, nullKey, ssl_auth_null, PR_FALSE, 0 },
239
    { kea_rsa, ssl_kea_rsa, nullKey, ssl_auth_rsa_decrypt, PR_FALSE, SEC_OID_TLS_RSA },
240
    { kea_dh_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_FALSE, SEC_OID_TLS_DH_DSS },
241
    { kea_dh_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_FALSE, SEC_OID_TLS_DH_RSA },
242
    { kea_dhe_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_TRUE, SEC_OID_TLS_DHE_DSS },
243
    { kea_dhe_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_DHE_RSA },
244
    { kea_dh_anon, ssl_kea_dh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_DH_ANON },
245
    { kea_ecdh_ecdsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_ecdsa, PR_FALSE, SEC_OID_TLS_ECDH_ECDSA },
246
    { kea_ecdhe_ecdsa, ssl_kea_ecdh, ecKey, ssl_auth_ecdsa, PR_TRUE, SEC_OID_TLS_ECDHE_ECDSA },
247
    { kea_ecdh_rsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_rsa, PR_FALSE, SEC_OID_TLS_ECDH_RSA },
248
    { kea_ecdhe_rsa, ssl_kea_ecdh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_ECDHE_RSA },
249
    { kea_ecdh_anon, ssl_kea_ecdh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_ECDH_ANON },
250
    { kea_ecdhe_psk, ssl_kea_ecdh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_ECDHE_PSK },
251
    { kea_dhe_psk, ssl_kea_dh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_DHE_PSK },
252
    { kea_tls13_any, ssl_kea_tls13_any, nullKey, ssl_auth_tls13_any, PR_TRUE, SEC_OID_TLS13_KEA_ANY },
253
};
254
255
/* must use ssl_LookupCipherSuiteDef to access */
256
static const ssl3CipherSuiteDef cipher_suite_defs[] = {
257
    /*  cipher_suite                    bulk_cipher_alg mac_alg key_exchange_alg prf_hash */
258
    /*  Note that the prf_hash_alg is the hash function used by the PRF, see sslimpl.h.  */
259
260
    { TLS_NULL_WITH_NULL_NULL, cipher_null, ssl_mac_null, kea_null, ssl_hash_none },
261
    { TLS_RSA_WITH_NULL_MD5, cipher_null, ssl_mac_md5, kea_rsa, ssl_hash_none },
262
    { TLS_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_rsa, ssl_hash_none },
263
    { TLS_RSA_WITH_NULL_SHA256, cipher_null, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
264
    { TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, ssl_mac_md5, kea_rsa, ssl_hash_none },
265
    { TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_rsa, ssl_hash_none },
266
    { TLS_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_rsa, ssl_hash_none },
267
    { TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_rsa, ssl_hash_none },
268
    { TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
269
    { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
270
      cipher_3des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
271
    { TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
272
    { TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
273
    { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
274
      cipher_3des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
275
276
    /* New TLS cipher suites */
277
    { TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
278
    { TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
279
    { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
280
    { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
281
    { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
282
    { TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
283
    { TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
284
    { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
285
    { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
286
    { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
287
    { TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha384 },
288
289
    { TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, ssl_mac_sha, kea_rsa, ssl_hash_none },
290
291
    { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
292
    { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
293
      cipher_camellia_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
294
    { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
295
      cipher_camellia_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
296
    { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
297
    { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
298
      cipher_camellia_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
299
    { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
300
      cipher_camellia_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
301
302
    { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
303
    { TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha256 },
304
305
    { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
306
    { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
307
    { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha384 },
308
    { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha384 },
309
    { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_ecdsa, ssl_hash_sha384 },
310
    { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_rsa, ssl_hash_sha384 },
311
    { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha256 },
312
    { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
313
    { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
314
    { TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha384 },
315
    { TLS_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha384 },
316
317
    { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
318
319
    { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
320
    { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
321
322
    { TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
323
    { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
324
    { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
325
    { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
326
    { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
327
328
    { TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
329
    { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
330
    { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
331
    { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
332
    { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_ecdsa, ssl_hash_sha256 },
333
    { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
334
335
    { TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
336
    { TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
337
    { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
338
    { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
339
    { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
340
341
    { TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
342
    { TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
343
    { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
344
    { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
345
    { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_rsa, ssl_hash_sha256 },
346
    { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
347
348
    { TLS_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
349
    { TLS_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
350
    { TLS_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha384 },
351
};
352
353
static const CK_MECHANISM_TYPE auth_alg_defs[] = {
354
    CKM_INVALID_MECHANISM, /* ssl_auth_null */
355
    CKM_RSA_PKCS,          /* ssl_auth_rsa_decrypt */
356
    CKM_DSA,
357
    /* ? _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_HKDF_DATA,         /* ssl_auth_psk (just check for HKDF) */
365
    CKM_INVALID_MECHANISM, /* ssl_auth_tls13_any */
366
    CKM_ML_DSA,            /* ssl_auth_mldsa44 */
367
    CKM_ML_DSA,            /* ssl_auth_mldsa65 */
368
    CKM_ML_DSA,            /* ssl_auth_mldsa87 */
369
};
370
PR_STATIC_ASSERT(PR_ARRAY_SIZE(auth_alg_defs) == ssl_auth_size);
371
372
static const CK_MECHANISM_TYPE kea_alg_defs[] = {
373
    CKM_INVALID_MECHANISM, /* ssl_kea_null */
374
    CKM_RSA_PKCS,          /* ssl_kea_rsa */
375
    CKM_DH_PKCS_DERIVE,    /* ssl_kea_dh */
376
    CKM_INVALID_MECHANISM, /* ssl_kea_fortezza (unused) */
377
    CKM_ECDH1_DERIVE,      /* ssl_kea_ecdh */
378
    CKM_ECDH1_DERIVE,      /* ssl_kea_ecdh_psk */
379
    CKM_DH_PKCS_DERIVE,    /* ssl_kea_dh_psk */
380
    CKM_INVALID_MECHANISM, /* ssl_kea_tls13_any */
381
    CKM_INVALID_MECHANISM, /* ssl_kea_ecdh_hybrid */
382
    CKM_INVALID_MECHANISM, /* ssl_kea_ecdh_hybrid_psk */
383
    CKM_INVALID_MECHANISM, /* ssl_kea_kem */
384
    CKM_INVALID_MECHANISM, /* ssl_kea_kem_psk */
385
};
386
PR_STATIC_ASSERT(PR_ARRAY_SIZE(kea_alg_defs) == ssl_kea_size);
387
388
typedef struct SSLCipher2MechStr {
389
    SSLCipherAlgorithm calg;
390
    CK_MECHANISM_TYPE cmech;
391
} SSLCipher2Mech;
392
393
/* indexed by type SSLCipherAlgorithm */
394
static const SSLCipher2Mech alg2Mech[] = {
395
    /* calg,          cmech  */
396
    { ssl_calg_null, CKM_INVALID_MECHANISM },
397
    { ssl_calg_rc4, CKM_RC4 },
398
    { ssl_calg_rc2, CKM_RC2_CBC },
399
    { ssl_calg_des, CKM_DES_CBC },
400
    { ssl_calg_3des, CKM_DES3_CBC },
401
    { ssl_calg_idea, CKM_IDEA_CBC },
402
    { ssl_calg_fortezza, CKM_SKIPJACK_CBC64 },
403
    { ssl_calg_aes, CKM_AES_CBC },
404
    { ssl_calg_camellia, CKM_CAMELLIA_CBC },
405
    { ssl_calg_seed, CKM_SEED_CBC },
406
    { ssl_calg_aes_gcm, CKM_AES_GCM },
407
    { ssl_calg_chacha20, CKM_CHACHA20_POLY1305 },
408
};
409
410
const PRUint8 tls12_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
411
                                           0x47, 0x52, 0x44, 0x01 };
412
const PRUint8 tls1_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
413
                                          0x47, 0x52, 0x44, 0x00 };
414
PR_STATIC_ASSERT(sizeof(tls12_downgrade_random) ==
415
                 sizeof(tls1_downgrade_random));
416
417
/* The ECCWrappedKeyInfo structure defines how various pieces of
418
 * information are laid out within wrappedSymmetricWrappingkey
419
 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
420
 * a 512-byte buffer (see sslimpl.h), the variable length field
421
 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
422
 *
423
 * XXX For now, NSS only supports named elliptic curves of size 571 bits
424
 * or smaller. The public value will fit within 145 bytes and EC params
425
 * will fit within 12 bytes. We'll need to revisit this when NSS
426
 * supports arbitrary curves.
427
 */
428
68
#define MAX_EC_WRAPPED_KEY_BUFLEN 504
429
430
typedef struct ECCWrappedKeyInfoStr {
431
    PRUint16 size;                          /* EC public key size in bits */
432
    PRUint16 encodedParamLen;               /* length (in bytes) of DER encoded EC params */
433
    PRUint16 pubValueLen;                   /* length (in bytes) of EC public value */
434
    PRUint16 wrappedKeyLen;                 /* length (in bytes) of the wrapped key */
435
    PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
436
    /* EC public-key params, the EC public value and the wrapped key  */
437
} ECCWrappedKeyInfo;
438
439
CK_MECHANISM_TYPE
440
ssl3_Alg2Mech(SSLCipherAlgorithm calg)
441
16.0M
{
442
16.0M
    PORT_Assert(alg2Mech[calg].calg == calg);
443
16.0M
    return alg2Mech[calg].cmech;
444
16.0M
}
445
446
#if defined(TRACE)
447
448
static char *
449
ssl3_DecodeHandshakeType(int msgType)
450
0
{
451
0
    char *rv;
452
0
    static char line[40];
453
454
0
    switch (msgType) {
455
0
        case ssl_hs_hello_request:
456
0
            rv = "hello_request (0)";
457
0
            break;
458
0
        case ssl_hs_client_hello:
459
0
            rv = "client_hello  (1)";
460
0
            break;
461
0
        case ssl_hs_server_hello:
462
0
            rv = "server_hello  (2)";
463
0
            break;
464
0
        case ssl_hs_hello_verify_request:
465
0
            rv = "hello_verify_request (3)";
466
0
            break;
467
0
        case ssl_hs_new_session_ticket:
468
0
            rv = "new_session_ticket (4)";
469
0
            break;
470
0
        case ssl_hs_end_of_early_data:
471
0
            rv = "end_of_early_data (5)";
472
0
            break;
473
0
        case ssl_hs_hello_retry_request:
474
0
            rv = "hello_retry_request (6)";
475
0
            break;
476
0
        case ssl_hs_encrypted_extensions:
477
0
            rv = "encrypted_extensions (8)";
478
0
            break;
479
0
        case ssl_hs_certificate:
480
0
            rv = "certificate  (11)";
481
0
            break;
482
0
        case ssl_hs_server_key_exchange:
483
0
            rv = "server_key_exchange (12)";
484
0
            break;
485
0
        case ssl_hs_certificate_request:
486
0
            rv = "certificate_request (13)";
487
0
            break;
488
0
        case ssl_hs_server_hello_done:
489
0
            rv = "server_hello_done   (14)";
490
0
            break;
491
0
        case ssl_hs_certificate_verify:
492
0
            rv = "certificate_verify  (15)";
493
0
            break;
494
0
        case ssl_hs_client_key_exchange:
495
0
            rv = "client_key_exchange (16)";
496
0
            break;
497
0
        case ssl_hs_finished:
498
0
            rv = "finished     (20)";
499
0
            break;
500
0
        case ssl_hs_certificate_status:
501
0
            rv = "certificate_status  (22)";
502
0
            break;
503
0
        case ssl_hs_key_update:
504
0
            rv = "key_update   (24)";
505
0
            break;
506
0
        case ssl_hs_compressed_certificate:
507
0
            rv = "compressed certificate (25)";
508
0
            break;
509
0
        default:
510
0
            snprintf(line, sizeof(line), "*UNKNOWN* handshake type! (%d)", msgType);
511
0
            rv = line;
512
0
    }
513
0
    return rv;
514
0
}
515
516
static char *
517
ssl3_DecodeContentType(int msgType)
518
0
{
519
0
    char *rv;
520
0
    static char line[40];
521
522
0
    switch (msgType) {
523
0
        case ssl_ct_change_cipher_spec:
524
0
            rv = "change_cipher_spec (20)";
525
0
            break;
526
0
        case ssl_ct_alert:
527
0
            rv = "alert      (21)";
528
0
            break;
529
0
        case ssl_ct_handshake:
530
0
            rv = "handshake  (22)";
531
0
            break;
532
0
        case ssl_ct_application_data:
533
0
            rv = "application_data (23)";
534
0
            break;
535
0
        case ssl_ct_ack:
536
0
            rv = "ack (26)";
537
0
            break;
538
0
        default:
539
0
            snprintf(line, sizeof(line), "*UNKNOWN* record type! (%d)", msgType);
540
0
            rv = line;
541
0
    }
542
0
    return rv;
543
0
}
544
545
#endif
546
547
PRBool
548
ssl_HaveRecvBufLock(sslSocket *ss)
549
19.8M
{
550
19.8M
    if (!ss->opt.noLocks) {
551
19.8M
        return PR_InMonitor(ss->recvBufLock);
552
19.8M
    } else {
553
0
        return PR_TRUE;
554
0
    }
555
19.8M
}
556
557
PRBool
558
ssl_HaveXmitBufLock(sslSocket *ss)
559
20.1M
{
560
20.1M
    if (!ss->opt.noLocks) {
561
20.1M
        return PR_InMonitor(ss->xmitBufLock);
562
20.1M
    } else {
563
0
        return PR_TRUE;
564
0
    }
565
20.1M
}
566
567
PRBool
568
ssl_Have1stHandshakeLock(sslSocket *ss)
569
715k
{
570
715k
    if (!ss->opt.noLocks) {
571
715k
        return PR_InMonitor(ss->firstHandshakeLock);
572
715k
    } else {
573
0
        return PR_TRUE;
574
0
    }
575
715k
}
576
577
PRBool
578
ssl_HaveSSL3HandshakeLock(sslSocket *ss)
579
7.20M
{
580
7.20M
    if (!ss->opt.noLocks) {
581
7.19M
        return PR_InMonitor(ss->ssl3HandshakeLock);
582
7.19M
    } else {
583
15.3k
        return PR_TRUE;
584
15.3k
    }
585
7.20M
}
586
587
PRBool
588
ssl_HaveSpecWriteLock(sslSocket *ss)
589
299k
{
590
299k
    if (!ss->opt.noLocks) {
591
299k
        return NSSRWLock_HaveWriteLock(ss->specLock);
592
299k
    } else {
593
0
        return PR_TRUE;
594
0
    }
595
299k
}
596
597
/* firstHandshakeLock -> recvBufLock */
598
void
599
ssl_Get1stHandshakeLock(sslSocket *ss)
600
2.43M
{
601
2.43M
    if (!ss->opt.noLocks) {
602
1.60M
        PORT_Assert(PR_InMonitor(ss->firstHandshakeLock) ||
603
1.60M
                    !ssl_HaveRecvBufLock(ss));
604
1.60M
        PR_EnterMonitor(ss->firstHandshakeLock);
605
1.60M
    }
606
2.43M
}
607
608
void
609
ssl_Release1stHandshakeLock(sslSocket *ss)
610
1.12M
{
611
1.12M
    if (!ss->opt.noLocks) {
612
481k
        PR_ExitMonitor(ss->firstHandshakeLock);
613
481k
    }
614
1.12M
}
615
616
void
617
ssl_GetSSL3HandshakeLock(sslSocket *ss)
618
29.1M
{
619
29.1M
    if (!ss->opt.noLocks) {
620
18.0M
        PORT_Assert(!ssl_HaveXmitBufLock(ss));
621
18.0M
        PR_EnterMonitor(ss->ssl3HandshakeLock);
622
18.0M
    }
623
29.1M
}
624
625
void
626
ssl_ReleaseSSL3HandshakeLock(sslSocket *ss)
627
27.8M
{
628
27.8M
    if (!ss->opt.noLocks) {
629
16.9M
        PR_ExitMonitor(ss->ssl3HandshakeLock);
630
16.9M
    }
631
27.8M
}
632
633
void
634
ssl_GetSpecReadLock(sslSocket *ss)
635
15.0M
{
636
15.0M
    if (!ss->opt.noLocks) {
637
8.47M
        NSSRWLock_LockRead(ss->specLock);
638
8.47M
    }
639
15.0M
}
640
641
void
642
ssl_ReleaseSpecReadLock(sslSocket *ss)
643
15.0M
{
644
15.0M
    if (!ss->opt.noLocks) {
645
8.47M
        NSSRWLock_UnlockRead(ss->specLock);
646
8.47M
    }
647
15.0M
}
648
649
/* NSSRWLock_HaveReadLock is not exported so there's no
650
 * ssl_HaveSpecReadLock. */
651
void
652
ssl_GetSpecWriteLock(sslSocket *ss)
653
936k
{
654
936k
    if (!ss->opt.noLocks) {
655
501k
        NSSRWLock_LockWrite(ss->specLock);
656
501k
    }
657
936k
}
658
659
void
660
ssl_ReleaseSpecWriteLock(sslSocket *ss)
661
936k
{
662
936k
    if (!ss->opt.noLocks) {
663
501k
        NSSRWLock_UnlockWrite(ss->specLock);
664
501k
    }
665
936k
}
666
667
/* recvBufLock -> ssl3HandshakeLock -> xmitBufLock */
668
void
669
ssl_GetRecvBufLock(sslSocket *ss)
670
935k
{
671
935k
    if (!ss->opt.noLocks) {
672
289k
        PORT_Assert(!ssl_HaveSSL3HandshakeLock(ss));
673
289k
        PORT_Assert(!ssl_HaveXmitBufLock(ss));
674
289k
        PR_EnterMonitor(ss->recvBufLock);
675
289k
    }
676
935k
}
677
678
void
679
ssl_ReleaseRecvBufLock(sslSocket *ss)
680
935k
{
681
935k
    if (!ss->opt.noLocks) {
682
289k
        PR_ExitMonitor(ss->recvBufLock);
683
289k
    }
684
935k
}
685
686
/* xmitBufLock -> specLock */
687
void
688
ssl_GetXmitBufLock(sslSocket *ss)
689
3.04M
{
690
3.04M
    if (!ss->opt.noLocks) {
691
1.01M
        PR_EnterMonitor(ss->xmitBufLock);
692
1.01M
    }
693
3.04M
}
694
695
void
696
ssl_ReleaseXmitBufLock(sslSocket *ss)
697
3.04M
{
698
3.04M
    if (!ss->opt.noLocks) {
699
1.01M
        PR_ExitMonitor(ss->xmitBufLock);
700
1.01M
    }
701
3.04M
}
702
703
SSL3Statistics *
704
SSL_GetStatistics(void)
705
24.2k
{
706
24.2k
    return &ssl3stats;
707
24.2k
}
708
709
typedef struct tooLongStr {
710
#if defined(IS_LITTLE_ENDIAN)
711
    PRInt32 low;
712
    PRInt32 high;
713
#else
714
    PRInt32 high;
715
    PRInt32 low;
716
#endif
717
} tooLong;
718
719
void
720
SSL_AtomicIncrementLong(long *x)
721
213k
{
722
213k
    if ((sizeof *x) == sizeof(PRInt32)) {
723
0
        PR_ATOMIC_INCREMENT((PRInt32 *)x);
724
213k
    } else {
725
213k
        tooLong *tl = (tooLong *)x;
726
213k
        if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
727
0
            PR_ATOMIC_INCREMENT(&tl->high);
728
213k
    }
729
213k
}
730
731
PRBool
732
ssl3_CipherSuiteAllowedForVersionRange(ssl3CipherSuite cipherSuite,
733
                                       const SSLVersionRange *vrange)
734
7.72M
{
735
7.72M
    switch (cipherSuite) {
736
103k
        case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
737
215k
        case TLS_RSA_WITH_AES_256_CBC_SHA256:
738
354k
        case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
739
492k
        case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
740
632k
        case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
741
770k
        case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
742
874k
        case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
743
998k
        case TLS_RSA_WITH_AES_128_CBC_SHA256:
744
1.12M
        case TLS_RSA_WITH_AES_128_GCM_SHA256:
745
1.25M
        case TLS_RSA_WITH_AES_256_GCM_SHA384:
746
1.33M
        case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
747
1.41M
        case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
748
1.49M
        case TLS_RSA_WITH_NULL_SHA256:
749
1.57M
        case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
750
1.65M
        case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
751
1.80M
        case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
752
1.94M
        case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
753
2.09M
        case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
754
2.24M
        case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
755
2.34M
        case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
756
2.45M
        case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
757
2.59M
        case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
758
2.74M
        case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
759
2.84M
        case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
760
2.84M
            return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2 &&
761
2.24M
                   vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
762
763
        /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and
764
         * point formats.*/
765
89.9k
        case TLS_ECDH_ECDSA_WITH_NULL_SHA:
766
189k
        case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
767
313k
        case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
768
436k
        case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
769
558k
        case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
770
648k
        case TLS_ECDHE_ECDSA_WITH_NULL_SHA:
771
749k
        case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
772
875k
        case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
773
1.01M
        case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
774
1.15M
        case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
775
1.23M
        case TLS_ECDH_RSA_WITH_NULL_SHA:
776
1.29M
        case TLS_ECDH_RSA_WITH_RC4_128_SHA:
777
1.37M
        case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
778
1.45M
        case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
779
1.55M
        case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
780
1.64M
        case TLS_ECDHE_RSA_WITH_NULL_SHA:
781
1.74M
        case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
782
1.87M
        case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
783
2.01M
        case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
784
2.15M
        case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
785
2.15M
            return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0 &&
786
2.15M
                   vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
787
788
165k
        case TLS_AES_128_GCM_SHA256:
789
323k
        case TLS_AES_256_GCM_SHA384:
790
482k
        case TLS_CHACHA20_POLY1305_SHA256:
791
482k
            return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_3;
792
793
2.24M
        default:
794
2.24M
            return vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
795
7.72M
    }
796
7.72M
}
797
798
/* return pointer to ssl3CipherSuiteDef for suite, or NULL */
799
/* XXX This does a linear search.  A binary search would be better. */
800
const ssl3CipherSuiteDef *
801
ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
802
23.9M
{
803
23.9M
    int cipher_suite_def_len =
804
23.9M
        sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
805
23.9M
    int i;
806
807
906M
    for (i = 0; i < cipher_suite_def_len; i++) {
808
906M
        if (cipher_suite_defs[i].cipher_suite == suite)
809
23.9M
            return &cipher_suite_defs[i];
810
906M
    }
811
0
    PORT_Assert(PR_FALSE); /* We should never get here. */
812
0
    PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
813
0
    return NULL;
814
23.9M
}
815
816
/* Find the cipher configuration struct associate with suite */
817
/* XXX This does a linear search.  A binary search would be better. */
818
static ssl3CipherSuiteCfg *
819
ssl_LookupCipherSuiteCfgMutable(ssl3CipherSuite suite,
820
                                ssl3CipherSuiteCfg *suites)
821
4.76M
{
822
4.76M
    int i;
823
824
170M
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
825
170M
        if (suites[i].cipher_suite == suite)
826
4.76M
            return &suites[i];
827
170M
    }
828
    /* return NULL and let the caller handle it.  */
829
0
    PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
830
0
    return NULL;
831
4.76M
}
832
833
const ssl3CipherSuiteCfg *
834
ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, const ssl3CipherSuiteCfg *suites)
835
162k
{
836
162k
    return ssl_LookupCipherSuiteCfgMutable(suite,
837
162k
                                           CONST_CAST(ssl3CipherSuiteCfg, suites));
838
162k
}
839
840
static PRBool
841
ssl_NamedGroupTypeEnabled(const sslSocket *ss, SSLKEAType keaType)
842
4.79M
{
843
4.79M
    unsigned int i;
844
21.5M
    for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
845
21.4M
        if (ss->namedGroupPreferences[i] &&
846
15.4M
            ss->namedGroupPreferences[i]->keaType == keaType) {
847
4.70M
            return PR_TRUE;
848
4.70M
        }
849
21.4M
    }
850
93.7k
    return PR_FALSE;
851
4.79M
}
852
853
static PRBool
854
ssl_KEAEnabled(const sslSocket *ss, SSLKEAType keaType)
855
8.05M
{
856
8.05M
    switch (keaType) {
857
1.68M
        case ssl_kea_rsa:
858
1.68M
            return PR_TRUE;
859
860
2.22M
        case ssl_kea_dh:
861
2.22M
        case ssl_kea_dh_psk: {
862
2.22M
            if (ss->sec.isServer && !ss->opt.enableServerDhe) {
863
0
                return PR_FALSE;
864
0
            }
865
866
2.22M
            if (ss->sec.isServer) {
867
                /* If the server requires named FFDHE groups, then the client
868
                 * must have included an FFDHE group. peerSupportsFfdheGroups
869
                 * is set to true in ssl_HandleSupportedGroupsXtn(). */
870
525k
                if (ss->opt.requireDHENamedGroups &&
871
247k
                    !ss->xtnData.peerSupportsFfdheGroups) {
872
236k
                    return PR_FALSE;
873
236k
                }
874
875
                /* We can use the weak DH group if all of these are true:
876
                 * 1. We don't require named groups.
877
                 * 2. The peer doesn't support named groups.
878
                 * 3. This isn't TLS 1.3.
879
                 * 4. The weak group is enabled. */
880
289k
                if (!ss->opt.requireDHENamedGroups &&
881
277k
                    !ss->xtnData.peerSupportsFfdheGroups &&
882
264k
                    ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
883
263k
                    ss->ssl3.dheWeakGroupEnabled) {
884
0
                    return PR_TRUE;
885
0
                }
886
1.69M
            } else {
887
1.69M
                if (ss->vrange.min < SSL_LIBRARY_VERSION_TLS_1_3 &&
888
1.64M
                    !ss->opt.requireDHENamedGroups) {
889
                    /* The client enables DHE cipher suites even if no DHE groups
890
                     * are enabled. Only if this isn't TLS 1.3 and named groups
891
                     * are not required. */
892
860k
                    return PR_TRUE;
893
860k
                }
894
1.69M
            }
895
1.12M
            return ssl_NamedGroupTypeEnabled(ss, ssl_kea_dh);
896
2.22M
        }
897
898
3.66M
        case ssl_kea_ecdh:
899
3.66M
        case ssl_kea_ecdh_psk:
900
3.66M
            return ssl_NamedGroupTypeEnabled(ss, ssl_kea_ecdh);
901
902
476k
        case ssl_kea_tls13_any:
903
476k
            return PR_TRUE;
904
905
0
        case ssl_kea_fortezza:
906
0
        default:
907
0
            PORT_Assert(0);
908
8.05M
    }
909
0
    return PR_FALSE;
910
8.05M
}
911
912
static PRBool
913
ssl_HasCert(const sslSocket *ss, PRUint16 maxVersion, SSLAuthType authType)
914
7.69M
{
915
7.69M
    PRCList *cursor;
916
7.69M
    if (authType == ssl_auth_null || authType == ssl_auth_psk || authType == ssl_auth_tls13_any) {
917
237k
        return PR_TRUE;
918
237k
    }
919
    /* mldsa is only supported in TLS 1.3 or greater */
920
7.45M
    if (maxVersion < SSL_LIBRARY_VERSION_TLS_1_3 &&
921
3.75M
        (authType == ssl_auth_mldsa44 ||
922
3.75M
         authType == ssl_auth_mldsa65 ||
923
3.75M
         authType == ssl_auth_mldsa87)) {
924
0
        return PR_FALSE;
925
0
    }
926
927
7.45M
    for (cursor = PR_NEXT_LINK(&ss->serverCerts);
928
21.1M
         cursor != &ss->serverCerts;
929
19.8M
         cursor = PR_NEXT_LINK(cursor)) {
930
19.8M
        sslServerCert *cert = (sslServerCert *)cursor;
931
19.8M
        if (!cert->serverKeyPair ||
932
19.8M
            !cert->serverKeyPair->privKey ||
933
19.8M
            !cert->serverCertChain ||
934
19.8M
            !SSL_CERT_IS(cert, authType)) {
935
13.5M
            continue;
936
13.5M
        }
937
        /* When called from ssl3_config_match_init(), all the EC curves will be
938
         * enabled, so this will essentially do nothing (unless we implement
939
         * curve configuration).  However, once we have seen the
940
         * supported_groups extension and this is called from config_match(),
941
         * this will filter out certificates with an unsupported curve.
942
         *
943
         * If we might negotiate TLS 1.3, skip this test as group configuration
944
         * doesn't affect choices in TLS 1.3.
945
         */
946
6.28M
        if (maxVersion < SSL_LIBRARY_VERSION_TLS_1_3 &&
947
3.44M
            (authType == ssl_auth_ecdsa ||
948
2.56M
             authType == ssl_auth_ecdh_ecdsa ||
949
2.23M
             authType == ssl_auth_ecdh_rsa) &&
950
1.21M
            !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
951
135k
            continue;
952
135k
        }
953
6.15M
        return PR_TRUE;
954
6.28M
    }
955
1.30M
    if (authType == ssl_auth_rsa_sign) {
956
0
        return ssl_HasCert(ss, maxVersion, ssl_auth_rsa_pss);
957
0
    }
958
1.30M
    return PR_FALSE;
959
1.30M
}
960
961
/* return true if the scheme is allowed by policy, This prevents
962
 * failures later when our actual signatures are rejected by
963
 * policy by either ssl code, or lower level NSS code */
964
static PRBool
965
ssl_SchemePolicyOK(SSLSignatureScheme scheme, PRUint32 require)
966
3.84M
{
967
    /* Hash policy. */
968
3.84M
    PRUint32 policy;
969
3.84M
    SECOidTag hashOID = ssl3_HashTypeToOID(ssl_SignatureSchemeToHashType(scheme));
970
3.84M
    SECOidTag sigOID;
971
972
    /* policy bits needed to enable a SignatureScheme */
973
3.84M
    SECStatus rv = NSS_GetAlgorithmPolicy(hashOID, &policy);
974
3.84M
    if (rv == SECSuccess &&
975
3.84M
        (policy & require) != require) {
976
0
        return PR_FALSE;
977
0
    }
978
979
    /* ssl_SignatureSchemeToAuthType reports rsa for rsa_pss_rsae, but we
980
     * actually implement pss signatures when we sign, so just use RSA_PSS
981
     * for all RSA PSS Siganture schemes */
982
3.84M
    if (ssl_IsRsaPssSignatureScheme(scheme)) {
983
1.79M
        sigOID = SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
984
2.05M
    } else {
985
2.05M
        sigOID = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme));
986
2.05M
    }
987
    /* Signature Policy. */
988
3.84M
    rv = NSS_GetAlgorithmPolicy(sigOID, &policy);
989
3.84M
    if (rv == SECSuccess &&
990
3.84M
        (policy & require) != require) {
991
0
        return PR_FALSE;
992
0
    }
993
3.84M
    return PR_TRUE;
994
3.84M
}
995
996
/* Check that a signature scheme is accepted.
997
 * Both by policy and by having a token that supports it. */
998
static PRBool
999
ssl_SignatureSchemeAccepted(PRUint16 maxVersion,
1000
                            PRUint16 minVersion,
1001
                            SSLSignatureScheme scheme,
1002
                            PRBool forCert)
1003
4.00M
{
1004
    /* Disable RSA-PSS schemes if there are no tokens to verify them. */
1005
4.00M
    if (ssl_IsRsaPssSignatureScheme(scheme)) {
1006
1.75M
        if (!PK11_TokenExists(auth_alg_defs[ssl_auth_rsa_pss])) {
1007
0
            return PR_FALSE;
1008
0
        }
1009
2.25M
    } else if (ssl_IsMldsaSignatureScheme(scheme)) {
1010
        /* ML-DSA: only in TLS 1.3 and later. */
1011
272k
        if (maxVersion < SSL_LIBRARY_VERSION_TLS_1_3) {
1012
182k
            return PR_FALSE;
1013
182k
        }
1014
90.1k
        if (!PK11_TokenExists(CKM_ML_DSA)) {
1015
0
            return PR_FALSE;
1016
0
        }
1017
1.98M
    } else if (!forCert && ssl_IsRsaPkcs1SignatureScheme(scheme)) {
1018
        /* Disable PKCS#1 signatures if we are limited to TLS 1.3.
1019
         * We still need to advertise PKCS#1 signatures in CH and CR
1020
         * for certificate signatures.
1021
         */
1022
59.9k
        if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_3) {
1023
59.9k
            return PR_FALSE;
1024
59.9k
        }
1025
1.92M
    } else if (ssl_IsDsaSignatureScheme(scheme)) {
1026
        /* DSA: not in TLS 1.3, and check policy. */
1027
376k
        if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_3) {
1028
73.3k
            return PR_FALSE;
1029
73.3k
        }
1030
376k
    }
1031
1032
3.69M
    return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy);
1033
4.00M
}
1034
1035
static SECStatus
1036
ssl_CheckSignatureSchemes(sslSocket *ss)
1037
220k
{
1038
220k
    if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_2) {
1039
47.4k
        return SECSuccess;
1040
47.4k
    }
1041
1042
    /* If this is a server using TLS 1.3, we just need to have one signature
1043
     * scheme for which we have a usable certificate.
1044
     *
1045
     * Note: Certificates for earlier TLS versions are checked along with the
1046
     * cipher suite in ssl3_config_match_init. */
1047
173k
    if (ss->sec.isServer && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
1048
53.9k
        PRBool foundCert = PR_FALSE;
1049
53.9k
        for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
1050
53.9k
            SSLAuthType authType =
1051
53.9k
                ssl_SignatureSchemeToAuthType(ss->ssl3.signatureSchemes[i]);
1052
53.9k
            if (ssl_HasCert(ss, ss->vrange.max, authType)) {
1053
53.9k
                foundCert = PR_TRUE;
1054
53.9k
                break;
1055
53.9k
            }
1056
53.9k
        }
1057
53.9k
        if (!foundCert) {
1058
0
            PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
1059
0
            return SECFailure;
1060
0
        }
1061
53.9k
    }
1062
1063
    /* Ensure that there is a signature scheme that can be accepted.*/
1064
173k
    for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
1065
173k
        if (ssl_SignatureSchemeAccepted(ss->vrange.max, ss->vrange.min,
1066
173k
                                        ss->ssl3.signatureSchemes[i],
1067
173k
                                        PR_FALSE /* forCert */)) {
1068
173k
            return SECSuccess;
1069
173k
        }
1070
173k
    }
1071
0
    PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
1072
0
    return SECFailure;
1073
173k
}
1074
1075
/* For a server, check that a signature scheme that can be used with the
1076
 * provided authType is both enabled and usable. */
1077
static PRBool
1078
ssl_HasSignatureScheme(const sslSocket *ss, SSLAuthType authType)
1079
4.08M
{
1080
4.08M
    PORT_Assert(ss->sec.isServer);
1081
4.08M
    PORT_Assert(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version);
1082
4.08M
    PORT_Assert(authType != ssl_auth_null);
1083
4.08M
    PORT_Assert(authType != ssl_auth_tls13_any);
1084
4.08M
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2 ||
1085
3.67M
        authType == ssl_auth_rsa_decrypt ||
1086
2.54M
        authType == ssl_auth_ecdh_rsa ||
1087
2.54M
        authType == ssl_auth_ecdh_ecdsa) {
1088
1.88M
        return PR_TRUE;
1089
1.88M
    }
1090
8.22M
    for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
1091
8.22M
        SSLSignatureScheme scheme = ss->ssl3.signatureSchemes[i];
1092
8.22M
        SSLAuthType schemeAuthType = ssl_SignatureSchemeToAuthType(scheme);
1093
8.22M
        PRBool acceptable = authType == schemeAuthType ||
1094
6.02M
                            (schemeAuthType == ssl_auth_rsa_pss &&
1095
0
                             authType == ssl_auth_rsa_sign);
1096
8.22M
        if (acceptable && ssl_SignatureSchemeAccepted(ss->version, ss->version,
1097
2.20M
                                                      scheme, PR_FALSE /* forCert */)) {
1098
2.20M
            return PR_TRUE;
1099
2.20M
        }
1100
8.22M
    }
1101
0
    return PR_FALSE;
1102
2.20M
}
1103
1104
/* Initialize the suite->isPresent value for config_match
1105
 * Returns count of enabled ciphers supported by extant tokens,
1106
 * regardless of policy or user preference.
1107
 * If this returns zero, the user cannot do SSL v3.
1108
 */
1109
unsigned int
1110
ssl3_config_match_init(sslSocket *ss)
1111
220k
{
1112
220k
    ssl3CipherSuiteCfg *suite;
1113
220k
    const ssl3CipherSuiteDef *cipher_def;
1114
220k
    SSLCipherAlgorithm cipher_alg;
1115
220k
    CK_MECHANISM_TYPE cipher_mech;
1116
220k
    SSLAuthType authType;
1117
220k
    SSLKEAType keaType;
1118
220k
    unsigned int i;
1119
220k
    unsigned int numPresent = 0;
1120
220k
    unsigned int numEnabled = 0;
1121
1122
220k
    PORT_Assert(ss);
1123
220k
    if (!ss) {
1124
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1125
0
        return 0;
1126
0
    }
1127
220k
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
1128
0
        return 0;
1129
0
    }
1130
220k
    if (ss->sec.isServer && ss->psk &&
1131
39.5k
        PR_CLIST_IS_EMPTY(&ss->serverCerts) &&
1132
0
        (ss->opt.requestCertificate || ss->opt.requireCertificate)) {
1133
        /* PSK and certificate auth cannot be combined. */
1134
0
        PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
1135
0
        return 0;
1136
0
    }
1137
220k
    if (ssl_CheckSignatureSchemes(ss) != SECSuccess) {
1138
0
        return 0; /* Code already set. */
1139
0
    }
1140
1141
220k
    ssl_FilterSupportedGroups(ss);
1142
15.8M
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
1143
15.6M
        suite = &ss->cipherSuites[i];
1144
15.6M
        if (suite->enabled) {
1145
15.4M
            ++numEnabled;
1146
            /* We need the cipher defs to see if we have a token that can handle
1147
             * this cipher.  It isn't part of the static definition.
1148
             */
1149
15.4M
            cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
1150
15.4M
            if (!cipher_def) {
1151
0
                suite->isPresent = PR_FALSE;
1152
0
                continue;
1153
0
            }
1154
15.4M
            cipher_alg = ssl_GetBulkCipherDef(cipher_def)->calg;
1155
15.4M
            cipher_mech = ssl3_Alg2Mech(cipher_alg);
1156
1157
            /* Mark the suites that are backed by real tokens, certs and keys */
1158
15.4M
            suite->isPresent = PR_TRUE;
1159
1160
15.4M
            authType = kea_defs[cipher_def->key_exchange_alg].authKeyType;
1161
15.4M
            if (authType != ssl_auth_null && authType != ssl_auth_tls13_any) {
1162
14.8M
                if (ss->sec.isServer &&
1163
5.38M
                    !(ssl_HasCert(ss, ss->vrange.max, authType) &&
1164
4.08M
                      ssl_HasSignatureScheme(ss, authType))) {
1165
1.30M
                    suite->isPresent = PR_FALSE;
1166
13.5M
                } else if (!PK11_TokenExists(auth_alg_defs[authType])) {
1167
0
                    suite->isPresent = PR_FALSE;
1168
0
                }
1169
14.8M
            }
1170
1171
15.4M
            keaType = kea_defs[cipher_def->key_exchange_alg].exchKeyType;
1172
15.4M
            if (keaType != ssl_kea_null &&
1173
15.4M
                keaType != ssl_kea_tls13_any &&
1174
14.8M
                !PK11_TokenExists(kea_alg_defs[keaType])) {
1175
0
                suite->isPresent = PR_FALSE;
1176
0
            }
1177
1178
15.4M
            if (cipher_alg != ssl_calg_null &&
1179
13.9M
                !PK11_TokenExists(cipher_mech)) {
1180
0
                suite->isPresent = PR_FALSE;
1181
0
            }
1182
1183
15.4M
            if (suite->isPresent) {
1184
14.1M
                ++numPresent;
1185
14.1M
            }
1186
15.4M
        }
1187
15.6M
    }
1188
220k
    PORT_AssertArg(numPresent > 0 || numEnabled == 0);
1189
220k
    if (numPresent == 0) {
1190
0
        PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
1191
0
    }
1192
220k
    return numPresent;
1193
220k
}
1194
1195
/* Return PR_TRUE if suite is usable.  This if the suite is permitted by policy,
1196
 * enabled, has a certificate (as needed), has a viable key agreement method, is
1197
 * usable with the negotiated TLS version, and is otherwise usable. */
1198
PRBool
1199
ssl3_config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy,
1200
                  const SSLVersionRange *vrange, const sslSocket *ss)
1201
8.96M
{
1202
8.96M
    const ssl3CipherSuiteDef *cipher_def;
1203
8.96M
    const ssl3KEADef *kea_def;
1204
1205
8.96M
    if (!suite) {
1206
0
        PORT_Assert(suite);
1207
0
        return PR_FALSE;
1208
0
    }
1209
1210
8.96M
    PORT_Assert(policy != SSL_NOT_ALLOWED);
1211
8.96M
    if (policy == SSL_NOT_ALLOWED)
1212
0
        return PR_FALSE;
1213
1214
8.96M
    if (!suite->enabled || !suite->isPresent)
1215
907k
        return PR_FALSE;
1216
1217
8.05M
    if ((suite->policy == SSL_NOT_ALLOWED) ||
1218
8.05M
        (suite->policy > policy))
1219
0
        return PR_FALSE;
1220
1221
8.05M
    PORT_Assert(ss != NULL);
1222
8.05M
    cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
1223
8.05M
    PORT_Assert(cipher_def != NULL);
1224
8.05M
    kea_def = &kea_defs[cipher_def->key_exchange_alg];
1225
8.05M
    PORT_Assert(kea_def != NULL);
1226
8.05M
    if (!ssl_KEAEnabled(ss, kea_def->exchKeyType)) {
1227
329k
        return PR_FALSE;
1228
329k
    }
1229
1230
7.72M
    if (ss->sec.isServer && !ssl_HasCert(ss, vrange->max, kea_def->authKeyType)) {
1231
4.05k
        return PR_FALSE;
1232
4.05k
    }
1233
1234
    /* If a PSK is selected, disable suites that use a different hash than
1235
     * the PSK. We advertise non-PSK-compatible suites in the CH, as we could
1236
     * fallback to certificate auth. The client handler will check hash
1237
     * compatibility before committing to use the PSK. */
1238
7.72M
    if (ss->xtnData.selectedPsk) {
1239
0
        if (ss->xtnData.selectedPsk->hash != cipher_def->prf_hash) {
1240
0
            return PR_FALSE;
1241
0
        }
1242
0
    }
1243
1244
7.72M
    return ssl3_CipherSuiteAllowedForVersionRange(suite->cipher_suite, vrange);
1245
7.72M
}
1246
1247
/* For TLS 1.3, when resuming, check for a ciphersuite that is both compatible
1248
 * with the identified ciphersuite and enabled. */
1249
static PRBool
1250
tls13_ResumptionCompatible(sslSocket *ss, ssl3CipherSuite suite)
1251
0
{
1252
0
    SSLVersionRange vrange = { SSL_LIBRARY_VERSION_TLS_1_3,
1253
0
                               SSL_LIBRARY_VERSION_TLS_1_3 };
1254
0
    SSLHashType hash = tls13_GetHashForCipherSuite(suite);
1255
0
    for (unsigned int i = 0; i < PR_ARRAY_SIZE(cipher_suite_defs); i++) {
1256
0
        if (cipher_suite_defs[i].prf_hash == hash) {
1257
0
            const ssl3CipherSuiteCfg *suiteCfg =
1258
0
                ssl_LookupCipherSuiteCfg(cipher_suite_defs[i].cipher_suite,
1259
0
                                         ss->cipherSuites);
1260
0
            if (suite && ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) {
1261
0
                return PR_TRUE;
1262
0
            }
1263
0
        }
1264
0
    }
1265
0
    return PR_FALSE;
1266
0
}
1267
1268
/*
1269
 * Null compression, mac and encryption functions
1270
 */
1271
SECStatus
1272
Null_Cipher(void *ctx, unsigned char *output, unsigned int *outputLen, unsigned int maxOutputLen,
1273
            const unsigned char *input, unsigned int inputLen)
1274
3.35M
{
1275
3.35M
    if (inputLen > maxOutputLen) {
1276
0
        *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */
1277
0
        PORT_SetError(SEC_ERROR_OUTPUT_LEN);
1278
0
        return SECFailure;
1279
0
    }
1280
3.35M
    *outputLen = inputLen;
1281
3.35M
    if (inputLen > 0 && input != output) {
1282
2.61M
        PORT_Memcpy(output, input, inputLen);
1283
2.61M
    }
1284
3.35M
    return SECSuccess;
1285
3.35M
}
1286
1287
/* Wrapper around PK11_CipherOp to avoid undefined behavior due to incompatible
1288
 * function pointer type cast
1289
 */
1290
static SECStatus
1291
SSLCipher_PK11_CipherOp(void *ctx, unsigned char *output, unsigned int *outputLen, unsigned int maxOutputLen,
1292
                        const unsigned char *input, unsigned int inputLen)
1293
49.8k
{
1294
49.8k
    PK11Context *pctx = ctx;
1295
49.8k
    PORT_Assert(maxOutputLen <= INT_MAX);
1296
49.8k
    int signedOutputLen = maxOutputLen;
1297
49.8k
    SECStatus rv = PK11_CipherOp(pctx, output, &signedOutputLen, maxOutputLen, input, inputLen);
1298
49.8k
    PORT_Assert(signedOutputLen >= 0);
1299
49.8k
    *outputLen = signedOutputLen;
1300
49.8k
    return rv;
1301
49.8k
}
1302
1303
/*
1304
 * SSL3 Utility functions
1305
 */
1306
1307
static void
1308
ssl_SetSpecVersions(sslSocket *ss, ssl3CipherSpec *spec)
1309
322k
{
1310
322k
    spec->version = ss->version;
1311
322k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
1312
8.05k
        tls13_SetSpecRecordVersion(ss, spec);
1313
314k
    } else if (IS_DTLS(ss)) {
1314
54.7k
        spec->recordVersion = dtls_TLSVersionToDTLSVersion(ss->version);
1315
259k
    } else {
1316
259k
        spec->recordVersion = ss->version;
1317
259k
    }
1318
322k
}
1319
1320
/* allowLargerPeerVersion controls whether the function will select the
1321
 * highest enabled SSL version or fail when peerVersion is greater than the
1322
 * highest enabled version.
1323
 *
1324
 * If allowLargerPeerVersion is true, peerVersion is the peer's highest
1325
 * enabled version rather than the peer's selected version.
1326
 */
1327
SECStatus
1328
ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
1329
                      PRBool allowLargerPeerVersion)
1330
76.4k
{
1331
76.4k
    SSL3ProtocolVersion negotiated;
1332
1333
    /* Prevent negotiating to a lower version in response to a TLS 1.3 HRR. */
1334
76.4k
    if (ss->ssl3.hs.helloRetry) {
1335
14
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
1336
14
        return SECFailure;
1337
14
    }
1338
1339
76.4k
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
1340
0
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
1341
0
        return SECFailure;
1342
0
    }
1343
1344
76.4k
    if (peerVersion < ss->vrange.min ||
1345
76.3k
        (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
1346
34
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
1347
34
        return SECFailure;
1348
34
    }
1349
1350
76.3k
    negotiated = PR_MIN(peerVersion, ss->vrange.max);
1351
76.3k
    PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, negotiated));
1352
76.3k
    if (ss->firstHsDone && ss->version != negotiated) {
1353
1
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
1354
1
        return SECFailure;
1355
1
    }
1356
1357
76.3k
    ss->version = negotiated;
1358
76.3k
    return SECSuccess;
1359
76.3k
}
1360
1361
/* Used by the client when the server produces a version number.
1362
 * This reads, validates, and normalizes the value. */
1363
SECStatus
1364
ssl_ClientReadVersion(sslSocket *ss, PRUint8 **b, unsigned int *len,
1365
                      SSL3ProtocolVersion *version)
1366
68.6k
{
1367
68.6k
    SSL3ProtocolVersion v;
1368
68.6k
    PRUint32 temp;
1369
68.6k
    SECStatus rv;
1370
1371
68.6k
    rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, b, len);
1372
68.6k
    if (rv != SECSuccess) {
1373
30
        return SECFailure; /* alert has been sent */
1374
30
    }
1375
68.6k
    v = (SSL3ProtocolVersion)temp;
1376
1377
68.6k
    if (IS_DTLS(ss)) {
1378
14.2k
        v = dtls_DTLSVersionToTLSVersion(v);
1379
        /* Check for failure. */
1380
14.2k
        if (!v || v > SSL_LIBRARY_VERSION_MAX_SUPPORTED) {
1381
73
            SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
1382
73
            return SECFailure;
1383
73
        }
1384
14.2k
    }
1385
1386
    /* You can't negotiate TLS 1.3 this way. */
1387
68.5k
    if (v >= SSL_LIBRARY_VERSION_TLS_1_3) {
1388
24
        SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
1389
24
        return SECFailure;
1390
24
    }
1391
68.5k
    *version = v;
1392
68.5k
    return SECSuccess;
1393
68.5k
}
1394
1395
SECStatus
1396
ssl3_GetNewRandom(SSL3Random random)
1397
151k
{
1398
151k
    SECStatus rv;
1399
1400
151k
    rv = PK11_GenerateRandom(random, SSL3_RANDOM_LENGTH);
1401
151k
    if (rv != SECSuccess) {
1402
0
        ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
1403
0
    }
1404
151k
    return rv;
1405
151k
}
1406
1407
/* this only implements TLS 1.2 and earlier signatures */
1408
static SECStatus
1409
ssl3_SignHashesWithPrivKey(SSL3Hashes *hash, SECKEYPrivateKey *key,
1410
                           SSLSignatureScheme scheme, PRBool isTls, SECItem *buf)
1411
28.1k
{
1412
28.1k
    SECStatus rv = SECFailure;
1413
28.1k
    PRBool doDerEncode = PR_FALSE;
1414
28.1k
    PRBool useRsaPss = ssl_IsRsaPssSignatureScheme(scheme);
1415
28.1k
    SECItem hashItem;
1416
1417
28.1k
    buf->data = NULL;
1418
1419
28.1k
    switch (SECKEY_GetPrivateKeyType(key)) {
1420
21.2k
        case rsaKey:
1421
21.2k
            hashItem.data = hash->u.raw;
1422
21.2k
            hashItem.len = hash->len;
1423
21.2k
            break;
1424
0
        case dsaKey:
1425
0
            doDerEncode = isTls;
1426
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1427
             * In that case, we use just the SHA1 part. */
1428
0
            if (hash->hashAlg == ssl_hash_none) {
1429
0
                hashItem.data = hash->u.s.sha;
1430
0
                hashItem.len = sizeof(hash->u.s.sha);
1431
0
            } else {
1432
0
                hashItem.data = hash->u.raw;
1433
0
                hashItem.len = hash->len;
1434
0
            }
1435
0
            break;
1436
6.87k
        case ecKey:
1437
6.87k
            doDerEncode = PR_TRUE;
1438
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1439
             * In that case, we use just the SHA1 part. */
1440
6.87k
            if (hash->hashAlg == ssl_hash_none) {
1441
1.25k
                hashItem.data = hash->u.s.sha;
1442
1.25k
                hashItem.len = sizeof(hash->u.s.sha);
1443
5.62k
            } else {
1444
5.62k
                hashItem.data = hash->u.raw;
1445
5.62k
                hashItem.len = hash->len;
1446
5.62k
            }
1447
6.87k
            break;
1448
0
        default:
1449
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
1450
0
            goto done;
1451
28.1k
    }
1452
28.1k
    PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
1453
1454
28.1k
    if (useRsaPss || hash->hashAlg == ssl_hash_none) {
1455
2.81k
        CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1456
2.81k
        int signatureLen = PK11_SignatureLen(key);
1457
2.81k
        PRInt32 optval;
1458
1459
2.81k
        SECItem *params = NULL;
1460
2.81k
        CK_RSA_PKCS_PSS_PARAMS pssParams;
1461
2.81k
        SECItem pssParamsItem = { siBuffer,
1462
2.81k
                                  (unsigned char *)&pssParams,
1463
2.81k
                                  sizeof(pssParams) };
1464
1465
2.81k
        if (signatureLen <= 0) {
1466
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
1467
0
            goto done;
1468
0
        }
1469
        /* since we are calling PK11_SignWithMechanism directly, we need to
1470
         * check the key policy ourselves (which is already checked in
1471
         * SGN_Digest) */
1472
2.81k
        rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS, &optval);
1473
2.81k
        if ((rv == SECSuccess) &&
1474
2.81k
            ((optval & NSS_KEY_SIZE_POLICY_SIGN_FLAG) == NSS_KEY_SIZE_POLICY_SIGN_FLAG)) {
1475
2.81k
            rv = SECKEY_EnforceKeySize(key->keyType, SECKEY_PrivateKeyStrengthInBits(key),
1476
2.81k
                                       SEC_ERROR_SIGNATURE_ALGORITHM_DISABLED);
1477
2.81k
            if (rv != SECSuccess) {
1478
0
                goto done; /* error code already set */
1479
0
            }
1480
2.81k
        }
1481
1482
2.81k
        buf->len = (unsigned)signatureLen;
1483
2.81k
        buf->data = (unsigned char *)PORT_Alloc(signatureLen);
1484
2.81k
        if (!buf->data)
1485
0
            goto done; /* error code was set. */
1486
1487
2.81k
        if (useRsaPss) {
1488
1.00k
            pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1489
1.00k
            pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1490
1.00k
            pssParams.sLen = hashItem.len;
1491
1.00k
            params = &pssParamsItem;
1492
1.00k
            mech = CKM_RSA_PKCS_PSS;
1493
1.00k
        }
1494
1495
2.81k
        rv = PK11_SignWithMechanism(key, mech, params, buf, &hashItem);
1496
25.2k
    } else {
1497
25.2k
        SECOidTag hashOID = ssl3_HashTypeToOID(hash->hashAlg);
1498
25.2k
        rv = SGN_Digest(key, hashOID, buf, &hashItem);
1499
25.2k
    }
1500
28.1k
    if (rv != SECSuccess) {
1501
0
        ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
1502
28.1k
    } else if (doDerEncode) {
1503
6.87k
        SECItem derSig = { siBuffer, NULL, 0 };
1504
1505
        /* This also works for an ECDSA signature */
1506
6.87k
        rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
1507
6.87k
        if (rv == SECSuccess) {
1508
6.87k
            PORT_Free(buf->data); /* discard unencoded signature. */
1509
6.87k
            *buf = derSig;        /* give caller encoded signature. */
1510
6.87k
        } else if (derSig.data) {
1511
0
            PORT_Free(derSig.data);
1512
0
        }
1513
6.87k
    }
1514
1515
28.1k
    PRINT_BUF(60, (NULL, "signed hashes", (unsigned char *)buf->data, buf->len));
1516
28.1k
done:
1517
28.1k
    if (rv != SECSuccess && buf->data) {
1518
0
        PORT_Free(buf->data);
1519
0
        buf->data = NULL;
1520
0
    }
1521
28.1k
    return rv;
1522
28.1k
}
1523
1524
/* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
1525
SECStatus
1526
ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash, SECKEYPrivateKey *key,
1527
                SECItem *buf)
1528
28.1k
{
1529
28.1k
    SECStatus rv = SECFailure;
1530
28.1k
    PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
1531
28.1k
    SSLSignatureScheme scheme = ss->ssl3.hs.signatureScheme;
1532
1533
28.1k
    rv = ssl3_SignHashesWithPrivKey(hash, key, scheme, isTLS, buf);
1534
28.1k
    if (rv != SECSuccess) {
1535
0
        return SECFailure;
1536
0
    }
1537
1538
28.1k
    if (ss->sec.isServer) {
1539
28.1k
        ss->sec.signatureScheme = scheme;
1540
28.1k
        ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
1541
28.1k
    }
1542
1543
28.1k
    return SECSuccess;
1544
28.1k
}
1545
1546
/* Called from ssl3_VerifySignedHashes */
1547
/* this only implements TLS 1.2 and earlier signatures */
1548
static SECStatus
1549
ssl_VerifySignedHashesWithPubKey(sslSocket *ss, SECKEYPublicKey *key,
1550
                                 SSLSignatureScheme scheme,
1551
                                 SSL3Hashes *hash, SECItem *buf)
1552
50.5k
{
1553
50.5k
    SECItem *signature = NULL;
1554
50.5k
    SECStatus rv = SECFailure;
1555
50.5k
    SECItem hashItem;
1556
50.5k
    SECOidTag encAlg;
1557
50.5k
    SECOidTag hashAlg;
1558
50.5k
    void *pwArg = ss->pkcs11PinArg;
1559
50.5k
    PRBool isRsaPssScheme = ssl_IsRsaPssSignatureScheme(scheme);
1560
1561
50.5k
    PRINT_BUF(60, (NULL, "check signed hashes", buf->data, buf->len));
1562
1563
50.5k
    hashAlg = ssl3_HashTypeToOID(hash->hashAlg);
1564
50.5k
    switch (SECKEY_GetPublicKeyType(key)) {
1565
43.5k
        case rsaKey:
1566
43.5k
            encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
1567
43.5k
            hashItem.data = hash->u.raw;
1568
43.5k
            hashItem.len = hash->len;
1569
43.5k
            if (scheme == ssl_sig_none) {
1570
2.71k
                scheme = ssl_sig_rsa_pkcs1_sha1md5;
1571
2.71k
            }
1572
43.5k
            break;
1573
5.12k
        case dsaKey:
1574
5.12k
            encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
1575
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1576
             * In that case, we use just the SHA1 part. */
1577
5.12k
            if (hash->hashAlg == ssl_hash_none) {
1578
14
                hashItem.data = hash->u.s.sha;
1579
14
                hashItem.len = sizeof(hash->u.s.sha);
1580
5.11k
            } else {
1581
5.11k
                hashItem.data = hash->u.raw;
1582
5.11k
                hashItem.len = hash->len;
1583
5.11k
            }
1584
            /* Allow DER encoded DSA signatures in SSL 3.0 */
1585
5.12k
            if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0 ||
1586
5.12k
                buf->len != SECKEY_SignatureLen(key)) {
1587
5.12k
                signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key));
1588
5.12k
                if (!signature) {
1589
20
                    PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1590
20
                    goto loser;
1591
20
                }
1592
5.10k
                buf = signature;
1593
5.10k
            }
1594
5.10k
            if (scheme == ssl_sig_none) {
1595
6
                scheme = ssl_sig_dsa_sha1;
1596
6
            }
1597
5.10k
            break;
1598
1599
1.87k
        case ecKey:
1600
1.87k
            encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
1601
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1602
             * In that case, we use just the SHA1 part.
1603
             * ECDSA signatures always encode the integers r and s using ASN.1
1604
             * (unlike DSA where ASN.1 encoding is used with TLS but not with
1605
             * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
1606
             */
1607
1.87k
            if (hash->hashAlg == ssl_hash_none) {
1608
262
                hashAlg = SEC_OID_SHA1;
1609
262
                hashItem.data = hash->u.s.sha;
1610
262
                hashItem.len = sizeof(hash->u.s.sha);
1611
1.60k
            } else {
1612
1.60k
                hashItem.data = hash->u.raw;
1613
1.60k
                hashItem.len = hash->len;
1614
1.60k
            }
1615
1.87k
            if (scheme == ssl_sig_none) {
1616
262
                scheme = ssl_sig_ecdsa_sha1;
1617
262
            }
1618
1.87k
            break;
1619
1620
8
        default:
1621
8
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
1622
8
            goto loser;
1623
50.5k
    }
1624
1625
50.5k
    PRINT_BUF(60, (NULL, "hash(es) to be verified",
1626
50.5k
                   hashItem.data, hashItem.len));
1627
1628
50.5k
    if (isRsaPssScheme ||
1629
45.4k
        hashAlg == SEC_OID_UNKNOWN ||
1630
42.7k
        SECKEY_GetPublicKeyType(key) == dsaKey) {
1631
        /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1632
         * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1633
         * above always removes the DER encoding of DSA signatures when
1634
         * present. Thus DSA signatures are always verified with PK11_Verify.
1635
         */
1636
12.8k
        CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1637
1638
12.8k
        SECItem *params = NULL;
1639
12.8k
        CK_RSA_PKCS_PSS_PARAMS pssParams;
1640
12.8k
        SECItem pssParamsItem = { siBuffer,
1641
12.8k
                                  (unsigned char *)&pssParams,
1642
12.8k
                                  sizeof(pssParams) };
1643
1644
12.8k
        if (isRsaPssScheme) {
1645
5.03k
            pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1646
5.03k
            pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1647
5.03k
            pssParams.sLen = hashItem.len;
1648
5.03k
            params = &pssParamsItem;
1649
5.03k
            mech = CKM_RSA_PKCS_PSS;
1650
5.03k
        }
1651
1652
12.8k
        rv = PK11_VerifyWithMechanism(key, mech, params, buf, &hashItem, pwArg);
1653
37.6k
    } else {
1654
37.6k
        rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
1655
37.6k
                                    pwArg);
1656
37.6k
    }
1657
50.5k
    if (signature) {
1658
5.10k
        SECITEM_FreeItem(signature, PR_TRUE);
1659
5.10k
    }
1660
50.5k
    if (rv != SECSuccess) {
1661
50.3k
        ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1662
50.3k
    }
1663
50.5k
    if (!ss->sec.isServer) {
1664
13.6k
        ss->sec.signatureScheme = scheme;
1665
13.6k
        ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
1666
13.6k
    }
1667
1668
50.5k
loser:
1669
#ifdef UNSAFE_FUZZER_MODE
1670
    rv = SECSuccess;
1671
25.2k
    PORT_SetError(0);
1672
#endif
1673
50.5k
    return rv;
1674
50.5k
}
ssl3con.c:ssl_VerifySignedHashesWithPubKey
Line
Count
Source
1552
25.2k
{
1553
25.2k
    SECItem *signature = NULL;
1554
25.2k
    SECStatus rv = SECFailure;
1555
25.2k
    SECItem hashItem;
1556
25.2k
    SECOidTag encAlg;
1557
25.2k
    SECOidTag hashAlg;
1558
25.2k
    void *pwArg = ss->pkcs11PinArg;
1559
25.2k
    PRBool isRsaPssScheme = ssl_IsRsaPssSignatureScheme(scheme);
1560
1561
25.2k
    PRINT_BUF(60, (NULL, "check signed hashes", buf->data, buf->len));
1562
1563
25.2k
    hashAlg = ssl3_HashTypeToOID(hash->hashAlg);
1564
25.2k
    switch (SECKEY_GetPublicKeyType(key)) {
1565
21.7k
        case rsaKey:
1566
21.7k
            encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
1567
21.7k
            hashItem.data = hash->u.raw;
1568
21.7k
            hashItem.len = hash->len;
1569
21.7k
            if (scheme == ssl_sig_none) {
1570
1.35k
                scheme = ssl_sig_rsa_pkcs1_sha1md5;
1571
1.35k
            }
1572
21.7k
            break;
1573
2.56k
        case dsaKey:
1574
2.56k
            encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
1575
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1576
             * In that case, we use just the SHA1 part. */
1577
2.56k
            if (hash->hashAlg == ssl_hash_none) {
1578
7
                hashItem.data = hash->u.s.sha;
1579
7
                hashItem.len = sizeof(hash->u.s.sha);
1580
2.55k
            } else {
1581
2.55k
                hashItem.data = hash->u.raw;
1582
2.55k
                hashItem.len = hash->len;
1583
2.55k
            }
1584
            /* Allow DER encoded DSA signatures in SSL 3.0 */
1585
2.56k
            if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0 ||
1586
2.56k
                buf->len != SECKEY_SignatureLen(key)) {
1587
2.56k
                signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key));
1588
2.56k
                if (!signature) {
1589
10
                    PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1590
10
                    goto loser;
1591
10
                }
1592
2.55k
                buf = signature;
1593
2.55k
            }
1594
2.55k
            if (scheme == ssl_sig_none) {
1595
3
                scheme = ssl_sig_dsa_sha1;
1596
3
            }
1597
2.55k
            break;
1598
1599
935
        case ecKey:
1600
935
            encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
1601
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1602
             * In that case, we use just the SHA1 part.
1603
             * ECDSA signatures always encode the integers r and s using ASN.1
1604
             * (unlike DSA where ASN.1 encoding is used with TLS but not with
1605
             * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
1606
             */
1607
935
            if (hash->hashAlg == ssl_hash_none) {
1608
131
                hashAlg = SEC_OID_SHA1;
1609
131
                hashItem.data = hash->u.s.sha;
1610
131
                hashItem.len = sizeof(hash->u.s.sha);
1611
804
            } else {
1612
804
                hashItem.data = hash->u.raw;
1613
804
                hashItem.len = hash->len;
1614
804
            }
1615
935
            if (scheme == ssl_sig_none) {
1616
131
                scheme = ssl_sig_ecdsa_sha1;
1617
131
            }
1618
935
            break;
1619
1620
4
        default:
1621
4
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
1622
4
            goto loser;
1623
25.2k
    }
1624
1625
25.2k
    PRINT_BUF(60, (NULL, "hash(es) to be verified",
1626
25.2k
                   hashItem.data, hashItem.len));
1627
1628
25.2k
    if (isRsaPssScheme ||
1629
22.7k
        hashAlg == SEC_OID_UNKNOWN ||
1630
21.3k
        SECKEY_GetPublicKeyType(key) == dsaKey) {
1631
        /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1632
         * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1633
         * above always removes the DER encoding of DSA signatures when
1634
         * present. Thus DSA signatures are always verified with PK11_Verify.
1635
         */
1636
6.42k
        CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1637
1638
6.42k
        SECItem *params = NULL;
1639
6.42k
        CK_RSA_PKCS_PSS_PARAMS pssParams;
1640
6.42k
        SECItem pssParamsItem = { siBuffer,
1641
6.42k
                                  (unsigned char *)&pssParams,
1642
6.42k
                                  sizeof(pssParams) };
1643
1644
6.42k
        if (isRsaPssScheme) {
1645
2.51k
            pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1646
2.51k
            pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1647
2.51k
            pssParams.sLen = hashItem.len;
1648
2.51k
            params = &pssParamsItem;
1649
2.51k
            mech = CKM_RSA_PKCS_PSS;
1650
2.51k
        }
1651
1652
6.42k
        rv = PK11_VerifyWithMechanism(key, mech, params, buf, &hashItem, pwArg);
1653
18.8k
    } else {
1654
18.8k
        rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
1655
18.8k
                                    pwArg);
1656
18.8k
    }
1657
25.2k
    if (signature) {
1658
2.55k
        SECITEM_FreeItem(signature, PR_TRUE);
1659
2.55k
    }
1660
25.2k
    if (rv != SECSuccess) {
1661
25.1k
        ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1662
25.1k
    }
1663
25.2k
    if (!ss->sec.isServer) {
1664
6.80k
        ss->sec.signatureScheme = scheme;
1665
6.80k
        ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
1666
6.80k
    }
1667
1668
25.2k
loser:
1669
25.2k
#ifdef UNSAFE_FUZZER_MODE
1670
25.2k
    rv = SECSuccess;
1671
25.2k
    PORT_SetError(0);
1672
25.2k
#endif
1673
25.2k
    return rv;
1674
25.2k
}
ssl3con.c:ssl_VerifySignedHashesWithPubKey
Line
Count
Source
1552
25.2k
{
1553
25.2k
    SECItem *signature = NULL;
1554
25.2k
    SECStatus rv = SECFailure;
1555
25.2k
    SECItem hashItem;
1556
25.2k
    SECOidTag encAlg;
1557
25.2k
    SECOidTag hashAlg;
1558
25.2k
    void *pwArg = ss->pkcs11PinArg;
1559
25.2k
    PRBool isRsaPssScheme = ssl_IsRsaPssSignatureScheme(scheme);
1560
1561
25.2k
    PRINT_BUF(60, (NULL, "check signed hashes", buf->data, buf->len));
1562
1563
25.2k
    hashAlg = ssl3_HashTypeToOID(hash->hashAlg);
1564
25.2k
    switch (SECKEY_GetPublicKeyType(key)) {
1565
21.7k
        case rsaKey:
1566
21.7k
            encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
1567
21.7k
            hashItem.data = hash->u.raw;
1568
21.7k
            hashItem.len = hash->len;
1569
21.7k
            if (scheme == ssl_sig_none) {
1570
1.35k
                scheme = ssl_sig_rsa_pkcs1_sha1md5;
1571
1.35k
            }
1572
21.7k
            break;
1573
2.56k
        case dsaKey:
1574
2.56k
            encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
1575
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1576
             * In that case, we use just the SHA1 part. */
1577
2.56k
            if (hash->hashAlg == ssl_hash_none) {
1578
7
                hashItem.data = hash->u.s.sha;
1579
7
                hashItem.len = sizeof(hash->u.s.sha);
1580
2.55k
            } else {
1581
2.55k
                hashItem.data = hash->u.raw;
1582
2.55k
                hashItem.len = hash->len;
1583
2.55k
            }
1584
            /* Allow DER encoded DSA signatures in SSL 3.0 */
1585
2.56k
            if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0 ||
1586
2.56k
                buf->len != SECKEY_SignatureLen(key)) {
1587
2.56k
                signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key));
1588
2.56k
                if (!signature) {
1589
10
                    PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1590
10
                    goto loser;
1591
10
                }
1592
2.55k
                buf = signature;
1593
2.55k
            }
1594
2.55k
            if (scheme == ssl_sig_none) {
1595
3
                scheme = ssl_sig_dsa_sha1;
1596
3
            }
1597
2.55k
            break;
1598
1599
935
        case ecKey:
1600
935
            encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
1601
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1602
             * In that case, we use just the SHA1 part.
1603
             * ECDSA signatures always encode the integers r and s using ASN.1
1604
             * (unlike DSA where ASN.1 encoding is used with TLS but not with
1605
             * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
1606
             */
1607
935
            if (hash->hashAlg == ssl_hash_none) {
1608
131
                hashAlg = SEC_OID_SHA1;
1609
131
                hashItem.data = hash->u.s.sha;
1610
131
                hashItem.len = sizeof(hash->u.s.sha);
1611
804
            } else {
1612
804
                hashItem.data = hash->u.raw;
1613
804
                hashItem.len = hash->len;
1614
804
            }
1615
935
            if (scheme == ssl_sig_none) {
1616
131
                scheme = ssl_sig_ecdsa_sha1;
1617
131
            }
1618
935
            break;
1619
1620
4
        default:
1621
4
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
1622
4
            goto loser;
1623
25.2k
    }
1624
1625
25.2k
    PRINT_BUF(60, (NULL, "hash(es) to be verified",
1626
25.2k
                   hashItem.data, hashItem.len));
1627
1628
25.2k
    if (isRsaPssScheme ||
1629
22.7k
        hashAlg == SEC_OID_UNKNOWN ||
1630
21.3k
        SECKEY_GetPublicKeyType(key) == dsaKey) {
1631
        /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1632
         * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1633
         * above always removes the DER encoding of DSA signatures when
1634
         * present. Thus DSA signatures are always verified with PK11_Verify.
1635
         */
1636
6.42k
        CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1637
1638
6.42k
        SECItem *params = NULL;
1639
6.42k
        CK_RSA_PKCS_PSS_PARAMS pssParams;
1640
6.42k
        SECItem pssParamsItem = { siBuffer,
1641
6.42k
                                  (unsigned char *)&pssParams,
1642
6.42k
                                  sizeof(pssParams) };
1643
1644
6.42k
        if (isRsaPssScheme) {
1645
2.51k
            pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1646
2.51k
            pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1647
2.51k
            pssParams.sLen = hashItem.len;
1648
2.51k
            params = &pssParamsItem;
1649
2.51k
            mech = CKM_RSA_PKCS_PSS;
1650
2.51k
        }
1651
1652
6.42k
        rv = PK11_VerifyWithMechanism(key, mech, params, buf, &hashItem, pwArg);
1653
18.8k
    } else {
1654
18.8k
        rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
1655
18.8k
                                    pwArg);
1656
18.8k
    }
1657
25.2k
    if (signature) {
1658
2.55k
        SECITEM_FreeItem(signature, PR_TRUE);
1659
2.55k
    }
1660
25.2k
    if (rv != SECSuccess) {
1661
25.1k
        ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1662
25.1k
    }
1663
25.2k
    if (!ss->sec.isServer) {
1664
6.80k
        ss->sec.signatureScheme = scheme;
1665
6.80k
        ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
1666
6.80k
    }
1667
1668
25.2k
loser:
1669
#ifdef UNSAFE_FUZZER_MODE
1670
    rv = SECSuccess;
1671
    PORT_SetError(0);
1672
#endif
1673
25.2k
    return rv;
1674
25.2k
}
1675
1676
/* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
1677
SECStatus
1678
ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme, SSL3Hashes *hash,
1679
                        SECItem *buf)
1680
25.2k
{
1681
25.2k
    SECKEYPublicKey *pubKey = SECKEY_ExtractPublicKey(ss->sec.peerCertSPKI);
1682
25.2k
    if (pubKey == NULL) {
1683
0
        ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
1684
0
        return SECFailure;
1685
0
    }
1686
25.2k
    SECStatus rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, scheme,
1687
25.2k
                                                    hash, buf);
1688
25.2k
    SECKEY_DestroyPublicKey(pubKey);
1689
25.2k
    return rv;
1690
25.2k
}
1691
1692
/* Caller must set hiLevel error code. */
1693
/* Called from ssl3_ComputeDHKeyHash
1694
 * which are called from ssl3_HandleServerKeyExchange.
1695
 *
1696
 * hashAlg: ssl_hash_none indicates the pre-1.2, MD5/SHA1 combination hash.
1697
 */
1698
SECStatus
1699
ssl3_ComputeCommonKeyHash(SSLHashType hashAlg,
1700
                          PRUint8 *hashBuf, unsigned int bufLen,
1701
                          SSL3Hashes *hashes)
1702
34.9k
{
1703
34.9k
    SECStatus rv;
1704
34.9k
    SECOidTag hashOID;
1705
34.9k
    PRUint32 policy;
1706
1707
34.9k
    if (hashAlg == ssl_hash_none) {
1708
2.93k
        if ((NSS_GetAlgorithmPolicy(SEC_OID_SHA1, &policy) == SECSuccess) &&
1709
2.93k
            !(policy & NSS_USE_ALG_IN_SSL_KX)) {
1710
0
            ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1711
0
            return SECFailure;
1712
0
        }
1713
2.93k
        rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen);
1714
2.93k
        if (rv != SECSuccess) {
1715
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
1716
0
            return rv;
1717
0
        }
1718
2.93k
        rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen);
1719
2.93k
        if (rv != SECSuccess) {
1720
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
1721
0
            return rv;
1722
0
        }
1723
2.93k
        hashes->len = MD5_LENGTH + SHA1_LENGTH;
1724
31.9k
    } else {
1725
31.9k
        hashOID = ssl3_HashTypeToOID(hashAlg);
1726
31.9k
        if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) &&
1727
31.9k
            !(policy & NSS_USE_ALG_IN_SSL_KX)) {
1728
0
            ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1729
0
            return SECFailure;
1730
0
        }
1731
31.9k
        hashes->len = HASH_ResultLenByOidTag(hashOID);
1732
31.9k
        if (hashes->len == 0 || hashes->len > sizeof(hashes->u.raw)) {
1733
0
            ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1734
0
            return SECFailure;
1735
0
        }
1736
31.9k
        rv = PK11_HashBuf(hashOID, hashes->u.raw, hashBuf, bufLen);
1737
31.9k
        if (rv != SECSuccess) {
1738
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
1739
0
            return rv;
1740
0
        }
1741
31.9k
    }
1742
34.9k
    hashes->hashAlg = hashAlg;
1743
34.9k
    return SECSuccess;
1744
34.9k
}
1745
1746
/* Caller must set hiLevel error code. */
1747
/* Called from ssl3_HandleServerKeyExchange. */
1748
static SECStatus
1749
ssl3_ComputeDHKeyHash(sslSocket *ss, SSLHashType hashAlg, SSL3Hashes *hashes,
1750
                      SECItem dh_p, SECItem dh_g, SECItem dh_Ys, PRBool padY)
1751
6.23k
{
1752
6.23k
    sslBuffer buf = SSL_BUFFER_EMPTY;
1753
6.23k
    SECStatus rv;
1754
6.23k
    unsigned int yLen;
1755
6.23k
    unsigned int i;
1756
1757
6.23k
    PORT_Assert(dh_p.data);
1758
6.23k
    PORT_Assert(dh_g.data);
1759
6.23k
    PORT_Assert(dh_Ys.data);
1760
1761
6.23k
    rv = sslBuffer_Append(&buf, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
1762
6.23k
    if (rv != SECSuccess) {
1763
0
        goto loser;
1764
0
    }
1765
6.23k
    rv = sslBuffer_Append(&buf, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
1766
6.23k
    if (rv != SECSuccess) {
1767
0
        goto loser;
1768
0
    }
1769
    /* p */
1770
6.23k
    rv = sslBuffer_AppendVariable(&buf, dh_p.data, dh_p.len, 2);
1771
6.23k
    if (rv != SECSuccess) {
1772
0
        goto loser;
1773
0
    }
1774
    /* g */
1775
6.23k
    rv = sslBuffer_AppendVariable(&buf, dh_g.data, dh_g.len, 2);
1776
6.23k
    if (rv != SECSuccess) {
1777
0
        goto loser;
1778
0
    }
1779
    /* y - complicated by padding */
1780
6.23k
    yLen = padY ? dh_p.len : dh_Ys.len;
1781
6.23k
    rv = sslBuffer_AppendNumber(&buf, yLen, 2);
1782
6.23k
    if (rv != SECSuccess) {
1783
0
        goto loser;
1784
0
    }
1785
    /* If we're padding Y, dh_Ys can't be longer than dh_p. */
1786
6.23k
    PORT_Assert(!padY || dh_p.len >= dh_Ys.len);
1787
6.23k
    for (i = dh_Ys.len; i < yLen; ++i) {
1788
0
        rv = sslBuffer_AppendNumber(&buf, 0, 1);
1789
0
        if (rv != SECSuccess) {
1790
0
            goto loser;
1791
0
        }
1792
0
    }
1793
6.23k
    rv = sslBuffer_Append(&buf, dh_Ys.data, dh_Ys.len);
1794
6.23k
    if (rv != SECSuccess) {
1795
0
        goto loser;
1796
0
    }
1797
1798
6.23k
    rv = ssl3_ComputeCommonKeyHash(hashAlg, SSL_BUFFER_BASE(&buf),
1799
6.23k
                                   SSL_BUFFER_LEN(&buf), hashes);
1800
6.23k
    if (rv != SECSuccess) {
1801
0
        goto loser;
1802
0
    }
1803
1804
6.23k
    PRINT_BUF(95, (NULL, "DHkey hash: ", SSL_BUFFER_BASE(&buf),
1805
6.23k
                   SSL_BUFFER_LEN(&buf)));
1806
6.23k
    if (hashAlg == ssl_hash_none) {
1807
423
        PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",
1808
423
                       hashes->u.s.md5, MD5_LENGTH));
1809
423
        PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",
1810
423
                       hashes->u.s.sha, SHA1_LENGTH));
1811
5.81k
    } else {
1812
5.81k
        PRINT_BUF(95, (NULL, "DHkey hash: result",
1813
5.81k
                       hashes->u.raw, hashes->len));
1814
5.81k
    }
1815
1816
6.23k
    sslBuffer_Clear(&buf);
1817
6.23k
    return SECSuccess;
1818
1819
0
loser:
1820
0
    sslBuffer_Clear(&buf);
1821
0
    return SECFailure;
1822
6.23k
}
1823
1824
static SECStatus
1825
ssl3_SetupPendingCipherSpec(sslSocket *ss, SSLSecretDirection direction,
1826
                            const ssl3CipherSuiteDef *suiteDef,
1827
                            ssl3CipherSpec **specp)
1828
271k
{
1829
271k
    ssl3CipherSpec *spec;
1830
271k
    const ssl3CipherSpec *prev;
1831
1832
271k
    prev = (direction == ssl_secret_write) ? ss->ssl3.cwSpec : ss->ssl3.crSpec;
1833
271k
    if (prev->epoch == PR_UINT16_MAX) {
1834
0
        PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
1835
0
        return SECFailure;
1836
0
    }
1837
1838
271k
    spec = ssl_CreateCipherSpec(ss, direction);
1839
271k
    if (!spec) {
1840
0
        return SECFailure;
1841
0
    }
1842
1843
271k
    spec->cipherDef = ssl_GetBulkCipherDef(suiteDef);
1844
271k
    spec->macDef = ssl_GetMacDef(ss, suiteDef);
1845
1846
271k
    spec->epoch = prev->epoch + 1;
1847
271k
    spec->nextSeqNum = 0;
1848
271k
    if (IS_DTLS(ss) && direction == ssl_secret_read) {
1849
17.9k
        dtls_InitRecvdRecords(&spec->recvdRecords);
1850
17.9k
    }
1851
271k
    ssl_SetSpecVersions(ss, spec);
1852
1853
271k
    ssl_SaveCipherSpec(ss, spec);
1854
271k
    *specp = spec;
1855
271k
    return SECSuccess;
1856
271k
}
1857
1858
/* Fill in the pending cipher spec with info from the selected ciphersuite.
1859
** This is as much initialization as we can do without having key material.
1860
** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1861
** Caller must hold the ssl3 handshake lock.
1862
** Acquires & releases SpecWriteLock.
1863
*/
1864
SECStatus
1865
ssl3_SetupBothPendingCipherSpecs(sslSocket *ss)
1866
135k
{
1867
135k
    ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
1868
135k
    SSL3KeyExchangeAlgorithm kea;
1869
135k
    const ssl3CipherSuiteDef *suiteDef;
1870
135k
    SECStatus rv;
1871
1872
135k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1873
135k
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
1874
1875
135k
    ssl_GetSpecWriteLock(ss); /*******************************/
1876
1877
    /* This hack provides maximal interoperability with SSL 3 servers. */
1878
135k
    if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
1879
        /* SSL records are not being MACed. */
1880
41.5k
        ss->ssl3.cwSpec->version = ss->version;
1881
41.5k
    }
1882
1883
135k
    SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1884
135k
                SSL_GETPID(), ss->fd, suite));
1885
1886
135k
    suiteDef = ssl_LookupCipherSuiteDef(suite);
1887
135k
    if (suiteDef == NULL) {
1888
0
        goto loser;
1889
0
    }
1890
1891
135k
    if (IS_DTLS(ss)) {
1892
        /* Double-check that we did not pick an RC4 suite */
1893
17.9k
        PORT_Assert(suiteDef->bulk_cipher_alg != cipher_rc4);
1894
17.9k
    }
1895
1896
135k
    ss->ssl3.hs.suite_def = suiteDef;
1897
1898
135k
    kea = suiteDef->key_exchange_alg;
1899
135k
    ss->ssl3.hs.kea_def = &kea_defs[kea];
1900
135k
    PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
1901
1902
135k
    rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_read, suiteDef,
1903
135k
                                     &ss->ssl3.prSpec);
1904
135k
    if (rv != SECSuccess) {
1905
0
        goto loser;
1906
0
    }
1907
135k
    rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_write, suiteDef,
1908
135k
                                     &ss->ssl3.pwSpec);
1909
135k
    if (rv != SECSuccess) {
1910
0
        goto loser;
1911
0
    }
1912
1913
135k
    if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) {
1914
3.14k
        ss->ssl3.prSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,
1915
3.14k
                                                  ss->opt.recordSizeLimit);
1916
3.14k
        ss->ssl3.pwSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,
1917
3.14k
                                                  ss->xtnData.recordSizeLimit);
1918
3.14k
    }
1919
1920
135k
    ssl_ReleaseSpecWriteLock(ss); /*******************************/
1921
135k
    return SECSuccess;
1922
1923
0
loser:
1924
0
    ssl_ReleaseSpecWriteLock(ss);
1925
0
    return SECFailure;
1926
135k
}
1927
1928
/* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data which
1929
 * is included in the MAC or AEAD additional data) to |buf|. See
1930
 * https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the definition of the
1931
 * AEAD additional data.
1932
 *
1933
 * TLS pseudo-header includes the record's version field, SSL's doesn't. Which
1934
 * pseudo-header definition to use should be decided based on the version of
1935
 * the protocol that was negotiated when the cipher spec became current, NOT
1936
 * based on the version value in the record itself, and the decision is passed
1937
 * to this function as the |includesVersion| argument. But, the |version|
1938
 * argument should be the record's version value.
1939
 */
1940
static SECStatus
1941
ssl3_BuildRecordPseudoHeader(DTLSEpoch epoch,
1942
                             sslSequenceNumber seqNum,
1943
                             SSLContentType ct,
1944
                             PRBool includesVersion,
1945
                             SSL3ProtocolVersion version,
1946
                             PRBool isDTLS,
1947
                             int length,
1948
                             sslBuffer *buf, SSL3ProtocolVersion v)
1949
204k
{
1950
204k
    SECStatus rv;
1951
204k
    if (isDTLS && v < SSL_LIBRARY_VERSION_TLS_1_3) {
1952
114k
        rv = sslBuffer_AppendNumber(buf, epoch, 2);
1953
114k
        if (rv != SECSuccess) {
1954
0
            return SECFailure;
1955
0
        }
1956
114k
        rv = sslBuffer_AppendNumber(buf, seqNum, 6);
1957
114k
    } else {
1958
90.0k
        rv = sslBuffer_AppendNumber(buf, seqNum, 8);
1959
90.0k
    }
1960
204k
    if (rv != SECSuccess) {
1961
0
        return SECFailure;
1962
0
    }
1963
204k
    rv = sslBuffer_AppendNumber(buf, ct, 1);
1964
204k
    if (rv != SECSuccess) {
1965
0
        return SECFailure;
1966
0
    }
1967
1968
    /* SSL3 MAC doesn't include the record's version field. */
1969
204k
    if (includesVersion) {
1970
        /* TLS MAC and AEAD additional data include version. */
1971
204k
        rv = sslBuffer_AppendNumber(buf, version, 2);
1972
204k
        if (rv != SECSuccess) {
1973
0
            return SECFailure;
1974
0
        }
1975
204k
    }
1976
204k
    rv = sslBuffer_AppendNumber(buf, length, 2);
1977
204k
    if (rv != SECSuccess) {
1978
0
        return SECFailure;
1979
0
    }
1980
1981
204k
    return SECSuccess;
1982
204k
}
1983
1984
/* Initialize encryption and MAC contexts for pending spec.
1985
 * Master Secret already is derived.
1986
 * Caller holds Spec write lock.
1987
 */
1988
static SECStatus
1989
ssl3_InitPendingContexts(sslSocket *ss, ssl3CipherSpec *spec)
1990
225k
{
1991
225k
    CK_MECHANISM_TYPE encMechanism;
1992
225k
    CK_ATTRIBUTE_TYPE encMode;
1993
225k
    SECItem macParam;
1994
225k
    CK_ULONG macLength;
1995
225k
    SECItem iv;
1996
225k
    SSLCipherAlgorithm calg;
1997
1998
225k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1999
225k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
2000
2001
225k
    calg = spec->cipherDef->calg;
2002
225k
    PORT_Assert(alg2Mech[calg].calg == calg);
2003
2004
225k
    if (spec->cipherDef->type != type_aead) {
2005
204k
        macLength = spec->macDef->mac_size;
2006
2007
        /*
2008
        ** Now setup the MAC contexts,
2009
        **   crypto contexts are setup below.
2010
        */
2011
204k
        macParam.data = (unsigned char *)&macLength;
2012
204k
        macParam.len = sizeof(macLength);
2013
204k
        macParam.type = siBuffer;
2014
2015
204k
        spec->keyMaterial.macContext = PK11_CreateContextBySymKey(
2016
204k
            spec->macDef->mmech, CKA_SIGN, spec->keyMaterial.macKey, &macParam);
2017
204k
        if (!spec->keyMaterial.macContext) {
2018
0
            ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2019
0
            return SECFailure;
2020
0
        }
2021
204k
    }
2022
2023
    /*
2024
    ** Now setup the crypto contexts.
2025
    */
2026
225k
    if (calg == ssl_calg_null) {
2027
30.5k
        spec->cipher = Null_Cipher;
2028
30.5k
        return SECSuccess;
2029
30.5k
    }
2030
2031
195k
    encMechanism = ssl3_Alg2Mech(calg);
2032
195k
    encMode = (spec->direction == ssl_secret_write) ? CKA_ENCRYPT : CKA_DECRYPT;
2033
195k
    if (spec->cipherDef->type == type_aead) {
2034
21.3k
        encMode |= CKA_NSS_MESSAGE;
2035
21.3k
        iv.data = NULL;
2036
21.3k
        iv.len = 0;
2037
174k
    } else {
2038
174k
        spec->cipher = SSLCipher_PK11_CipherOp;
2039
174k
        iv.data = spec->keyMaterial.iv;
2040
174k
        iv.len = spec->cipherDef->iv_size;
2041
174k
    }
2042
2043
    /*
2044
     * build the context
2045
     */
2046
195k
    spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode,
2047
195k
                                                     spec->keyMaterial.key,
2048
195k
                                                     &iv);
2049
195k
    if (!spec->cipherContext) {
2050
0
        ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2051
0
        return SECFailure;
2052
0
    }
2053
2054
195k
    return SECSuccess;
2055
195k
}
2056
2057
/* Complete the initialization of all keys, ciphers, MACs and their contexts
2058
 * for the pending Cipher Spec.
2059
 * Called from: ssl3_SendClientKeyExchange  (for Full handshake)
2060
 *              ssl3_HandleRSAClientKeyExchange (for Full handshake)
2061
 *              ssl3_HandleServerHello      (for session restart)
2062
 *              ssl3_HandleClientHello      (for session restart)
2063
 * Sets error code, but caller probably should override to disambiguate.
2064
 *
2065
 * If |secret| is a master secret from a previous connection is reused, |derive|
2066
 * is PR_FALSE.  If the secret is a pre-master secret, then |derive| is PR_TRUE
2067
 * and the master secret is derived from |secret|.
2068
 */
2069
SECStatus
2070
ssl3_InitPendingCipherSpecs(sslSocket *ss, PK11SymKey *secret, PRBool derive)
2071
113k
{
2072
113k
    PK11SymKey *masterSecret;
2073
113k
    ssl3CipherSpec *pwSpec;
2074
113k
    ssl3CipherSpec *prSpec;
2075
113k
    SECStatus rv;
2076
2077
113k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2078
113k
    PORT_Assert(secret);
2079
2080
113k
    ssl_GetSpecWriteLock(ss); /**************************************/
2081
2082
113k
    PORT_Assert(ss->ssl3.pwSpec);
2083
113k
    PORT_Assert(ss->ssl3.cwSpec->epoch == ss->ssl3.crSpec->epoch);
2084
113k
    prSpec = ss->ssl3.prSpec;
2085
113k
    pwSpec = ss->ssl3.pwSpec;
2086
2087
113k
    if (ss->ssl3.cwSpec->epoch == PR_UINT16_MAX) {
2088
        /* The problem here is that we have rehandshaked too many
2089
         * times (you are not allowed to wrap the epoch). The
2090
         * spec says you should be discarding the connection
2091
         * and start over, so not much we can do here. */
2092
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2093
0
        goto loser;
2094
0
    }
2095
2096
113k
    if (derive) {
2097
113k
        rv = ssl3_ComputeMasterSecret(ss, secret, &masterSecret);
2098
113k
        if (rv != SECSuccess) {
2099
202
            goto loser;
2100
202
        }
2101
113k
    } else {
2102
0
        masterSecret = secret;
2103
0
    }
2104
2105
112k
    PORT_Assert(masterSecret);
2106
112k
    rv = ssl3_DeriveConnectionKeys(ss, masterSecret);
2107
112k
    if (rv != SECSuccess) {
2108
0
        if (derive) {
2109
            /* masterSecret was created here. */
2110
0
            PK11_FreeSymKey(masterSecret);
2111
0
        }
2112
0
        goto loser;
2113
0
    }
2114
2115
    /* Both cipher specs maintain a reference to the master secret, since each
2116
     * is managed and freed independently. */
2117
112k
    prSpec->masterSecret = masterSecret;
2118
112k
    pwSpec->masterSecret = PK11_ReferenceSymKey(masterSecret);
2119
112k
    rv = ssl3_InitPendingContexts(ss, ss->ssl3.prSpec);
2120
112k
    if (rv != SECSuccess) {
2121
0
        goto loser;
2122
0
    }
2123
2124
112k
    rv = ssl3_InitPendingContexts(ss, ss->ssl3.pwSpec);
2125
112k
    if (rv != SECSuccess) {
2126
0
        goto loser;
2127
0
    }
2128
2129
112k
    ssl_ReleaseSpecWriteLock(ss); /******************************/
2130
112k
    return SECSuccess;
2131
2132
202
loser:
2133
202
    ssl_ReleaseSpecWriteLock(ss); /******************************/
2134
202
    ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
2135
202
    return SECFailure;
2136
112k
}
2137
2138
/*
2139
 * 60 bytes is 3 times the maximum length MAC size that is supported.
2140
 */
2141
static const unsigned char mac_pad_1[60] = {
2142
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2143
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2144
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2145
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2146
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2147
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2148
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2149
    0x36, 0x36, 0x36, 0x36
2150
};
2151
static const unsigned char mac_pad_2[60] = {
2152
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2153
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2154
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2155
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2156
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2157
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2158
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2159
    0x5c, 0x5c, 0x5c, 0x5c
2160
};
2161
2162
/* Called from: ssl3_SendRecord()
2163
** Caller must already hold the SpecReadLock. (wish we could assert that!)
2164
*/
2165
static SECStatus
2166
ssl3_ComputeRecordMAC(
2167
    ssl3CipherSpec *spec,
2168
    const unsigned char *header,
2169
    unsigned int headerLen,
2170
    const PRUint8 *input,
2171
    int inputLen,
2172
    unsigned char *outbuf,
2173
    unsigned int *outLen)
2174
179k
{
2175
179k
    PK11Context *context;
2176
179k
    int macSize = spec->macDef->mac_size;
2177
179k
    SECStatus rv;
2178
2179
179k
    PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen));
2180
179k
    PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLen));
2181
2182
179k
    if (spec->macDef->mac == ssl_mac_null) {
2183
147k
        *outLen = 0;
2184
147k
        return SECSuccess;
2185
147k
    }
2186
2187
32.8k
    context = spec->keyMaterial.macContext;
2188
32.8k
    rv = PK11_DigestBegin(context);
2189
32.8k
    rv |= PK11_DigestOp(context, header, headerLen);
2190
32.8k
    rv |= PK11_DigestOp(context, input, inputLen);
2191
32.8k
    rv |= PK11_DigestFinal(context, outbuf, outLen, macSize);
2192
32.8k
    PORT_Assert(rv != SECSuccess || *outLen == (unsigned)macSize);
2193
2194
32.8k
    PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLen));
2195
2196
32.8k
    if (rv != SECSuccess) {
2197
0
        rv = SECFailure;
2198
0
        ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2199
0
    }
2200
32.8k
    return rv;
2201
179k
}
2202
2203
/* Called from: ssl3_HandleRecord()
2204
 * Caller must already hold the SpecReadLock. (wish we could assert that!)
2205
 *
2206
 * On entry:
2207
 *   originalLen >= inputLen >= MAC size
2208
 */
2209
static SECStatus
2210
ssl3_ComputeRecordMACConstantTime(
2211
    ssl3CipherSpec *spec,
2212
    const unsigned char *header,
2213
    unsigned int headerLen,
2214
    const PRUint8 *input,
2215
    int inputLen,
2216
    int originalLen,
2217
    unsigned char *outbuf,
2218
    unsigned int *outLen)
2219
23.0k
{
2220
23.0k
    CK_MECHANISM_TYPE macType;
2221
23.0k
    CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
2222
23.0k
    SECItem param, inputItem, outputItem;
2223
23.0k
    int macSize = spec->macDef->mac_size;
2224
23.0k
    SECStatus rv;
2225
2226
23.0k
    PORT_Assert(inputLen >= spec->macDef->mac_size);
2227
23.0k
    PORT_Assert(originalLen >= inputLen);
2228
2229
23.0k
    if (spec->macDef->mac == ssl_mac_null) {
2230
0
        *outLen = 0;
2231
0
        return SECSuccess;
2232
0
    }
2233
2234
23.0k
    macType = CKM_NSS_HMAC_CONSTANT_TIME;
2235
23.0k
    if (spec->version == SSL_LIBRARY_VERSION_3_0) {
2236
0
        macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME;
2237
0
    }
2238
2239
23.0k
    params.macAlg = spec->macDef->mmech;
2240
23.0k
    params.ulBodyTotalLen = originalLen;
2241
23.0k
    params.pHeader = (unsigned char *)header; /* const cast */
2242
23.0k
    params.ulHeaderLen = headerLen;
2243
2244
23.0k
    param.data = (unsigned char *)&params;
2245
23.0k
    param.len = sizeof(params);
2246
23.0k
    param.type = 0;
2247
2248
23.0k
    inputItem.data = (unsigned char *)input;
2249
23.0k
    inputItem.len = inputLen;
2250
23.0k
    inputItem.type = 0;
2251
2252
23.0k
    outputItem.data = outbuf;
2253
23.0k
    outputItem.len = *outLen;
2254
23.0k
    outputItem.type = 0;
2255
2256
23.0k
    rv = PK11_SignWithSymKey(spec->keyMaterial.macKey, macType, &param,
2257
23.0k
                             &outputItem, &inputItem);
2258
23.0k
    if (rv != SECSuccess) {
2259
0
        if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) {
2260
            /* ssl3_ComputeRecordMAC() expects the MAC to have been removed
2261
             * from the input length already. */
2262
0
            return ssl3_ComputeRecordMAC(spec, header, headerLen,
2263
0
                                         input, inputLen - macSize,
2264
0
                                         outbuf, outLen);
2265
0
        }
2266
2267
0
        *outLen = 0;
2268
0
        rv = SECFailure;
2269
0
        ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2270
0
        return rv;
2271
0
    }
2272
2273
23.0k
    PORT_Assert(outputItem.len == (unsigned)macSize);
2274
23.0k
    *outLen = outputItem.len;
2275
2276
23.0k
    return rv;
2277
23.0k
}
2278
2279
static PRBool
2280
ssl3_ClientAuthTokenPresent(sslSessionID *sid)
2281
14.8M
{
2282
14.8M
    PK11SlotInfo *slot = NULL;
2283
14.8M
    PRBool isPresent = PR_TRUE;
2284
2285
    /* we only care if we are doing client auth */
2286
14.8M
    if (!sid || !sid->u.ssl3.clAuthValid) {
2287
14.8M
        return PR_TRUE;
2288
14.8M
    }
2289
2290
    /* get the slot */
2291
0
    slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
2292
0
                             sid->u.ssl3.clAuthSlotID);
2293
0
    if (slot == NULL ||
2294
0
        !PK11_IsPresent(slot) ||
2295
0
        sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) ||
2296
0
        sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) ||
2297
0
        sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) ||
2298
0
        (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
2299
0
        isPresent = PR_FALSE;
2300
0
    }
2301
0
    if (slot) {
2302
0
        PK11_FreeSlot(slot);
2303
0
    }
2304
0
    return isPresent;
2305
14.8M
}
2306
2307
/* Caller must hold the spec read lock. */
2308
SECStatus
2309
ssl3_MACEncryptRecord(ssl3CipherSpec *cwSpec,
2310
                      PRBool isServer,
2311
                      PRBool isDTLS,
2312
                      SSLContentType ct,
2313
                      const PRUint8 *pIn,
2314
                      PRUint32 contentLen,
2315
                      sslBuffer *wrBuf)
2316
52.8k
{
2317
52.8k
    SECStatus rv;
2318
52.8k
    PRUint32 macLen = 0;
2319
52.8k
    PRUint32 fragLen;
2320
52.8k
    PRUint32 p1Len, p2Len, oddLen = 0;
2321
52.8k
    unsigned int ivLen = 0;
2322
52.8k
    unsigned char pseudoHeaderBuf[13];
2323
52.8k
    sslBuffer pseudoHeader = SSL_BUFFER(pseudoHeaderBuf);
2324
52.8k
    unsigned int len;
2325
2326
52.8k
    if (cwSpec->cipherDef->type == type_block &&
2327
1.74k
        cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
2328
        /* Prepend the per-record explicit IV using technique 2b from
2329
         * RFC 4346 section 6.2.3.2: The IV is a cryptographically
2330
         * strong random number XORed with the CBC residue from the previous
2331
         * record.
2332
         */
2333
1.37k
        ivLen = cwSpec->cipherDef->iv_size;
2334
1.37k
        if (ivLen > SSL_BUFFER_SPACE(wrBuf)) {
2335
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2336
0
            return SECFailure;
2337
0
        }
2338
1.37k
        rv = PK11_GenerateRandom(SSL_BUFFER_NEXT(wrBuf), ivLen);
2339
1.37k
        if (rv != SECSuccess) {
2340
0
            ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
2341
0
            return rv;
2342
0
        }
2343
1.37k
        rv = cwSpec->cipher(cwSpec->cipherContext,
2344
1.37k
                            SSL_BUFFER_NEXT(wrBuf), /* output */
2345
1.37k
                            &len,                   /* outlen */
2346
1.37k
                            ivLen,                  /* max outlen */
2347
1.37k
                            SSL_BUFFER_NEXT(wrBuf), /* input */
2348
1.37k
                            ivLen);                 /* input len */
2349
1.37k
        if (rv != SECSuccess || len != ivLen) {
2350
0
            PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2351
0
            return SECFailure;
2352
0
        }
2353
2354
1.37k
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2355
1.37k
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2356
1.37k
    }
2357
52.8k
    rv = ssl3_BuildRecordPseudoHeader(
2358
52.8k
        cwSpec->epoch, cwSpec->nextSeqNum, ct,
2359
52.8k
        cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->recordVersion,
2360
52.8k
        isDTLS, contentLen, &pseudoHeader, cwSpec->version);
2361
52.8k
    PORT_Assert(rv == SECSuccess);
2362
52.8k
    if (cwSpec->cipherDef->type == type_aead) {
2363
123
        const unsigned int nonceLen = cwSpec->cipherDef->explicit_nonce_size;
2364
123
        const unsigned int tagLen = cwSpec->cipherDef->tag_size;
2365
123
        unsigned int ivOffset = 0;
2366
123
        CK_GENERATOR_FUNCTION gen;
2367
        /* ivOut includes the iv and the nonce and is the internal iv/nonce
2368
         * for the AEAD function. On Encrypt, this is an in/out parameter */
2369
123
        unsigned char ivOut[MAX_IV_LENGTH];
2370
123
        ivLen = cwSpec->cipherDef->iv_size;
2371
2372
123
        PORT_Assert((ivLen + nonceLen) <= MAX_IV_LENGTH);
2373
123
        PORT_Assert((ivLen + nonceLen) >= sizeof(sslSequenceNumber));
2374
2375
123
        if (nonceLen + contentLen + tagLen > SSL_BUFFER_SPACE(wrBuf)) {
2376
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2377
0
            return SECFailure;
2378
0
        }
2379
2380
123
        if (nonceLen == 0) {
2381
8
            ivOffset = ivLen - sizeof(sslSequenceNumber);
2382
8
            gen = CKG_GENERATE_COUNTER_XOR;
2383
115
        } else {
2384
115
            ivOffset = ivLen;
2385
115
            gen = CKG_GENERATE_COUNTER;
2386
115
        }
2387
123
        ivOffset = tls13_SetupAeadIv(isDTLS, cwSpec->version, ivOut, cwSpec->keyMaterial.iv,
2388
123
                                     ivOffset, ivLen, cwSpec->epoch);
2389
123
        rv = tls13_AEAD(cwSpec->cipherContext,
2390
123
                        PR_FALSE,
2391
123
                        gen, ivOffset * BPB,                /* iv generator params */
2392
123
                        ivOut,                              /* iv in  */
2393
123
                        ivOut,                              /* iv out */
2394
123
                        ivLen + nonceLen,                   /* full iv length */
2395
123
                        NULL, 0,                            /* nonce is generated*/
2396
123
                        SSL_BUFFER_BASE(&pseudoHeader),     /* aad */
2397
123
                        SSL_BUFFER_LEN(&pseudoHeader),      /* aadlen */
2398
123
                        SSL_BUFFER_NEXT(wrBuf) + nonceLen,  /* output  */
2399
123
                        &len,                               /* out len */
2400
123
                        SSL_BUFFER_SPACE(wrBuf) - nonceLen, /* max out */
2401
123
                        tagLen,
2402
123
                        pIn, contentLen); /* input   */
2403
123
        if (rv != SECSuccess) {
2404
0
            PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2405
0
            return SECFailure;
2406
0
        }
2407
123
        len += nonceLen; /* include the nonce at the beginning */
2408
        /* copy out the generated iv if we are using explict nonces */
2409
123
        if (nonceLen) {
2410
115
            PORT_Memcpy(SSL_BUFFER_NEXT(wrBuf), ivOut + ivLen, nonceLen);
2411
115
        }
2412
2413
123
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2414
123
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2415
52.7k
    } else {
2416
52.7k
        int blockSize = cwSpec->cipherDef->block_size;
2417
2418
        /*
2419
         * Add the MAC
2420
         */
2421
52.7k
        rv = ssl3_ComputeRecordMAC(cwSpec, SSL_BUFFER_BASE(&pseudoHeader),
2422
52.7k
                                   SSL_BUFFER_LEN(&pseudoHeader),
2423
52.7k
                                   pIn, contentLen,
2424
52.7k
                                   SSL_BUFFER_NEXT(wrBuf) + contentLen, &macLen);
2425
52.7k
        if (rv != SECSuccess) {
2426
0
            ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2427
0
            return SECFailure;
2428
0
        }
2429
52.7k
        p1Len = contentLen;
2430
52.7k
        p2Len = macLen;
2431
52.7k
        fragLen = contentLen + macLen; /* needs to be encrypted */
2432
52.7k
        PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
2433
2434
        /*
2435
         * Pad the text (if we're doing a block cipher)
2436
         * then Encrypt it
2437
         */
2438
52.7k
        if (cwSpec->cipherDef->type == type_block) {
2439
1.74k
            unsigned char *pBuf;
2440
1.74k
            int padding_length;
2441
1.74k
            int i;
2442
2443
1.74k
            oddLen = contentLen % blockSize;
2444
            /* Assume blockSize is a power of two */
2445
1.74k
            padding_length = blockSize - 1 - ((fragLen) & (blockSize - 1));
2446
1.74k
            fragLen += padding_length + 1;
2447
1.74k
            PORT_Assert((fragLen % blockSize) == 0);
2448
2449
            /* Pad according to TLS rules (also acceptable to SSL3). */
2450
1.74k
            pBuf = SSL_BUFFER_NEXT(wrBuf) + fragLen - 1;
2451
14.3k
            for (i = padding_length + 1; i > 0; --i) {
2452
12.6k
                *pBuf-- = padding_length;
2453
12.6k
            }
2454
            /* now, if contentLen is not a multiple of block size, fix it */
2455
1.74k
            p2Len = fragLen - p1Len;
2456
1.74k
        }
2457
52.7k
        if (p1Len < 256) {
2458
35.2k
            oddLen = p1Len;
2459
35.2k
            p1Len = 0;
2460
35.2k
        } else {
2461
17.5k
            p1Len -= oddLen;
2462
17.5k
        }
2463
52.7k
        if (oddLen) {
2464
35.2k
            p2Len += oddLen;
2465
35.2k
            PORT_Assert((blockSize < 2) ||
2466
35.2k
                        (p2Len % blockSize) == 0);
2467
35.2k
            memmove(SSL_BUFFER_NEXT(wrBuf) + p1Len, pIn + p1Len, oddLen);
2468
35.2k
        }
2469
52.7k
        if (p1Len > 0) {
2470
17.5k
            unsigned int cipherBytesPart1 = 0;
2471
17.5k
            rv = cwSpec->cipher(cwSpec->cipherContext,
2472
17.5k
                                SSL_BUFFER_NEXT(wrBuf), /* output */
2473
17.5k
                                &cipherBytesPart1,      /* actual outlen */
2474
17.5k
                                p1Len,                  /* max outlen */
2475
17.5k
                                pIn,
2476
17.5k
                                p1Len); /* input, and inputlen */
2477
17.5k
            PORT_Assert(rv == SECSuccess && cipherBytesPart1 == p1Len);
2478
17.5k
            if (rv != SECSuccess || cipherBytesPart1 != p1Len) {
2479
0
                PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2480
0
                return SECFailure;
2481
0
            }
2482
17.5k
            rv = sslBuffer_Skip(wrBuf, p1Len, NULL);
2483
17.5k
            PORT_Assert(rv == SECSuccess);
2484
17.5k
        }
2485
52.7k
        if (p2Len > 0) {
2486
35.2k
            unsigned int cipherBytesPart2 = 0;
2487
35.2k
            rv = cwSpec->cipher(cwSpec->cipherContext,
2488
35.2k
                                SSL_BUFFER_NEXT(wrBuf),
2489
35.2k
                                &cipherBytesPart2, /* output and actual outLen */
2490
35.2k
                                p2Len,             /* max outlen */
2491
35.2k
                                SSL_BUFFER_NEXT(wrBuf),
2492
35.2k
                                p2Len); /* input and inputLen*/
2493
35.2k
            PORT_Assert(rv == SECSuccess && cipherBytesPart2 == p2Len);
2494
35.2k
            if (rv != SECSuccess || cipherBytesPart2 != p2Len) {
2495
0
                PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2496
0
                return SECFailure;
2497
0
            }
2498
35.2k
            rv = sslBuffer_Skip(wrBuf, p2Len, NULL);
2499
35.2k
            PORT_Assert(rv == SECSuccess);
2500
35.2k
        }
2501
52.7k
    }
2502
2503
52.8k
    return SECSuccess;
2504
52.8k
}
2505
2506
/* Note: though this can report failure, it shouldn't. */
2507
SECStatus
2508
ssl_InsertRecordHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec,
2509
                       SSLContentType contentType, sslBuffer *wrBuf,
2510
                       PRBool *needsLength)
2511
1.29M
{
2512
1.29M
    SECStatus rv;
2513
2514
#ifndef UNSAFE_FUZZER_MODE
2515
135k
    if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
2516
82.4k
        cwSpec->epoch > TrafficKeyClearText) {
2517
51.5k
        if (IS_DTLS(ss)) {
2518
46.0k
            return dtls13_InsertCipherTextHeader(ss, cwSpec, wrBuf,
2519
46.0k
                                                 needsLength);
2520
46.0k
        }
2521
5.52k
        contentType = ssl_ct_application_data;
2522
5.52k
    }
2523
89.3k
#endif
2524
89.3k
    rv = sslBuffer_AppendNumber(wrBuf, contentType, 1);
2525
1.24M
    if (rv != SECSuccess) {
2526
0
        return SECFailure;
2527
0
    }
2528
2529
1.24M
    rv = sslBuffer_AppendNumber(wrBuf, cwSpec->recordVersion, 2);
2530
1.24M
    if (rv != SECSuccess) {
2531
0
        return SECFailure;
2532
0
    }
2533
1.24M
    if (IS_DTLS(ss)) {
2534
108k
        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->epoch, 2);
2535
108k
        if (rv != SECSuccess) {
2536
0
            return SECFailure;
2537
0
        }
2538
108k
        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->nextSeqNum, 6);
2539
108k
        if (rv != SECSuccess) {
2540
0
            return SECFailure;
2541
0
        }
2542
108k
    }
2543
1.24M
    *needsLength = PR_TRUE;
2544
1.24M
    return SECSuccess;
2545
1.24M
}
ssl_InsertRecordHeader
Line
Count
Source
2511
1.15M
{
2512
1.15M
    SECStatus rv;
2513
2514
#ifndef UNSAFE_FUZZER_MODE
2515
    if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
2516
        cwSpec->epoch > TrafficKeyClearText) {
2517
        if (IS_DTLS(ss)) {
2518
            return dtls13_InsertCipherTextHeader(ss, cwSpec, wrBuf,
2519
                                                 needsLength);
2520
        }
2521
        contentType = ssl_ct_application_data;
2522
    }
2523
#endif
2524
1.15M
    rv = sslBuffer_AppendNumber(wrBuf, contentType, 1);
2525
1.15M
    if (rv != SECSuccess) {
2526
0
        return SECFailure;
2527
0
    }
2528
2529
1.15M
    rv = sslBuffer_AppendNumber(wrBuf, cwSpec->recordVersion, 2);
2530
1.15M
    if (rv != SECSuccess) {
2531
0
        return SECFailure;
2532
0
    }
2533
1.15M
    if (IS_DTLS(ss)) {
2534
51.1k
        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->epoch, 2);
2535
51.1k
        if (rv != SECSuccess) {
2536
0
            return SECFailure;
2537
0
        }
2538
51.1k
        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->nextSeqNum, 6);
2539
51.1k
        if (rv != SECSuccess) {
2540
0
            return SECFailure;
2541
0
        }
2542
51.1k
    }
2543
1.15M
    *needsLength = PR_TRUE;
2544
1.15M
    return SECSuccess;
2545
1.15M
}
ssl_InsertRecordHeader
Line
Count
Source
2511
135k
{
2512
135k
    SECStatus rv;
2513
2514
135k
#ifndef UNSAFE_FUZZER_MODE
2515
135k
    if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
2516
82.4k
        cwSpec->epoch > TrafficKeyClearText) {
2517
51.5k
        if (IS_DTLS(ss)) {
2518
46.0k
            return dtls13_InsertCipherTextHeader(ss, cwSpec, wrBuf,
2519
46.0k
                                                 needsLength);
2520
46.0k
        }
2521
5.52k
        contentType = ssl_ct_application_data;
2522
5.52k
    }
2523
89.3k
#endif
2524
89.3k
    rv = sslBuffer_AppendNumber(wrBuf, contentType, 1);
2525
89.3k
    if (rv != SECSuccess) {
2526
0
        return SECFailure;
2527
0
    }
2528
2529
89.3k
    rv = sslBuffer_AppendNumber(wrBuf, cwSpec->recordVersion, 2);
2530
89.3k
    if (rv != SECSuccess) {
2531
0
        return SECFailure;
2532
0
    }
2533
89.3k
    if (IS_DTLS(ss)) {
2534
56.9k
        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->epoch, 2);
2535
56.9k
        if (rv != SECSuccess) {
2536
0
            return SECFailure;
2537
0
        }
2538
56.9k
        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->nextSeqNum, 6);
2539
56.9k
        if (rv != SECSuccess) {
2540
0
            return SECFailure;
2541
0
        }
2542
56.9k
    }
2543
89.3k
    *needsLength = PR_TRUE;
2544
89.3k
    return SECSuccess;
2545
89.3k
}
2546
2547
SECStatus
2548
ssl_ProtectRecord(sslSocket *ss, ssl3CipherSpec *cwSpec, SSLContentType ct,
2549
                  const PRUint8 *pIn, PRUint32 contentLen, sslBuffer *wrBuf)
2550
1.26M
{
2551
1.26M
    PRBool needsLength;
2552
1.26M
    unsigned int lenOffset;
2553
1.26M
    SECStatus rv;
2554
2555
1.26M
    PORT_Assert(cwSpec->direction == ssl_secret_write);
2556
1.26M
    PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
2557
1.26M
    PORT_Assert(cwSpec->cipherDef->max_records <= RECORD_SEQ_MAX);
2558
2559
1.26M
    if (cwSpec->nextSeqNum >= cwSpec->cipherDef->max_records) {
2560
0
        SSL_TRC(3, ("%d: SSL[-]: write sequence number at limit 0x%0llx",
2561
0
                    SSL_GETPID(), cwSpec->nextSeqNum));
2562
0
        PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
2563
0
        return SECFailure;
2564
0
    }
2565
2566
1.26M
    rv = ssl_InsertRecordHeader(ss, cwSpec, ct, wrBuf, &needsLength);
2567
1.26M
    if (rv != SECSuccess) {
2568
0
        return SECFailure;
2569
0
    }
2570
1.26M
    if (needsLength) {
2571
1.26M
        rv = sslBuffer_Skip(wrBuf, 2, &lenOffset);
2572
1.26M
        if (rv != SECSuccess) {
2573
0
            return SECFailure;
2574
0
        }
2575
1.26M
    }
2576
2577
#ifdef UNSAFE_FUZZER_MODE
2578
1.15M
    {
2579
1.15M
        unsigned int len;
2580
1.15M
        rv = Null_Cipher(NULL, SSL_BUFFER_NEXT(wrBuf), &len,
2581
1.15M
                         SSL_BUFFER_SPACE(wrBuf), pIn, contentLen);
2582
1.15M
        if (rv != SECSuccess) {
2583
0
            return SECFailure; /* error was set */
2584
0
        }
2585
1.15M
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2586
1.15M
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2587
1.15M
    }
2588
#else
2589
109k
    if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
2590
56.6k
        PRUint8 *cipherText = SSL_BUFFER_NEXT(wrBuf);
2591
56.6k
        unsigned int bufLen = SSL_BUFFER_LEN(wrBuf);
2592
56.6k
        rv = tls13_ProtectRecord(ss, cwSpec, ct, pIn, contentLen, wrBuf);
2593
56.6k
        if (rv != SECSuccess) {
2594
0
            return SECFailure;
2595
0
        }
2596
56.6k
        if (IS_DTLS(ss)) {
2597
43.8k
            bufLen = SSL_BUFFER_LEN(wrBuf) - bufLen;
2598
43.8k
            rv = dtls13_MaskSequenceNumber(ss, cwSpec,
2599
43.8k
                                           SSL_BUFFER_BASE(wrBuf),
2600
43.8k
                                           cipherText, bufLen);
2601
43.8k
        }
2602
56.6k
    } else {
2603
52.8k
        rv = ssl3_MACEncryptRecord(cwSpec, ss->sec.isServer, IS_DTLS(ss), ct,
2604
52.8k
                                   pIn, contentLen, wrBuf);
2605
52.8k
    }
2606
109k
#endif
2607
1.26M
    if (rv != SECSuccess) {
2608
0
        return SECFailure; /* error was set */
2609
0
    }
2610
2611
1.26M
    if (needsLength) {
2612
        /* Insert the length. */
2613
1.26M
        rv = sslBuffer_InsertLength(wrBuf, lenOffset, 2);
2614
1.26M
        if (rv != SECSuccess) {
2615
0
            PORT_Assert(0); /* Can't fail. */
2616
0
            return SECFailure;
2617
0
        }
2618
1.26M
    }
2619
2620
1.26M
    ++cwSpec->nextSeqNum;
2621
1.26M
    return SECSuccess;
2622
1.26M
}
ssl_ProtectRecord
Line
Count
Source
2550
1.15M
{
2551
1.15M
    PRBool needsLength;
2552
1.15M
    unsigned int lenOffset;
2553
1.15M
    SECStatus rv;
2554
2555
1.15M
    PORT_Assert(cwSpec->direction == ssl_secret_write);
2556
1.15M
    PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
2557
1.15M
    PORT_Assert(cwSpec->cipherDef->max_records <= RECORD_SEQ_MAX);
2558
2559
1.15M
    if (cwSpec->nextSeqNum >= cwSpec->cipherDef->max_records) {
2560
0
        SSL_TRC(3, ("%d: SSL[-]: write sequence number at limit 0x%0llx",
2561
0
                    SSL_GETPID(), cwSpec->nextSeqNum));
2562
0
        PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
2563
0
        return SECFailure;
2564
0
    }
2565
2566
1.15M
    rv = ssl_InsertRecordHeader(ss, cwSpec, ct, wrBuf, &needsLength);
2567
1.15M
    if (rv != SECSuccess) {
2568
0
        return SECFailure;
2569
0
    }
2570
1.15M
    if (needsLength) {
2571
1.15M
        rv = sslBuffer_Skip(wrBuf, 2, &lenOffset);
2572
1.15M
        if (rv != SECSuccess) {
2573
0
            return SECFailure;
2574
0
        }
2575
1.15M
    }
2576
2577
1.15M
#ifdef UNSAFE_FUZZER_MODE
2578
1.15M
    {
2579
1.15M
        unsigned int len;
2580
1.15M
        rv = Null_Cipher(NULL, SSL_BUFFER_NEXT(wrBuf), &len,
2581
1.15M
                         SSL_BUFFER_SPACE(wrBuf), pIn, contentLen);
2582
1.15M
        if (rv != SECSuccess) {
2583
0
            return SECFailure; /* error was set */
2584
0
        }
2585
1.15M
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2586
1.15M
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2587
1.15M
    }
2588
#else
2589
    if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
2590
        PRUint8 *cipherText = SSL_BUFFER_NEXT(wrBuf);
2591
        unsigned int bufLen = SSL_BUFFER_LEN(wrBuf);
2592
        rv = tls13_ProtectRecord(ss, cwSpec, ct, pIn, contentLen, wrBuf);
2593
        if (rv != SECSuccess) {
2594
            return SECFailure;
2595
        }
2596
        if (IS_DTLS(ss)) {
2597
            bufLen = SSL_BUFFER_LEN(wrBuf) - bufLen;
2598
            rv = dtls13_MaskSequenceNumber(ss, cwSpec,
2599
                                           SSL_BUFFER_BASE(wrBuf),
2600
                                           cipherText, bufLen);
2601
        }
2602
    } else {
2603
        rv = ssl3_MACEncryptRecord(cwSpec, ss->sec.isServer, IS_DTLS(ss), ct,
2604
                                   pIn, contentLen, wrBuf);
2605
    }
2606
#endif
2607
1.15M
    if (rv != SECSuccess) {
2608
0
        return SECFailure; /* error was set */
2609
0
    }
2610
2611
1.15M
    if (needsLength) {
2612
        /* Insert the length. */
2613
1.15M
        rv = sslBuffer_InsertLength(wrBuf, lenOffset, 2);
2614
1.15M
        if (rv != SECSuccess) {
2615
0
            PORT_Assert(0); /* Can't fail. */
2616
0
            return SECFailure;
2617
0
        }
2618
1.15M
    }
2619
2620
1.15M
    ++cwSpec->nextSeqNum;
2621
1.15M
    return SECSuccess;
2622
1.15M
}
ssl_ProtectRecord
Line
Count
Source
2550
109k
{
2551
109k
    PRBool needsLength;
2552
109k
    unsigned int lenOffset;
2553
109k
    SECStatus rv;
2554
2555
109k
    PORT_Assert(cwSpec->direction == ssl_secret_write);
2556
109k
    PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
2557
109k
    PORT_Assert(cwSpec->cipherDef->max_records <= RECORD_SEQ_MAX);
2558
2559
109k
    if (cwSpec->nextSeqNum >= cwSpec->cipherDef->max_records) {
2560
0
        SSL_TRC(3, ("%d: SSL[-]: write sequence number at limit 0x%0llx",
2561
0
                    SSL_GETPID(), cwSpec->nextSeqNum));
2562
0
        PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
2563
0
        return SECFailure;
2564
0
    }
2565
2566
109k
    rv = ssl_InsertRecordHeader(ss, cwSpec, ct, wrBuf, &needsLength);
2567
109k
    if (rv != SECSuccess) {
2568
0
        return SECFailure;
2569
0
    }
2570
109k
    if (needsLength) {
2571
109k
        rv = sslBuffer_Skip(wrBuf, 2, &lenOffset);
2572
109k
        if (rv != SECSuccess) {
2573
0
            return SECFailure;
2574
0
        }
2575
109k
    }
2576
2577
#ifdef UNSAFE_FUZZER_MODE
2578
    {
2579
        unsigned int len;
2580
        rv = Null_Cipher(NULL, SSL_BUFFER_NEXT(wrBuf), &len,
2581
                         SSL_BUFFER_SPACE(wrBuf), pIn, contentLen);
2582
        if (rv != SECSuccess) {
2583
            return SECFailure; /* error was set */
2584
        }
2585
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2586
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2587
    }
2588
#else
2589
109k
    if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
2590
56.6k
        PRUint8 *cipherText = SSL_BUFFER_NEXT(wrBuf);
2591
56.6k
        unsigned int bufLen = SSL_BUFFER_LEN(wrBuf);
2592
56.6k
        rv = tls13_ProtectRecord(ss, cwSpec, ct, pIn, contentLen, wrBuf);
2593
56.6k
        if (rv != SECSuccess) {
2594
0
            return SECFailure;
2595
0
        }
2596
56.6k
        if (IS_DTLS(ss)) {
2597
43.8k
            bufLen = SSL_BUFFER_LEN(wrBuf) - bufLen;
2598
43.8k
            rv = dtls13_MaskSequenceNumber(ss, cwSpec,
2599
43.8k
                                           SSL_BUFFER_BASE(wrBuf),
2600
43.8k
                                           cipherText, bufLen);
2601
43.8k
        }
2602
56.6k
    } else {
2603
52.8k
        rv = ssl3_MACEncryptRecord(cwSpec, ss->sec.isServer, IS_DTLS(ss), ct,
2604
52.8k
                                   pIn, contentLen, wrBuf);
2605
52.8k
    }
2606
109k
#endif
2607
109k
    if (rv != SECSuccess) {
2608
0
        return SECFailure; /* error was set */
2609
0
    }
2610
2611
109k
    if (needsLength) {
2612
        /* Insert the length. */
2613
109k
        rv = sslBuffer_InsertLength(wrBuf, lenOffset, 2);
2614
109k
        if (rv != SECSuccess) {
2615
0
            PORT_Assert(0); /* Can't fail. */
2616
0
            return SECFailure;
2617
0
        }
2618
109k
    }
2619
2620
109k
    ++cwSpec->nextSeqNum;
2621
109k
    return SECSuccess;
2622
109k
}
2623
2624
SECStatus
2625
ssl_ProtectNextRecord(sslSocket *ss, ssl3CipherSpec *spec, SSLContentType ct,
2626
                      const PRUint8 *pIn, unsigned int nIn,
2627
                      unsigned int *written)
2628
1.26M
{
2629
1.26M
    sslBuffer *wrBuf = &ss->sec.writeBuf;
2630
1.26M
    unsigned int contentLen;
2631
1.26M
    unsigned int spaceNeeded;
2632
1.26M
    SECStatus rv;
2633
2634
1.26M
    contentLen = PR_MIN(nIn, spec->recordSizeLimit);
2635
1.26M
    spaceNeeded = contentLen + SSL3_BUFFER_FUDGE;
2636
1.26M
    if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
2637
1.12M
        spec->cipherDef->type == type_block) {
2638
155k
        spaceNeeded += spec->cipherDef->iv_size;
2639
155k
    }
2640
1.26M
    if (spaceNeeded > SSL_BUFFER_SPACE(wrBuf)) {
2641
0
        rv = sslBuffer_Grow(wrBuf, spaceNeeded);
2642
0
        if (rv != SECSuccess) {
2643
0
            SSL_DBG(("%d: SSL3[%d]: failed to expand write buffer to %d",
2644
0
                     SSL_GETPID(), ss->fd, spaceNeeded));
2645
0
            return SECFailure;
2646
0
        }
2647
0
    }
2648
2649
1.26M
    rv = ssl_ProtectRecord(ss, spec, ct, pIn, contentLen, wrBuf);
2650
1.26M
    if (rv != SECSuccess) {
2651
0
        return SECFailure;
2652
0
    }
2653
1.26M
    PRINT_BUF(50, (ss, "send (encrypted) record data:",
2654
1.26M
                   SSL_BUFFER_BASE(wrBuf), SSL_BUFFER_LEN(wrBuf)));
2655
1.26M
    *written = contentLen;
2656
1.26M
    return SECSuccess;
2657
1.26M
}
2658
2659
/* Process the plain text before sending it.
2660
 * Returns the number of bytes of plaintext that were successfully sent
2661
 *  plus the number of bytes of plaintext that were copied into the
2662
 *  output (write) buffer.
2663
 * Returns -1 on an error.  PR_WOULD_BLOCK_ERROR is set if the error is blocking
2664
 *  and not terminal.
2665
 *
2666
 * Notes on the use of the private ssl flags:
2667
 * (no private SSL flags)
2668
 *    Attempt to make and send SSL records for all plaintext
2669
 *    If non-blocking and a send gets WOULD_BLOCK,
2670
 *    or if the pending (ciphertext) buffer is not empty,
2671
 *    then buffer remaining bytes of ciphertext into pending buf,
2672
 *    and continue to do that for all succssive records until all
2673
 *    bytes are used.
2674
 * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2675
 *    As above, except this suppresses all write attempts, and forces
2676
 *    all ciphertext into the pending ciphertext buffer.
2677
 * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
2678
 *    Forces the use of the provided epoch
2679
 */
2680
PRInt32
2681
ssl3_SendRecord(sslSocket *ss,
2682
                ssl3CipherSpec *cwSpec, /* non-NULL for DTLS retransmits */
2683
                SSLContentType ct,
2684
                const PRUint8 *pIn, /* input buffer */
2685
                PRInt32 nIn,        /* bytes of input */
2686
                PRInt32 flags)
2687
1.26M
{
2688
1.26M
    sslBuffer *wrBuf = &ss->sec.writeBuf;
2689
1.26M
    ssl3CipherSpec *spec;
2690
1.26M
    SECStatus rv;
2691
1.26M
    PRInt32 totalSent = 0;
2692
2693
1.26M
    SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
2694
1.26M
                SSL_GETPID(), ss->fd, ssl3_DecodeContentType(ct),
2695
1.26M
                nIn));
2696
1.26M
    PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn));
2697
2698
1.26M
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2699
1.26M
    PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
2700
2701
1.26M
    if (ss->ssl3.fatalAlertSent) {
2702
3.00k
        SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent",
2703
3.00k
                    SSL_GETPID(), ss->fd));
2704
3.00k
        if (ct != ssl_ct_alert) {
2705
            /* If we are sending an alert, then we already have an
2706
             * error, so don't overwrite. */
2707
13
            PORT_SetError(SSL_ERROR_HANDSHAKE_FAILED);
2708
13
        }
2709
3.00k
        return -1;
2710
3.00k
    }
2711
2712
    /* check for Token Presence */
2713
1.26M
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
2714
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
2715
0
        return -1;
2716
0
    }
2717
2718
1.26M
    if (ss->recordWriteCallback) {
2719
0
        PRUint16 epoch;
2720
0
        ssl_GetSpecReadLock(ss);
2721
0
        epoch = ss->ssl3.cwSpec->epoch;
2722
0
        ssl_ReleaseSpecReadLock(ss);
2723
0
        rv = ss->recordWriteCallback(ss->fd, epoch, ct, pIn, nIn,
2724
0
                                     ss->recordWriteCallbackArg);
2725
0
        if (rv != SECSuccess) {
2726
0
            return -1;
2727
0
        }
2728
0
        return nIn;
2729
0
    }
2730
2731
1.26M
    if (cwSpec) {
2732
        /* cwSpec can only be set for retransmissions of the DTLS handshake. */
2733
118k
        PORT_Assert(IS_DTLS(ss) &&
2734
118k
                    (ct == ssl_ct_handshake ||
2735
118k
                     ct == ssl_ct_change_cipher_spec));
2736
118k
        spec = cwSpec;
2737
1.14M
    } else {
2738
1.14M
        spec = ss->ssl3.cwSpec;
2739
1.14M
    }
2740
2741
2.52M
    while (nIn > 0) {
2742
1.26M
        unsigned int written = 0;
2743
1.26M
        PRInt32 sent;
2744
2745
1.26M
        ssl_GetSpecReadLock(ss);
2746
1.26M
        rv = ssl_ProtectNextRecord(ss, spec, ct, pIn, nIn, &written);
2747
1.26M
        ssl_ReleaseSpecReadLock(ss);
2748
1.26M
        if (rv != SECSuccess) {
2749
0
            goto loser;
2750
0
        }
2751
2752
1.26M
        PORT_Assert(written > 0);
2753
        /* DTLS should not fragment non-application data here. */
2754
1.26M
        if (IS_DTLS(ss) && ct != ssl_ct_application_data) {
2755
129k
            PORT_Assert(written == nIn);
2756
129k
        }
2757
2758
1.26M
        pIn += written;
2759
1.26M
        nIn -= written;
2760
1.26M
        PORT_Assert(nIn >= 0);
2761
2762
        /* If there's still some previously saved ciphertext,
2763
         * or the caller doesn't want us to send the data yet,
2764
         * then add all our new ciphertext to the amount previously saved.
2765
         */
2766
1.26M
        if ((ss->pendingBuf.len > 0) ||
2767
1.04M
            (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2768
2769
363k
            rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf),
2770
363k
                                   SSL_BUFFER_LEN(wrBuf));
2771
363k
            if (rv != SECSuccess) {
2772
                /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2773
0
                goto loser;
2774
0
            }
2775
2776
363k
            if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2777
100k
                ss->handshakeBegun = 1;
2778
100k
                sent = ssl_SendSavedWriteData(ss);
2779
100k
                if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2780
0
                    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2781
0
                    goto loser;
2782
0
                }
2783
100k
                if (ss->pendingBuf.len) {
2784
0
                    flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2785
0
                }
2786
100k
            }
2787
901k
        } else {
2788
901k
            PORT_Assert(SSL_BUFFER_LEN(wrBuf) > 0);
2789
901k
            ss->handshakeBegun = 1;
2790
901k
            sent = ssl_DefSend(ss, SSL_BUFFER_BASE(wrBuf),
2791
901k
                               SSL_BUFFER_LEN(wrBuf),
2792
901k
                               flags & ~ssl_SEND_FLAG_MASK);
2793
901k
            if (sent < 0) {
2794
0
                if (PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
2795
0
                    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2796
0
                    goto loser;
2797
0
                }
2798
                /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
2799
0
                sent = 0;
2800
0
            }
2801
901k
            if (SSL_BUFFER_LEN(wrBuf) > (unsigned int)sent) {
2802
0
                if (IS_DTLS(ss)) {
2803
                    /* DTLS just says no in this case. No buffering */
2804
0
                    PORT_SetError(PR_WOULD_BLOCK_ERROR);
2805
0
                    goto loser;
2806
0
                }
2807
                /* now take all the remaining unsent new ciphertext and
2808
                 * append it to the buffer of previously unsent ciphertext.
2809
                 */
2810
0
                rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf) + sent,
2811
0
                                       SSL_BUFFER_LEN(wrBuf) - sent);
2812
0
                if (rv != SECSuccess) {
2813
                    /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2814
0
                    goto loser;
2815
0
                }
2816
0
            }
2817
901k
        }
2818
1.26M
        wrBuf->len = 0;
2819
1.26M
        totalSent += written;
2820
1.26M
    }
2821
1.26M
    return totalSent;
2822
2823
0
loser:
2824
    /* Don't leave bits of buffer lying around. */
2825
0
    wrBuf->len = 0;
2826
0
    return -1;
2827
1.26M
}
2828
2829
1.45M
#define SSL3_PENDING_HIGH_WATER 1024
2830
2831
/* Attempt to send the content of "in" in an SSL application_data record.
2832
 * Returns "len" or -1 on failure.
2833
 */
2834
int
2835
ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
2836
                         PRInt32 len, PRInt32 flags)
2837
726k
{
2838
726k
    PRInt32 totalSent = 0;
2839
726k
    PRInt32 discarded = 0;
2840
726k
    PRBool splitNeeded = PR_FALSE;
2841
2842
726k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2843
    /* These flags for internal use only */
2844
726k
    PORT_Assert(!(flags & ssl_SEND_FLAG_NO_RETRANSMIT));
2845
726k
    if (len < 0 || !in) {
2846
0
        PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2847
0
        return -1;
2848
0
    }
2849
2850
726k
    if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
2851
0
        !ssl_SocketIsBlocking(ss)) {
2852
0
        PORT_Assert(!ssl_SocketIsBlocking(ss));
2853
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
2854
0
        return -1;
2855
0
    }
2856
2857
726k
    if (ss->appDataBuffered && len) {
2858
0
        PORT_Assert(in[0] == (unsigned char)(ss->appDataBuffered));
2859
0
        if (in[0] != (unsigned char)(ss->appDataBuffered)) {
2860
0
            PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2861
0
            return -1;
2862
0
        }
2863
0
        in++;
2864
0
        len--;
2865
0
        discarded = 1;
2866
0
    }
2867
2868
    /* We will split the first byte of the record into its own record, as
2869
     * explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h.
2870
     */
2871
726k
    if (len > 1 && ss->opt.cbcRandomIV &&
2872
9.14k
        ss->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
2873
2.09k
        ss->ssl3.cwSpec->cipherDef->type == type_block /* CBC */) {
2874
1.67k
        splitNeeded = PR_TRUE;
2875
1.67k
    }
2876
2877
1.45M
    while (len > totalSent) {
2878
728k
        PRInt32 sent, toSend;
2879
2880
728k
        if (totalSent > 0 && ssl_SocketIsBlocking(ss)) {
2881
            /*
2882
             * The thread yield is intended to give the reader thread a
2883
             * chance to get some cycles while the writer thread is in
2884
             * the middle of a large application data write.  (See
2885
             * Bugzilla bug 127740, comment #1.)
2886
             *
2887
             * For non-blocking sockets, the pendingBuf check below
2888
             * already breaks out of the loop when the underlying
2889
             * socket cannot accept more data.
2890
             */
2891
0
            ssl_ReleaseXmitBufLock(ss);
2892
0
            PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */
2893
0
            ssl_GetXmitBufLock(ss);
2894
0
        }
2895
2896
728k
        if (splitNeeded) {
2897
1.67k
            toSend = 1;
2898
1.67k
            splitNeeded = PR_FALSE;
2899
726k
        } else {
2900
726k
            toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
2901
726k
        }
2902
2903
        /*
2904
         * Note that the 0 epoch is OK because flags will never require
2905
         * its use, as guaranteed by the PORT_Assert above.
2906
         */
2907
728k
        sent = ssl3_SendRecord(ss, NULL, ssl_ct_application_data,
2908
728k
                               in + totalSent, toSend, flags);
2909
728k
        if (sent < 0) {
2910
0
            if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
2911
0
                PORT_Assert(ss->lastWriteBlocked);
2912
0
                break;
2913
0
            }
2914
0
            return -1; /* error code set by ssl3_SendRecord */
2915
0
        }
2916
728k
        totalSent += sent;
2917
728k
        if (ss->pendingBuf.len) {
2918
            /* must be a non-blocking socket */
2919
0
            PORT_Assert(!ssl_SocketIsBlocking(ss));
2920
0
            PORT_Assert(ss->lastWriteBlocked);
2921
0
            break;
2922
0
        }
2923
728k
    }
2924
726k
    if (ss->pendingBuf.len) {
2925
        /* Must be non-blocking. */
2926
0
        PORT_Assert(!ssl_SocketIsBlocking(ss));
2927
0
        if (totalSent > 0) {
2928
0
            ss->appDataBuffered = 0x100 | in[totalSent - 1];
2929
0
        }
2930
2931
0
        totalSent = totalSent + discarded - 1;
2932
0
        if (totalSent <= 0) {
2933
0
            PORT_SetError(PR_WOULD_BLOCK_ERROR);
2934
0
            totalSent = SECFailure;
2935
0
        }
2936
0
        return totalSent;
2937
0
    }
2938
726k
    ss->appDataBuffered = 0;
2939
726k
    return totalSent + discarded;
2940
726k
}
2941
2942
/* Attempt to send buffered handshake messages.
2943
 * Always set sendBuf.len to 0, even when returning SECFailure.
2944
 *
2945
 * Depending on whether we are doing DTLS or not, this either calls
2946
 *
2947
 * - ssl3_FlushHandshakeMessages if non-DTLS
2948
 * - dtls_FlushHandshakeMessages if DTLS
2949
 *
2950
 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
2951
 *             ssl3_AppendHandshake(), ssl3_SendClientHello(),
2952
 *             ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
2953
 *             ssl3_SendFinished(),
2954
 */
2955
SECStatus
2956
ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
2957
554k
{
2958
554k
    if (IS_DTLS(ss)) {
2959
51.6k
        return dtls_FlushHandshakeMessages(ss, flags);
2960
51.6k
    }
2961
502k
    return ssl3_FlushHandshakeMessages(ss, flags);
2962
554k
}
2963
2964
/* Attempt to send the content of sendBuf buffer in an SSL handshake record.
2965
 * Always set sendBuf.len to 0, even when returning SECFailure.
2966
 *
2967
 * Called from ssl3_FlushHandshake
2968
 */
2969
static SECStatus
2970
ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
2971
502k
{
2972
502k
    static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2973
502k
    PRInt32 count = -1;
2974
502k
    SECStatus rv;
2975
2976
502k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2977
502k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2978
2979
502k
    if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
2980
214k
        return SECSuccess;
2981
2982
    /* only these flags are allowed */
2983
287k
    PORT_Assert(!(flags & ~allowedFlags));
2984
287k
    if ((flags & ~allowedFlags) != 0) {
2985
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
2986
0
        return SECFailure;
2987
0
    }
2988
287k
    count = ssl3_SendRecord(ss, NULL, ssl_ct_handshake,
2989
287k
                            ss->sec.ci.sendBuf.buf,
2990
287k
                            ss->sec.ci.sendBuf.len, flags);
2991
287k
    if (count < 0) {
2992
13
        int err = PORT_GetError();
2993
13
        PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
2994
13
        if (err == PR_WOULD_BLOCK_ERROR) {
2995
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2996
0
        }
2997
13
        rv = SECFailure;
2998
287k
    } else if ((unsigned int)count < ss->sec.ci.sendBuf.len) {
2999
        /* short write should never happen */
3000
0
        PORT_Assert((unsigned int)count >= ss->sec.ci.sendBuf.len);
3001
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3002
0
        rv = SECFailure;
3003
287k
    } else {
3004
287k
        rv = SECSuccess;
3005
287k
    }
3006
3007
    /* Whether we succeeded or failed, toss the old handshake data. */
3008
287k
    ss->sec.ci.sendBuf.len = 0;
3009
287k
    return rv;
3010
287k
}
3011
3012
/*
3013
 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
3014
 * the remote client sends a negative response to our certificate request.
3015
 * Returns SECFailure if the application has required client auth.
3016
 *         SECSuccess otherwise.
3017
 */
3018
SECStatus
3019
ssl3_HandleNoCertificate(sslSocket *ss)
3020
2.00k
{
3021
2.00k
    ssl3_CleanupPeerCerts(ss);
3022
3023
    /* If the server has required client-auth blindly but doesn't
3024
     * actually look at the certificate it won't know that no
3025
     * certificate was presented so we shutdown the socket to ensure
3026
     * an error.  We only do this if we haven't already completed the
3027
     * first handshake because if we're redoing the handshake we
3028
     * know the server is paying attention to the certificate.
3029
     */
3030
2.00k
    if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
3031
1.98k
        (!ss->firstHsDone &&
3032
172
         (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
3033
19
        PRFileDesc *lower;
3034
3035
19
        ssl_UncacheSessionID(ss);
3036
3037
19
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
3038
2
            SSL3_SendAlert(ss, alert_fatal, certificate_required);
3039
17
        } else {
3040
17
            SSL3_SendAlert(ss, alert_fatal, bad_certificate);
3041
17
        }
3042
3043
19
        lower = ss->fd->lower;
3044
#ifdef _WIN32
3045
        lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
3046
#else
3047
19
        lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
3048
19
#endif
3049
19
        PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
3050
19
        return SECFailure;
3051
19
    }
3052
1.98k
    return SECSuccess;
3053
2.00k
}
3054
3055
/************************************************************************
3056
 * Alerts
3057
 */
3058
3059
/*
3060
** Acquires both handshake and XmitBuf locks.
3061
** Called from: ssl3_IllegalParameter   <-
3062
**              ssl3_HandshakeFailure   <-
3063
**              ssl3_HandleAlert    <- ssl3_HandleRecord.
3064
**              ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
3065
**              ssl3_ConsumeHandshakeVariable <-
3066
**              ssl3_HandleHelloRequest <-
3067
**              ssl3_HandleServerHello  <-
3068
**              ssl3_HandleServerKeyExchange <-
3069
**              ssl3_HandleCertificateRequest <-
3070
**              ssl3_HandleServerHelloDone <-
3071
**              ssl3_HandleClientHello  <-
3072
**              ssl3_HandleV2ClientHello <-
3073
**              ssl3_HandleCertificateVerify <-
3074
**              ssl3_HandleClientKeyExchange <-
3075
**              ssl3_HandleCertificate  <-
3076
**              ssl3_HandleFinished <-
3077
**              ssl3_HandleHandshakeMessage <-
3078
**              ssl3_HandlePostHelloHandshakeMessage <-
3079
**              ssl3_HandleRecord   <-
3080
**
3081
*/
3082
SECStatus
3083
SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
3084
31.4k
{
3085
31.4k
    PRUint8 bytes[2];
3086
31.4k
    SECStatus rv;
3087
31.4k
    PRBool needHsLock = !ssl_HaveSSL3HandshakeLock(ss);
3088
3089
    /* Check that if I need the HS lock I also need the Xmit lock */
3090
31.4k
    PORT_Assert(!needHsLock || !ssl_HaveXmitBufLock(ss));
3091
3092
31.4k
    SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
3093
31.4k
                SSL_GETPID(), ss->fd, level, desc));
3094
3095
31.4k
    bytes[0] = level;
3096
31.4k
    bytes[1] = desc;
3097
3098
31.4k
    if (needHsLock) {
3099
2.98k
        ssl_GetSSL3HandshakeLock(ss);
3100
2.98k
    }
3101
31.4k
    if (level == alert_fatal) {
3102
26.7k
        if (ss->sec.ci.sid) {
3103
21.9k
            ssl_UncacheSessionID(ss);
3104
21.9k
        }
3105
26.7k
    }
3106
3107
31.4k
    rv = tls13_SetAlertCipherSpec(ss);
3108
31.4k
    if (rv != SECSuccess) {
3109
0
        if (needHsLock) {
3110
0
            ssl_ReleaseSSL3HandshakeLock(ss);
3111
0
        }
3112
0
        return rv;
3113
0
    }
3114
3115
31.4k
    ssl_GetXmitBufLock(ss);
3116
31.4k
    rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3117
31.4k
    if (rv == SECSuccess) {
3118
31.4k
        PRInt32 sent;
3119
31.4k
        sent = ssl3_SendRecord(ss, NULL, ssl_ct_alert, bytes, 2,
3120
31.4k
                               (desc == no_certificate) ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
3121
31.4k
        rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
3122
31.4k
    }
3123
31.4k
    if (level == alert_fatal) {
3124
26.7k
        ss->ssl3.fatalAlertSent = PR_TRUE;
3125
26.7k
    }
3126
31.4k
    ssl_ReleaseXmitBufLock(ss);
3127
31.4k
    if (needHsLock) {
3128
2.98k
        ssl_ReleaseSSL3HandshakeLock(ss);
3129
2.98k
    }
3130
31.4k
    if (rv == SECSuccess && ss->alertSentCallback) {
3131
0
        SSLAlert alert = { level, desc };
3132
0
        ss->alertSentCallback(ss->fd, ss->alertSentCallbackArg, &alert);
3133
0
    }
3134
31.4k
    return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
3135
31.4k
}
3136
3137
/*
3138
 * Send illegal_parameter alert.  Set generic error number.
3139
 */
3140
static SECStatus
3141
ssl3_IllegalParameter(sslSocket *ss)
3142
34
{
3143
34
    (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
3144
34
    PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3145
34
                                   : SSL_ERROR_BAD_SERVER);
3146
34
    return SECFailure;
3147
34
}
3148
3149
/*
3150
 * Send handshake_Failure alert.  Set generic error number.
3151
 */
3152
static SECStatus
3153
ssl3_HandshakeFailure(sslSocket *ss)
3154
0
{
3155
0
    (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
3156
0
    PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3157
0
                                   : SSL_ERROR_BAD_SERVER);
3158
0
    return SECFailure;
3159
0
}
3160
3161
void
3162
ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode)
3163
2.51k
{
3164
2.51k
    SSL3AlertDescription desc = bad_certificate;
3165
2.51k
    PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
3166
3167
2.51k
    switch (errCode) {
3168
0
        case SEC_ERROR_LIBRARY_FAILURE:
3169
0
            desc = unsupported_certificate;
3170
0
            break;
3171
0
        case SEC_ERROR_EXPIRED_CERTIFICATE:
3172
0
            desc = certificate_expired;
3173
0
            break;
3174
0
        case SEC_ERROR_REVOKED_CERTIFICATE:
3175
0
            desc = certificate_revoked;
3176
0
            break;
3177
0
        case SEC_ERROR_INADEQUATE_KEY_USAGE:
3178
0
        case SEC_ERROR_INADEQUATE_CERT_TYPE:
3179
0
            desc = certificate_unknown;
3180
0
            break;
3181
0
        case SEC_ERROR_UNTRUSTED_CERT:
3182
0
            desc = isTLS ? access_denied : certificate_unknown;
3183
0
            break;
3184
0
        case SEC_ERROR_UNKNOWN_ISSUER:
3185
0
        case SEC_ERROR_UNTRUSTED_ISSUER:
3186
0
            desc = isTLS ? unknown_ca : certificate_unknown;
3187
0
            break;
3188
0
        case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
3189
0
            desc = isTLS ? unknown_ca : certificate_expired;
3190
0
            break;
3191
3192
0
        case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
3193
0
        case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
3194
0
        case SEC_ERROR_CA_CERT_INVALID:
3195
0
        case SEC_ERROR_BAD_SIGNATURE:
3196
2.51k
        default:
3197
2.51k
            desc = bad_certificate;
3198
2.51k
            break;
3199
2.51k
    }
3200
2.51k
    SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
3201
2.51k
             SSL_GETPID(), ss->fd, errCode));
3202
3203
2.51k
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
3204
2.51k
}
3205
3206
/*
3207
 * Send decode_error alert.  Set generic error number.
3208
 */
3209
SECStatus
3210
ssl3_DecodeError(sslSocket *ss)
3211
4.26k
{
3212
4.26k
    (void)SSL3_SendAlert(ss, alert_fatal,
3213
4.26k
                         ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error
3214
4.26k
                                                               : illegal_parameter);
3215
4.26k
    PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3216
4.26k
                                   : SSL_ERROR_BAD_SERVER);
3217
4.26k
    return SECFailure;
3218
4.26k
}
3219
3220
/* Called from ssl3_HandleRecord.
3221
** Caller must hold both RecvBuf and Handshake locks.
3222
*/
3223
static SECStatus
3224
ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
3225
69.0k
{
3226
69.0k
    SSL3AlertLevel level;
3227
69.0k
    SSL3AlertDescription desc;
3228
69.0k
    int error;
3229
3230
69.0k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3231
69.0k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3232
3233
69.0k
    SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
3234
3235
69.0k
    if (buf->len != 2) {
3236
422
        (void)ssl3_DecodeError(ss);
3237
422
        PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
3238
422
        return SECFailure;
3239
422
    }
3240
68.6k
    level = (SSL3AlertLevel)buf->buf[0];
3241
68.6k
    desc = (SSL3AlertDescription)buf->buf[1];
3242
68.6k
    buf->len = 0;
3243
68.6k
    SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
3244
68.6k
                SSL_GETPID(), ss->fd, level, desc));
3245
3246
68.6k
    if (ss->alertReceivedCallback) {
3247
0
        SSLAlert alert = { level, desc };
3248
0
        ss->alertReceivedCallback(ss->fd, ss->alertReceivedCallbackArg, &alert);
3249
0
    }
3250
3251
68.6k
    switch (desc) {
3252
36
        case close_notify:
3253
36
            ss->recvdCloseNotify = 1;
3254
36
            error = SSL_ERROR_CLOSE_NOTIFY_ALERT;
3255
36
            break;
3256
1.40k
        case unexpected_message:
3257
1.40k
            error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
3258
1.40k
            break;
3259
1.32k
        case bad_record_mac:
3260
1.32k
            error = SSL_ERROR_BAD_MAC_ALERT;
3261
1.32k
            break;
3262
1.32k
        case decryption_failed_RESERVED:
3263
1.32k
            error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
3264
1.32k
            break;
3265
1.06k
        case record_overflow:
3266
1.06k
            error = SSL_ERROR_RECORD_OVERFLOW_ALERT;
3267
1.06k
            break;
3268
1.48k
        case decompression_failure:
3269
1.48k
            error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
3270
1.48k
            break;
3271
1.19k
        case handshake_failure:
3272
1.19k
            error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
3273
1.19k
            break;
3274
2.00k
        case no_certificate:
3275
2.00k
            error = SSL_ERROR_NO_CERTIFICATE;
3276
2.00k
            break;
3277
1.43k
        case certificate_required:
3278
1.43k
            error = SSL_ERROR_RX_CERTIFICATE_REQUIRED_ALERT;
3279
1.43k
            break;
3280
998
        case bad_certificate:
3281
998
            error = SSL_ERROR_BAD_CERT_ALERT;
3282
998
            break;
3283
1.01k
        case unsupported_certificate:
3284
1.01k
            error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;
3285
1.01k
            break;
3286
1.16k
        case certificate_revoked:
3287
1.16k
            error = SSL_ERROR_REVOKED_CERT_ALERT;
3288
1.16k
            break;
3289
1.82k
        case certificate_expired:
3290
1.82k
            error = SSL_ERROR_EXPIRED_CERT_ALERT;
3291
1.82k
            break;
3292
1.18k
        case certificate_unknown:
3293
1.18k
            error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
3294
1.18k
            break;
3295
1.58k
        case illegal_parameter:
3296
1.58k
            error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;
3297
1.58k
            break;
3298
892
        case inappropriate_fallback:
3299
892
            error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
3300
892
            break;
3301
3302
        /* All alerts below are TLS only. */
3303
1.16k
        case unknown_ca:
3304
1.16k
            error = SSL_ERROR_UNKNOWN_CA_ALERT;
3305
1.16k
            break;
3306
1.17k
        case access_denied:
3307
1.17k
            error = SSL_ERROR_ACCESS_DENIED_ALERT;
3308
1.17k
            break;
3309
1.14k
        case decode_error:
3310
1.14k
            error = SSL_ERROR_DECODE_ERROR_ALERT;
3311
1.14k
            break;
3312
1.53k
        case decrypt_error:
3313
1.53k
            error = SSL_ERROR_DECRYPT_ERROR_ALERT;
3314
1.53k
            break;
3315
1.02k
        case export_restriction:
3316
1.02k
            error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
3317
1.02k
            break;
3318
1.04k
        case protocol_version:
3319
1.04k
            error = SSL_ERROR_PROTOCOL_VERSION_ALERT;
3320
1.04k
            break;
3321
19.9k
        case insufficient_security:
3322
19.9k
            error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
3323
19.9k
            break;
3324
1.12k
        case internal_error:
3325
1.12k
            error = SSL_ERROR_INTERNAL_ERROR_ALERT;
3326
1.12k
            break;
3327
1.46k
        case user_canceled:
3328
1.46k
            error = SSL_ERROR_USER_CANCELED_ALERT;
3329
1.46k
            break;
3330
1.04k
        case no_renegotiation:
3331
1.04k
            error = SSL_ERROR_NO_RENEGOTIATION_ALERT;
3332
1.04k
            break;
3333
3334
        /* Alerts for TLS client hello extensions */
3335
1.25k
        case missing_extension:
3336
1.25k
            error = SSL_ERROR_MISSING_EXTENSION_ALERT;
3337
1.25k
            break;
3338
958
        case unsupported_extension:
3339
958
            error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT;
3340
958
            break;
3341
2.48k
        case certificate_unobtainable:
3342
2.48k
            error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT;
3343
2.48k
            break;
3344
1.21k
        case unrecognized_name:
3345
1.21k
            error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
3346
1.21k
            break;
3347
7.39k
        case bad_certificate_status_response:
3348
7.39k
            error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT;
3349
7.39k
            break;
3350
1.23k
        case bad_certificate_hash_value:
3351
1.23k
            error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT;
3352
1.23k
            break;
3353
973
        case no_application_protocol:
3354
973
            error = SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL;
3355
973
            break;
3356
934
        case ech_required:
3357
934
            error = SSL_ERROR_ECH_REQUIRED_ALERT;
3358
934
            break;
3359
1.61k
        default:
3360
1.61k
            error = SSL_ERROR_RX_UNKNOWN_ALERT;
3361
1.61k
            break;
3362
68.6k
    }
3363
68.6k
    if ((ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) &&
3364
720
        (ss->ssl3.hs.ws != wait_server_hello)) {
3365
        /* TLS 1.3 requires all but "end of data" alerts to be
3366
         * treated as fatal. */
3367
439
        switch (desc) {
3368
10
            case close_notify:
3369
428
            case user_canceled:
3370
428
                break;
3371
11
            default:
3372
11
                level = alert_fatal;
3373
439
        }
3374
439
    }
3375
68.6k
    if (level == alert_fatal) {
3376
127
        ssl_UncacheSessionID(ss);
3377
127
        if ((ss->ssl3.hs.ws == wait_server_hello) &&
3378
69
            (desc == handshake_failure)) {
3379
            /* XXX This is a hack.  We're assuming that any handshake failure
3380
             * XXX on the client hello is a failure to match ciphers.
3381
             */
3382
6
            error = SSL_ERROR_NO_CYPHER_OVERLAP;
3383
6
        }
3384
127
        PORT_SetError(error);
3385
127
        return SECFailure;
3386
127
    }
3387
68.4k
    if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
3388
        /* I'm a server. I've requested a client cert. He hasn't got one. */
3389
525
        SECStatus rv;
3390
3391
525
        PORT_Assert(ss->sec.isServer);
3392
525
        ss->ssl3.hs.ws = wait_client_key;
3393
525
        rv = ssl3_HandleNoCertificate(ss);
3394
525
        return rv;
3395
525
    }
3396
67.9k
    return SECSuccess;
3397
68.4k
}
3398
3399
/*
3400
 * Change Cipher Specs
3401
 * Called from ssl3_HandleServerHelloDone,
3402
 *             ssl3_HandleClientHello,
3403
 * and         ssl3_HandleFinished
3404
 *
3405
 * Acquires and releases spec write lock, to protect switching the current
3406
 * and pending write spec pointers.
3407
 */
3408
3409
SECStatus
3410
ssl3_SendChangeCipherSpecsInt(sslSocket *ss)
3411
101k
{
3412
101k
    PRUint8 change = change_cipher_spec_choice;
3413
101k
    SECStatus rv;
3414
3415
101k
    SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
3416
101k
                SSL_GETPID(), ss->fd));
3417
3418
101k
    rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3419
101k
    if (rv != SECSuccess) {
3420
0
        return SECFailure; /* error code set by ssl3_FlushHandshake */
3421
0
    }
3422
3423
101k
    if (!IS_DTLS(ss)) {
3424
98.5k
        PRInt32 sent;
3425
98.5k
        sent = ssl3_SendRecord(ss, NULL, ssl_ct_change_cipher_spec,
3426
98.5k
                               &change, 1, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3427
98.5k
        if (sent < 0) {
3428
0
            return SECFailure; /* error code set by ssl3_SendRecord */
3429
0
        }
3430
98.5k
    } else {
3431
3.39k
        rv = dtls_QueueMessage(ss, ssl_ct_change_cipher_spec, &change, 1);
3432
3.39k
        if (rv != SECSuccess) {
3433
0
            return SECFailure;
3434
0
        }
3435
3.39k
    }
3436
101k
    return SECSuccess;
3437
101k
}
3438
3439
static SECStatus
3440
ssl3_SendChangeCipherSpecs(sslSocket *ss)
3441
101k
{
3442
101k
    SECStatus rv;
3443
3444
101k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3445
101k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3446
3447
101k
    rv = ssl3_SendChangeCipherSpecsInt(ss);
3448
101k
    if (rv != SECSuccess) {
3449
0
        return rv; /* Error code set. */
3450
0
    }
3451
3452
    /* swap the pending and current write specs. */
3453
101k
    ssl_GetSpecWriteLock(ss); /**************************************/
3454
3455
101k
    ssl_CipherSpecRelease(ss->ssl3.cwSpec);
3456
101k
    ss->ssl3.cwSpec = ss->ssl3.pwSpec;
3457
101k
    ss->ssl3.pwSpec = NULL;
3458
3459
101k
    SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
3460
101k
                SSL_GETPID(), ss->fd));
3461
3462
    /* With DTLS, we need to set a holddown timer in case the final
3463
     * message got lost */
3464
101k
    if (IS_DTLS(ss) && ss->ssl3.crSpec->epoch == ss->ssl3.cwSpec->epoch) {
3465
221
        rv = dtls_StartHolddownTimer(ss);
3466
221
    }
3467
101k
    ssl_ReleaseSpecWriteLock(ss); /**************************************/
3468
3469
101k
    return rv;
3470
101k
}
3471
3472
/* Called from ssl3_HandleRecord.
3473
** Caller must hold both RecvBuf and Handshake locks.
3474
*
3475
* Acquires and releases spec write lock, to protect switching the current
3476
* and pending write spec pointers.
3477
*/
3478
static SECStatus
3479
ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
3480
99.6k
{
3481
99.6k
    SSL3WaitState ws = ss->ssl3.hs.ws;
3482
99.6k
    SSL3ChangeCipherSpecChoice change;
3483
3484
99.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3485
99.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3486
3487
99.6k
    SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
3488
99.6k
                SSL_GETPID(), ss->fd));
3489
3490
    /* For DTLS: Ignore this if we aren't expecting it.  Don't kill a connection
3491
     *           as a result of receiving trash.
3492
     * For TLS: Maybe ignore, but only after checking format. */
3493
99.6k
    if (ws != wait_change_cipher && IS_DTLS(ss)) {
3494
        /* Ignore this because it's out of order. */
3495
808
        SSL_TRC(3, ("%d: SSL3[%d]: discard out of order "
3496
808
                    "DTLS change_cipher_spec",
3497
808
                    SSL_GETPID(), ss->fd));
3498
808
        buf->len = 0;
3499
808
        return SECSuccess;
3500
808
    }
3501
3502
    /* Handshake messages should not span ChangeCipherSpec. */
3503
98.8k
    if (ss->ssl3.hs.header_bytes) {
3504
91
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3505
91
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3506
91
        return SECFailure;
3507
91
    }
3508
98.7k
    if (buf->len != 1) {
3509
316
        (void)ssl3_DecodeError(ss);
3510
316
        PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3511
316
        return SECFailure;
3512
316
    }
3513
98.4k
    change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
3514
98.4k
    if (change != change_cipher_spec_choice) {
3515
        /* illegal_parameter is correct here for both SSL3 and TLS. */
3516
34
        (void)ssl3_IllegalParameter(ss);
3517
34
        PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3518
34
        return SECFailure;
3519
34
    }
3520
3521
98.4k
    buf->len = 0;
3522
98.4k
    if (ws != wait_change_cipher) {
3523
        /* Ignore a CCS for TLS 1.3. This only happens if the server sends a
3524
         * HelloRetryRequest.  In other cases, the CCS will fail decryption and
3525
         * will be discarded by ssl3_HandleRecord(). */
3526
628
        if (ws == wait_server_hello &&
3527
568
            ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
3528
566
            ss->ssl3.hs.helloRetry) {
3529
566
            PORT_Assert(!ss->sec.isServer);
3530
566
            return SECSuccess;
3531
566
        }
3532
        /* Note: For a server, we can't test ss->ssl3.hs.helloRetry or
3533
         * ss->version because the server might be stateless (and so it won't
3534
         * have set either value yet). Set a flag so that at least we will
3535
         * guarantee that the server will treat any ClientHello properly. */
3536
62
        if (ws == wait_client_hello &&
3537
22
            ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3 &&
3538
18
            !ss->ssl3.hs.receivedCcs) {
3539
16
            PORT_Assert(ss->sec.isServer);
3540
16
            ss->ssl3.hs.receivedCcs = PR_TRUE;
3541
16
            return SECSuccess;
3542
16
        }
3543
46
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3544
46
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3545
46
        return SECFailure;
3546
62
    }
3547
3548
97.8k
    SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
3549
97.8k
                SSL_GETPID(), ss->fd));
3550
97.8k
    ssl_GetSpecWriteLock(ss); /*************************************/
3551
97.8k
    PORT_Assert(ss->ssl3.prSpec);
3552
97.8k
    ssl_CipherSpecRelease(ss->ssl3.crSpec);
3553
97.8k
    ss->ssl3.crSpec = ss->ssl3.prSpec;
3554
97.8k
    ss->ssl3.prSpec = NULL;
3555
97.8k
    ssl_ReleaseSpecWriteLock(ss); /*************************************/
3556
3557
97.8k
    ss->ssl3.hs.ws = wait_finished;
3558
97.8k
    return SECSuccess;
3559
98.4k
}
3560
3561
static CK_MECHANISM_TYPE
3562
ssl3_GetMgfMechanismByHashType(SSLHashType hash)
3563
3.51k
{
3564
3.51k
    switch (hash) {
3565
2.36k
        case ssl_hash_sha256:
3566
2.36k
            return CKG_MGF1_SHA256;
3567
474
        case ssl_hash_sha384:
3568
474
            return CKG_MGF1_SHA384;
3569
683
        case ssl_hash_sha512:
3570
683
            return CKG_MGF1_SHA512;
3571
0
        default:
3572
0
            PORT_Assert(0);
3573
3.51k
    }
3574
0
    return CKG_MGF1_SHA256;
3575
3.51k
}
3576
3577
/* Function valid for >= TLS 1.2, only. */
3578
static CK_MECHANISM_TYPE
3579
ssl3_GetHashMechanismByHashType(SSLHashType hashType)
3580
324k
{
3581
324k
    switch (hashType) {
3582
683
        case ssl_hash_sha512:
3583
683
            return CKM_SHA512;
3584
74.1k
        case ssl_hash_sha384:
3585
74.1k
            return CKM_SHA384;
3586
32.6k
        case ssl_hash_sha256:
3587
249k
        case ssl_hash_none:
3588
            /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
3589
249k
            return CKM_SHA256;
3590
0
        case ssl_hash_sha1:
3591
0
            return CKM_SHA_1;
3592
0
        default:
3593
0
            PORT_Assert(0);
3594
324k
    }
3595
0
    return CKM_SHA256;
3596
324k
}
3597
3598
/* Function valid for >= TLS 1.2, only. */
3599
static CK_MECHANISM_TYPE
3600
ssl3_GetPrfHashMechanism(sslSocket *ss)
3601
321k
{
3602
321k
    return ssl3_GetHashMechanismByHashType(ss->ssl3.hs.suite_def->prf_hash);
3603
321k
}
3604
3605
static SSLHashType
3606
ssl3_GetSuitePrfHash(sslSocket *ss)
3607
133k
{
3608
    /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
3609
133k
    if (ss->ssl3.hs.suite_def->prf_hash == ssl_hash_none) {
3610
86.8k
        return ssl_hash_sha256;
3611
86.8k
    }
3612
46.1k
    return ss->ssl3.hs.suite_def->prf_hash;
3613
133k
}
3614
3615
/* This method completes the derivation of the MS from the PMS.
3616
**
3617
** 1. Derive the MS, if possible, else return an error.
3618
**
3619
** 2. Check the version if |pms_version| is non-zero and if wrong,
3620
**    return an error.
3621
**
3622
** 3. If |msp| is nonzero, return MS in |*msp|.
3623
3624
** Called from:
3625
**   ssl3_ComputeMasterSecretInt
3626
**   tls_ComputeExtendedMasterSecretInt
3627
*/
3628
static SECStatus
3629
ssl3_ComputeMasterSecretFinish(sslSocket *ss,
3630
                               CK_MECHANISM_TYPE master_derive,
3631
                               CK_MECHANISM_TYPE key_derive,
3632
                               CK_VERSION *pms_version,
3633
                               SECItem *params, CK_FLAGS keyFlags,
3634
                               PK11SymKey *pms, PK11SymKey **msp)
3635
157k
{
3636
157k
    PK11SymKey *ms = NULL;
3637
3638
157k
    ms = PK11_DeriveWithFlags(pms, master_derive,
3639
157k
                              params, key_derive,
3640
157k
                              CKA_DERIVE, 0, keyFlags);
3641
157k
    if (!ms) {
3642
3.79k
        ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3643
3.79k
        return SECFailure;
3644
3.79k
    }
3645
3646
153k
    if (pms_version && ss->opt.detectRollBack) {
3647
99.1k
        SSL3ProtocolVersion client_version;
3648
99.1k
        client_version = pms_version->major << 8 | pms_version->minor;
3649
3650
99.1k
        if (IS_DTLS(ss)) {
3651
8.92k
            client_version = dtls_DTLSVersionToTLSVersion(client_version);
3652
8.92k
        }
3653
3654
99.1k
        if (client_version != ss->clientHelloVersion) {
3655
            /* Destroy MS.  Version roll-back detected. */
3656
351
            PK11_FreeSymKey(ms);
3657
351
            ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3658
351
            return SECFailure;
3659
351
        }
3660
99.1k
    }
3661
3662
153k
    if (msp) {
3663
112k
        *msp = ms;
3664
112k
    } else {
3665
40.0k
        PK11_FreeSymKey(ms);
3666
40.0k
    }
3667
3668
153k
    return SECSuccess;
3669
153k
}
3670
3671
/*  Compute the ordinary (pre draft-ietf-tls-session-hash) master
3672
 ** secret and return it in |*msp|.
3673
 **
3674
 ** Called from: ssl3_ComputeMasterSecret
3675
 */
3676
static SECStatus
3677
ssl3_ComputeMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3678
                            PK11SymKey **msp)
3679
148k
{
3680
148k
    PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
3681
148k
    PRBool isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3682
    /*
3683
     * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
3684
     * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
3685
     * data into a 48-byte value, and does not expect to return the version.
3686
     */
3687
148k
    PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
3688
145k
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh) ||
3689
96.6k
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh_hybrid) ||
3690
96.6k
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_kem));
3691
148k
    CK_MECHANISM_TYPE master_derive;
3692
148k
    CK_MECHANISM_TYPE key_derive;
3693
148k
    SECItem params;
3694
148k
    CK_FLAGS keyFlags;
3695
148k
    CK_VERSION pms_version;
3696
148k
    CK_VERSION *pms_version_ptr = NULL;
3697
    /* master_params may be used as a CK_SSL3_MASTER_KEY_DERIVE_PARAMS */
3698
148k
    CK_TLS12_MASTER_KEY_DERIVE_PARAMS master_params;
3699
148k
    unsigned int master_params_len;
3700
3701
    /* if we are using TLS and we aren't using the extended master secret,
3702
     * and SEC_OID_TLS_REQUIRE_EMS policy is true, fail. The caller will
3703
     * send an alert (eventually). In the RSA Server case, the alert
3704
     * won't happen until Finish time because the upper level code
3705
     * can't tell a difference between this failure and an RSA decrypt
3706
     * failure, so it will proceed with a faux key */
3707
148k
    if (isTLS) {
3708
148k
        PRUint32 policy;
3709
148k
        SECStatus rv;
3710
3711
        /* first fetch the policy for this algorithm */
3712
148k
        rv = NSS_GetAlgorithmPolicy(SEC_OID_TLS_REQUIRE_EMS, &policy);
3713
        /* we only look at the policy if we can fetch it. */
3714
148k
        if ((rv == SECSuccess) && (policy & NSS_USE_ALG_IN_SSL_KX)) {
3715
            /* just set the error, we don't want to map any errors
3716
             * set by NSS_GetAlgorithmPolicy here */
3717
0
            PORT_SetError(SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET);
3718
0
            return SECFailure;
3719
0
        }
3720
148k
    }
3721
3722
148k
    if (isTLS12) {
3723
107k
        if (isDH)
3724
22.1k
            master_derive = CKM_TLS12_MASTER_KEY_DERIVE_DH;
3725
85.0k
        else
3726
85.0k
            master_derive = CKM_TLS12_MASTER_KEY_DERIVE;
3727
107k
        key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3728
107k
        keyFlags = CKF_SIGN | CKF_VERIFY;
3729
107k
    } else if (isTLS) {
3730
40.8k
        if (isDH)
3731
29.3k
            master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
3732
11.5k
        else
3733
11.5k
            master_derive = CKM_TLS_MASTER_KEY_DERIVE;
3734
40.8k
        key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3735
40.8k
        keyFlags = CKF_SIGN | CKF_VERIFY;
3736
40.8k
    } else {
3737
0
        if (isDH)
3738
0
            master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
3739
0
        else
3740
0
            master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
3741
0
        key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3742
0
        keyFlags = 0;
3743
0
    }
3744
3745
148k
    if (!isDH) {
3746
96.6k
        pms_version_ptr = &pms_version;
3747
96.6k
    }
3748
3749
148k
    master_params.pVersion = pms_version_ptr;
3750
148k
    master_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
3751
148k
    master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3752
148k
    master_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
3753
148k
    master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3754
148k
    if (isTLS12) {
3755
107k
        master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3756
107k
        master_params_len = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS);
3757
107k
    } else {
3758
        /* prfHashMechanism is not relevant with this PRF */
3759
40.8k
        master_params_len = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS);
3760
40.8k
    }
3761
3762
148k
    params.data = (unsigned char *)&master_params;
3763
148k
    params.len = master_params_len;
3764
3765
148k
    return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3766
148k
                                          pms_version_ptr, &params,
3767
148k
                                          keyFlags, pms, msp);
3768
148k
}
3769
3770
/* Compute the draft-ietf-tls-session-hash master
3771
** secret and return it in |*msp|.
3772
**
3773
** Called from: ssl3_ComputeMasterSecret
3774
*/
3775
static SECStatus
3776
tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3777
                                   PK11SymKey **msp)
3778
9.15k
{
3779
9.15k
    ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3780
9.15k
    CK_TLS12_EXTENDED_MASTER_KEY_DERIVE_PARAMS extended_master_params;
3781
9.15k
    SSL3Hashes hashes;
3782
3783
    /*
3784
     * Determine whether to use the DH/ECDH or RSA derivation modes.
3785
     */
3786
    /*
3787
     * TODO(ekr@rtfm.com): Verify that the slot can handle this key expansion
3788
     * mode. Bug 1198298 */
3789
9.15k
    PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
3790
9.07k
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh) ||
3791
6.30k
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh_hybrid) ||
3792
6.30k
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_kem));
3793
9.15k
    CK_MECHANISM_TYPE master_derive;
3794
9.15k
    CK_MECHANISM_TYPE key_derive;
3795
9.15k
    SECItem params;
3796
9.15k
    const CK_FLAGS keyFlags = CKF_SIGN | CKF_VERIFY;
3797
9.15k
    CK_VERSION pms_version;
3798
9.15k
    CK_VERSION *pms_version_ptr = NULL;
3799
9.15k
    SECStatus rv;
3800
3801
9.15k
    rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0);
3802
9.15k
    if (rv != SECSuccess) {
3803
0
        PORT_Assert(0); /* Should never fail */
3804
0
        ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3805
0
        return SECFailure;
3806
0
    }
3807
3808
9.15k
    if (isDH) {
3809
2.84k
        master_derive = CKM_TLS12_EXTENDED_MASTER_KEY_DERIVE_DH;
3810
6.30k
    } else {
3811
6.30k
        master_derive = CKM_TLS12_EXTENDED_MASTER_KEY_DERIVE;
3812
6.30k
        pms_version_ptr = &pms_version;
3813
6.30k
    }
3814
3815
9.15k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
3816
        /* TLS 1.2+ */
3817
6.55k
        extended_master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3818
6.55k
        key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3819
6.55k
    } else {
3820
        /* TLS < 1.2 */
3821
2.59k
        extended_master_params.prfHashMechanism = CKM_TLS_PRF;
3822
2.59k
        key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3823
2.59k
    }
3824
3825
9.15k
    extended_master_params.pVersion = pms_version_ptr;
3826
9.15k
    extended_master_params.pSessionHash = hashes.u.raw;
3827
9.15k
    extended_master_params.ulSessionHashLen = hashes.len;
3828
3829
9.15k
    params.data = (unsigned char *)&extended_master_params;
3830
9.15k
    params.len = sizeof extended_master_params;
3831
3832
9.15k
    return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3833
9.15k
                                          pms_version_ptr, &params,
3834
9.15k
                                          keyFlags, pms, msp);
3835
9.15k
}
3836
3837
/* Wrapper method to compute the master secret and return it in |*msp|.
3838
**
3839
** Called from ssl3_ComputeMasterSecret
3840
*/
3841
static SECStatus
3842
ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
3843
                         PK11SymKey **msp)
3844
157k
{
3845
157k
    PORT_Assert(pms != NULL);
3846
157k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3847
3848
157k
    if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
3849
9.15k
        return tls_ComputeExtendedMasterSecretInt(ss, pms, msp);
3850
148k
    } else {
3851
148k
        return ssl3_ComputeMasterSecretInt(ss, pms, msp);
3852
148k
    }
3853
157k
}
3854
3855
/*
3856
 * Derive encryption and MAC Keys (and IVs) from master secret
3857
 * Sets a useful error code when returning SECFailure.
3858
 *
3859
 * Called only from ssl3_InitPendingCipherSpec(),
3860
 * which in turn is called from
3861
 *              ssl3_SendRSAClientKeyExchange    (for Full handshake)
3862
 *              ssl3_SendDHClientKeyExchange     (for Full handshake)
3863
 *              ssl3_HandleClientKeyExchange    (for Full handshake)
3864
 *              ssl3_HandleServerHello          (for session restart)
3865
 *              ssl3_HandleClientHello          (for session restart)
3866
 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
3867
 * ssl3_InitPendingCipherSpec does that.
3868
 *
3869
 */
3870
static SECStatus
3871
ssl3_DeriveConnectionKeys(sslSocket *ss, PK11SymKey *masterSecret)
3872
112k
{
3873
112k
    ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3874
112k
    ssl3CipherSpec *prSpec = ss->ssl3.prSpec;
3875
112k
    ssl3CipherSpec *clientSpec;
3876
112k
    ssl3CipherSpec *serverSpec;
3877
112k
    PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
3878
112k
    PRBool isTLS12 =
3879
112k
        (PRBool)(isTLS && ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3880
112k
    const ssl3BulkCipherDef *cipher_def = pwSpec->cipherDef;
3881
112k
    PK11SlotInfo *slot = NULL;
3882
112k
    PK11SymKey *derivedKeyHandle = NULL;
3883
112k
    void *pwArg = ss->pkcs11PinArg;
3884
112k
    int keySize;
3885
112k
    CK_TLS12_KEY_MAT_PARAMS key_material_params; /* may be used as a
3886
                                                  * CK_SSL3_KEY_MAT_PARAMS */
3887
112k
    unsigned int key_material_params_len;
3888
112k
    CK_SSL3_KEY_MAT_OUT returnedKeys;
3889
112k
    CK_MECHANISM_TYPE key_derive;
3890
112k
    CK_MECHANISM_TYPE bulk_mechanism;
3891
112k
    SSLCipherAlgorithm calg;
3892
112k
    SECItem params;
3893
112k
    PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == ssl_calg_null);
3894
3895
112k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3896
112k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3897
112k
    PORT_Assert(masterSecret);
3898
3899
    /* These functions operate in terms of who is writing specs. */
3900
112k
    if (ss->sec.isServer) {
3901
67.6k
        clientSpec = prSpec;
3902
67.6k
        serverSpec = pwSpec;
3903
67.6k
    } else {
3904
45.3k
        clientSpec = pwSpec;
3905
45.3k
        serverSpec = prSpec;
3906
45.3k
    }
3907
3908
    /*
3909
     * generate the key material
3910
     */
3911
112k
    if (cipher_def->type == type_block &&
3912
83.6k
        ss->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
3913
        /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
3914
53.9k
        key_material_params.ulIVSizeInBits = 0;
3915
53.9k
        PORT_Memset(clientSpec->keyMaterial.iv, 0, cipher_def->iv_size);
3916
53.9k
        PORT_Memset(serverSpec->keyMaterial.iv, 0, cipher_def->iv_size);
3917
53.9k
    }
3918
3919
112k
    key_material_params.bIsExport = PR_FALSE;
3920
112k
    key_material_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
3921
112k
    key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3922
112k
    key_material_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
3923
112k
    key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3924
112k
    key_material_params.pReturnedKeyMaterial = &returnedKeys;
3925
3926
112k
    if (skipKeysAndIVs) {
3927
15.2k
        keySize = 0;
3928
15.2k
        returnedKeys.pIVClient = NULL;
3929
15.2k
        returnedKeys.pIVServer = NULL;
3930
15.2k
        key_material_params.ulKeySizeInBits = 0;
3931
15.2k
        key_material_params.ulIVSizeInBits = 0;
3932
97.6k
    } else {
3933
97.6k
        keySize = cipher_def->key_size;
3934
97.6k
        returnedKeys.pIVClient = clientSpec->keyMaterial.iv;
3935
97.6k
        returnedKeys.pIVServer = serverSpec->keyMaterial.iv;
3936
97.6k
        key_material_params.ulKeySizeInBits = cipher_def->secret_key_size * BPB;
3937
97.6k
        key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB;
3938
97.6k
    }
3939
112k
    key_material_params.ulMacSizeInBits = pwSpec->macDef->mac_size * BPB;
3940
3941
112k
    calg = cipher_def->calg;
3942
112k
    bulk_mechanism = ssl3_Alg2Mech(calg);
3943
3944
112k
    if (isTLS12) {
3945
75.3k
        key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3946
75.3k
        key_material_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3947
75.3k
        key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS);
3948
75.3k
    } else if (isTLS) {
3949
37.5k
        key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3950
37.5k
        key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
3951
37.5k
    } else {
3952
0
        key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3953
0
        key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
3954
0
    }
3955
3956
112k
    params.data = (unsigned char *)&key_material_params;
3957
112k
    params.len = key_material_params_len;
3958
3959
    /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
3960
     * DERIVE by DEFAULT */
3961
112k
    derivedKeyHandle = PK11_Derive(masterSecret, key_derive, &params,
3962
112k
                                   bulk_mechanism, CKA_ENCRYPT, keySize);
3963
112k
    if (!derivedKeyHandle) {
3964
0
        ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3965
0
        return SECFailure;
3966
0
    }
3967
    /* we really should use the actual mac'ing mechanism here, but we
3968
     * don't because these types are used to map keytype anyway and both
3969
     * mac's map to the same keytype.
3970
     */
3971
112k
    slot = PK11_GetSlotFromKey(derivedKeyHandle);
3972
3973
112k
    PK11_FreeSlot(slot); /* slot is held until the key is freed */
3974
112k
    clientSpec->keyMaterial.macKey =
3975
112k
        PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3976
112k
                              CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret,
3977
112k
                              PR_TRUE, pwArg);
3978
112k
    if (clientSpec->keyMaterial.macKey == NULL) {
3979
0
        goto loser; /* loser sets err */
3980
0
    }
3981
112k
    serverSpec->keyMaterial.macKey =
3982
112k
        PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3983
112k
                              CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret,
3984
112k
                              PR_TRUE, pwArg);
3985
112k
    if (serverSpec->keyMaterial.macKey == NULL) {
3986
0
        goto loser; /* loser sets err */
3987
0
    }
3988
112k
    if (!skipKeysAndIVs) {
3989
97.6k
        clientSpec->keyMaterial.key =
3990
97.6k
            PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3991
97.6k
                                  bulk_mechanism, returnedKeys.hClientKey,
3992
97.6k
                                  PR_TRUE, pwArg);
3993
97.6k
        if (clientSpec->keyMaterial.key == NULL) {
3994
0
            goto loser; /* loser sets err */
3995
0
        }
3996
97.6k
        serverSpec->keyMaterial.key =
3997
97.6k
            PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3998
97.6k
                                  bulk_mechanism, returnedKeys.hServerKey,
3999
97.6k
                                  PR_TRUE, pwArg);
4000
97.6k
        if (serverSpec->keyMaterial.key == NULL) {
4001
0
            goto loser; /* loser sets err */
4002
0
        }
4003
97.6k
    }
4004
112k
    PK11_FreeSymKey(derivedKeyHandle);
4005
112k
    return SECSuccess;
4006
4007
0
loser:
4008
0
    PK11_FreeSymKey(derivedKeyHandle);
4009
0
    ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
4010
0
    return SECFailure;
4011
112k
}
4012
4013
void
4014
ssl3_CoalesceEchHandshakeHashes(sslSocket *ss)
4015
1.20k
{
4016
    /* |sha| contains the CHOuter transcript, which is the singular
4017
     * transcript if not doing ECH. If the server responded with 1.2,
4018
     * contexts are not yet initialized. */
4019
1.20k
    if (ss->ssl3.hs.echAccepted) {
4020
0
        if (ss->ssl3.hs.sha) {
4021
0
            PORT_Assert(ss->ssl3.hs.shaEchInner);
4022
0
            PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
4023
0
            ss->ssl3.hs.sha = ss->ssl3.hs.shaEchInner;
4024
0
            ss->ssl3.hs.shaEchInner = NULL;
4025
0
        }
4026
1.20k
    } else {
4027
1.20k
        if (ss->ssl3.hs.shaEchInner) {
4028
531
            PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
4029
531
            ss->ssl3.hs.shaEchInner = NULL;
4030
531
        }
4031
1.20k
    }
4032
1.20k
}
4033
4034
/* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
4035
 * buffered messages in ss->ssl3.hs.messages. Called from
4036
 * ssl3_NegotiateCipherSuite(), tls13_HandleClientHelloPart2(),
4037
 * and ssl3_HandleServerHello. */
4038
SECStatus
4039
ssl3_InitHandshakeHashes(sslSocket *ss)
4040
141k
{
4041
141k
    SSL_TRC(30, ("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
4042
4043
141k
    PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
4044
141k
    if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
4045
94.1k
        ss->ssl3.hs.hashType = handshake_hash_record;
4046
94.1k
    } else {
4047
47.6k
        PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha);
4048
        /*
4049
         * note: We should probably lookup an SSL3 slot for these
4050
         * handshake hashes in hopes that we wind up with the same slots
4051
         * that the master secret will wind up in ...
4052
         */
4053
47.6k
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
4054
            /* determine the hash from the prf */
4055
5.54k
            const SECOidData *hash_oid =
4056
5.54k
                SECOID_FindOIDByMechanism(ssl3_GetPrfHashMechanism(ss));
4057
4058
            /* Get the PKCS #11 mechanism for the Hash from the cipher suite (prf_hash)
4059
             * Convert that to the OidTag. We can then use that OidTag to create our
4060
             * PK11Context */
4061
5.54k
            PORT_Assert(hash_oid != NULL);
4062
5.54k
            if (hash_oid == NULL) {
4063
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4064
0
                return SECFailure;
4065
0
            }
4066
4067
5.54k
            ss->ssl3.hs.sha = PK11_CreateDigestContext(hash_oid->offset);
4068
5.54k
            if (ss->ssl3.hs.sha == NULL) {
4069
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4070
0
                return SECFailure;
4071
0
            }
4072
5.54k
            ss->ssl3.hs.hashType = handshake_hash_single;
4073
5.54k
            if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
4074
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4075
0
                return SECFailure;
4076
0
            }
4077
4078
            /* Transcript hash used on ECH client. */
4079
5.54k
            if (!ss->sec.isServer && ss->ssl3.hs.echHpkeCtx) {
4080
627
                ss->ssl3.hs.shaEchInner = PK11_CreateDigestContext(hash_oid->offset);
4081
627
                if (ss->ssl3.hs.shaEchInner == NULL) {
4082
0
                    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4083
0
                    return SECFailure;
4084
0
                }
4085
627
                if (PK11_DigestBegin(ss->ssl3.hs.shaEchInner) != SECSuccess) {
4086
0
                    ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4087
0
                    return SECFailure;
4088
0
                }
4089
627
            }
4090
42.0k
        } else {
4091
            /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
4092
             * created successfully. */
4093
42.0k
            ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
4094
42.0k
            if (ss->ssl3.hs.md5 == NULL) {
4095
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4096
0
                return SECFailure;
4097
0
            }
4098
42.0k
            ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
4099
42.0k
            if (ss->ssl3.hs.sha == NULL) {
4100
0
                PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
4101
0
                ss->ssl3.hs.md5 = NULL;
4102
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4103
0
                return SECFailure;
4104
0
            }
4105
42.0k
            ss->ssl3.hs.hashType = handshake_hash_combo;
4106
4107
42.0k
            if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
4108
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4109
0
                return SECFailure;
4110
0
            }
4111
42.0k
            if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
4112
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4113
0
                return SECFailure;
4114
0
            }
4115
42.0k
        }
4116
47.6k
    }
4117
4118
141k
    if (ss->ssl3.hs.hashType != handshake_hash_record &&
4119
47.6k
        ss->ssl3.hs.messages.len > 0) {
4120
        /* When doing ECH, ssl3_UpdateHandshakeHashes will store outer messages
4121
         * into the both the outer and inner transcripts.
4122
         * ssl3_UpdateDefaultHandshakeHashes uses the default context which is
4123
         * the outer when doing client ECH. For ECH shared-mode or backend
4124
         * servers only the hs.messages buffer is used. */
4125
47.6k
        if (ssl3_UpdateDefaultHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
4126
47.6k
                                              ss->ssl3.hs.messages.len) != SECSuccess) {
4127
0
            return SECFailure;
4128
0
        }
4129
        /* When doing ECH, deriving the accept_confirmation value requires all
4130
         * messages up to and including the ServerHello
4131
         * (see draft-ietf-tls-esni-14, Section 7.2).
4132
         *
4133
         * Don't free the transcript buffer until confirmation calculation. */
4134
47.6k
        if (!ss->ssl3.hs.echHpkeCtx && !ss->opt.enableTls13BackendEch) {
4135
41.2k
            sslBuffer_Clear(&ss->ssl3.hs.messages);
4136
41.2k
        }
4137
47.6k
    }
4138
141k
    if (ss->ssl3.hs.shaEchInner &&
4139
627
        ss->ssl3.hs.echInnerMessages.len > 0) {
4140
627
        if (PK11_DigestOp(ss->ssl3.hs.shaEchInner, ss->ssl3.hs.echInnerMessages.buf,
4141
627
                          ss->ssl3.hs.echInnerMessages.len) != SECSuccess) {
4142
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4143
0
            return SECFailure;
4144
0
        }
4145
627
        if (!ss->ssl3.hs.echHpkeCtx) {
4146
0
            sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
4147
0
        }
4148
627
    }
4149
4150
141k
    return SECSuccess;
4151
141k
}
4152
4153
void
4154
ssl3_RestartHandshakeHashes(sslSocket *ss)
4155
157k
{
4156
157k
    SSL_TRC(30, ("%d: SSL3[%d]: reset handshake hashes",
4157
157k
                 SSL_GETPID(), ss->fd));
4158
157k
    ss->ssl3.hs.hashType = handshake_hash_unknown;
4159
157k
    ss->ssl3.hs.messages.len = 0;
4160
157k
    ss->ssl3.hs.echInnerMessages.len = 0;
4161
157k
    if (ss->ssl3.hs.md5) {
4162
34.2k
        PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
4163
34.2k
        ss->ssl3.hs.md5 = NULL;
4164
34.2k
    }
4165
157k
    if (ss->ssl3.hs.sha) {
4166
34.2k
        PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
4167
34.2k
        ss->ssl3.hs.sha = NULL;
4168
34.2k
    }
4169
157k
    if (ss->ssl3.hs.shaEchInner) {
4170
0
        PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
4171
0
        ss->ssl3.hs.shaEchInner = NULL;
4172
0
    }
4173
157k
    if (ss->ssl3.hs.shaPostHandshake) {
4174
0
        PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
4175
0
        ss->ssl3.hs.shaPostHandshake = NULL;
4176
0
    }
4177
157k
}
4178
4179
/* Add the provided bytes to the handshake hash context. When doing
4180
 * TLS 1.3 ECH, |target| may be provided to specify only the inner/outer
4181
 * transcript, else the input is added to both contexts. This happens
4182
 * only on the client. On the server, only the default context is used. */
4183
SECStatus
4184
ssl3_UpdateHandshakeHashesInt(sslSocket *ss, const unsigned char *b,
4185
                              unsigned int l, sslBuffer *target)
4186
2.93M
{
4187
4188
2.93M
    SECStatus rv = SECSuccess;
4189
2.93M
    PRBool explicit = (target != NULL);
4190
2.93M
    PRBool appendToEchInner = !ss->sec.isServer &&
4191
920k
                              ss->ssl3.hs.echHpkeCtx &&
4192
28.8k
                              !explicit;
4193
2.93M
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4194
2.93M
    PORT_Assert(target != &ss->ssl3.hs.echInnerMessages ||
4195
2.93M
                !ss->sec.isServer);
4196
4197
2.93M
    if (target == NULL) {
4198
        /* Default context. */
4199
2.87M
        target = &ss->ssl3.hs.messages;
4200
2.87M
    }
4201
    /* With TLS 1.3, and versions TLS.1.1 and older, we keep the hash(es)
4202
     * always up to date. However, we must initially buffer the handshake
4203
     * messages, until we know what to do.
4204
     * If ss->ssl3.hs.hashType != handshake_hash_unknown,
4205
     * it means we know what to do. We calculate (hash our input),
4206
     * and we stop appending to the buffer.
4207
     *
4208
     * With TLS 1.2, we always append all handshake messages,
4209
     * and never update the hash, because the hash function we must use for
4210
     * certificate_verify might be different from the hash function we use
4211
     * when signing other handshake hashes. */
4212
2.93M
    if (ss->ssl3.hs.hashType == handshake_hash_unknown ||
4213
2.67M
        ss->ssl3.hs.hashType == handshake_hash_record) {
4214
2.19M
        rv = sslBuffer_Append(target, b, l);
4215
2.19M
        if (rv != SECSuccess) {
4216
0
            return SECFailure;
4217
0
        }
4218
2.19M
        if (appendToEchInner) {
4219
9.69k
            return sslBuffer_Append(&ss->ssl3.hs.echInnerMessages, b, l);
4220
9.69k
        }
4221
2.18M
        return SECSuccess;
4222
2.19M
    }
4223
4224
740k
    PRINT_BUF(90, (ss, "handshake hash input:", b, l));
4225
4226
740k
    if (ss->ssl3.hs.hashType == handshake_hash_single) {
4227
67.2k
        PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
4228
67.2k
        if (target == &ss->ssl3.hs.messages) {
4229
67.2k
            rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
4230
67.2k
            if (rv != SECSuccess) {
4231
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4232
0
                return rv;
4233
0
            }
4234
67.2k
        }
4235
67.2k
        if (ss->ssl3.hs.shaEchInner &&
4236
1.83k
            (target == &ss->ssl3.hs.echInnerMessages || !explicit)) {
4237
1.20k
            rv = PK11_DigestOp(ss->ssl3.hs.shaEchInner, b, l);
4238
1.20k
            if (rv != SECSuccess) {
4239
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4240
0
                return rv;
4241
0
            }
4242
1.20k
        }
4243
672k
    } else if (ss->ssl3.hs.hashType == handshake_hash_combo) {
4244
672k
        rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
4245
672k
        if (rv != SECSuccess) {
4246
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4247
0
            return rv;
4248
0
        }
4249
672k
        rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
4250
672k
        if (rv != SECSuccess) {
4251
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4252
0
            return rv;
4253
0
        }
4254
672k
    }
4255
740k
    return rv;
4256
740k
}
4257
4258
static SECStatus
4259
ssl3_UpdateDefaultHandshakeHashes(sslSocket *ss, const unsigned char *b,
4260
                                  unsigned int l)
4261
57.3k
{
4262
57.3k
    return ssl3_UpdateHandshakeHashesInt(ss, b, l,
4263
57.3k
                                         &ss->ssl3.hs.messages);
4264
57.3k
}
4265
4266
static SECStatus
4267
ssl3_UpdateInnerHandshakeHashes(sslSocket *ss, const unsigned char *b,
4268
                                unsigned int l)
4269
1.34k
{
4270
1.34k
    return ssl3_UpdateHandshakeHashesInt(ss, b, l,
4271
1.34k
                                         &ss->ssl3.hs.echInnerMessages);
4272
1.34k
}
4273
4274
/*
4275
 * Handshake messages
4276
 */
4277
/* Called from  ssl3_InitHandshakeHashes()
4278
**      ssl3_AppendHandshake()
4279
**      ssl3_HandleV2ClientHello()
4280
**      ssl3_HandleHandshakeMessage()
4281
** Caller must hold the ssl3Handshake lock.
4282
*/
4283
SECStatus
4284
ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l)
4285
2.87M
{
4286
2.87M
    return ssl3_UpdateHandshakeHashesInt(ss, b, l, NULL);
4287
2.87M
}
4288
4289
SECStatus
4290
ssl3_UpdatePostHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l)
4291
0
{
4292
0
    SECStatus rv = SECSuccess;
4293
4294
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4295
4296
0
    PRINT_BUF(90, (ss, "post handshake hash input:", b, l));
4297
4298
0
    PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single);
4299
0
    PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
4300
0
    rv = PK11_DigestOp(ss->ssl3.hs.shaPostHandshake, b, l);
4301
0
    if (rv != SECSuccess) {
4302
0
        PORT_SetError(SSL_ERROR_DIGEST_FAILURE);
4303
0
    }
4304
0
    return rv;
4305
0
}
4306
4307
/* The next two functions serve to append the handshake header.
4308
   The first one additionally writes to seqNumberBuffer
4309
   the sequence number of the message we are generating.
4310
   This function is used when generating the keyUpdate message in dtls13_enqueueKeyUpdateMessage.
4311
*/
4312
SECStatus
4313
ssl3_AppendHandshakeHeaderAndStashSeqNum(sslSocket *ss, SSLHandshakeType t, PRUint32 length, PRUint64 *sendMessageSeqOut)
4314
464k
{
4315
464k
    PORT_Assert(t != ssl_hs_client_hello);
4316
464k
    SECStatus rv;
4317
4318
    /* If we already have a message in place, we need to enqueue it.
4319
     * This empties the buffer. This is a convenient place to call
4320
     * dtls_StageHandshakeMessage to mark the message boundary.
4321
     */
4322
464k
    if (IS_DTLS(ss)) {
4323
50.4k
        rv = dtls_StageHandshakeMessage(ss);
4324
50.4k
        if (rv != SECSuccess) {
4325
0
            return rv;
4326
0
        }
4327
50.4k
    }
4328
4329
464k
    SSL_TRC(30, ("%d: SSL3[%d]: append handshake header: type %s",
4330
464k
                 SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
4331
4332
464k
    rv = ssl3_AppendHandshakeNumber(ss, t, 1);
4333
464k
    if (rv != SECSuccess) {
4334
0
        return rv; /* error code set by AppendHandshake, if applicable. */
4335
0
    }
4336
464k
    rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4337
464k
    if (rv != SECSuccess) {
4338
0
        return rv; /* error code set by AppendHandshake, if applicable. */
4339
0
    }
4340
4341
464k
    if (IS_DTLS(ss)) {
4342
        /* RFC 9147. 5.2.  DTLS Handshake Message Format.
4343
         * In DTLS 1.3, the message transcript is computed over the original TLS
4344
         * 1.3-style Handshake messages without the message_seq,
4345
         * fragment_offset, and fragment_length values.  Note that this is a
4346
         * change from DTLS 1.2 where those values were included in the transcript. */
4347
50.4k
        PRBool suppressHash = ss->version == SSL_LIBRARY_VERSION_TLS_1_3 ? PR_TRUE : PR_FALSE;
4348
4349
        /* Note that we make an unfragmented message here. We fragment in the
4350
         * transmission code, if necessary */
4351
50.4k
        rv = ssl3_AppendHandshakeNumberSuppressHash(ss, ss->ssl3.hs.sendMessageSeq, 2, suppressHash);
4352
50.4k
        if (rv != SECSuccess) {
4353
0
            return rv; /* error code set by AppendHandshake, if applicable. */
4354
0
        }
4355
        /* In case if we provide a buffer for the sequence message,
4356
        we write down sendMessageSeq to the buffer. */
4357
50.4k
        if (sendMessageSeqOut != NULL) {
4358
40
            *sendMessageSeqOut = ss->ssl3.hs.sendMessageSeq;
4359
40
        }
4360
50.4k
        ss->ssl3.hs.sendMessageSeq++;
4361
4362
        /* 0 is the fragment offset, because it's not fragmented yet */
4363
50.4k
        rv = ssl3_AppendHandshakeNumberSuppressHash(ss, 0, 3, suppressHash);
4364
50.4k
        if (rv != SECSuccess) {
4365
0
            return rv; /* error code set by AppendHandshake, if applicable. */
4366
0
        }
4367
4368
        /* Fragment length -- set to the packet length because not fragmented */
4369
50.4k
        rv = ssl3_AppendHandshakeNumberSuppressHash(ss, length, 3, suppressHash);
4370
50.4k
        if (rv != SECSuccess) {
4371
0
            return rv; /* error code set by AppendHandshake, if applicable. */
4372
0
        }
4373
50.4k
    }
4374
4375
464k
    return rv; /* error code set by AppendHandshake, if applicable. */
4376
464k
}
4377
4378
/* The function calls the ssl3_AppendHandshakeHeaderAndStashSeqNum implemented above.
4379
   As in the majority of the cases we do not need the last parameter,
4380
   we separate out this function. */
4381
SECStatus
4382
ssl3_AppendHandshakeHeader(sslSocket *ss, SSLHandshakeType t, PRUint32 length)
4383
464k
{
4384
464k
    return ssl3_AppendHandshakeHeaderAndStashSeqNum(ss, t, length, NULL);
4385
464k
}
4386
4387
/**************************************************************************
4388
 * Consume Handshake functions.
4389
 *
4390
 * All data used in these functions is protected by two locks,
4391
 * the RecvBufLock and the SSL3HandshakeLock
4392
 **************************************************************************/
4393
4394
/* Read up the next "bytes" number of bytes from the (decrypted) input
4395
 * stream "b" (which is *length bytes long). Copy them into buffer "v".
4396
 * Reduces *length by bytes.  Advances *b by bytes.
4397
 *
4398
 * If this function returns SECFailure, it has already sent an alert,
4399
 * and has set a generic error code.  The caller should probably
4400
 * override the generic error code by setting another.
4401
 */
4402
SECStatus
4403
ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRUint32 bytes, PRUint8 **b,
4404
                      PRUint32 *length)
4405
155k
{
4406
155k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4407
155k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4408
4409
155k
    if ((PRUint32)bytes > *length) {
4410
165
        return ssl3_DecodeError(ss);
4411
165
    }
4412
154k
    PORT_Memcpy(v, *b, bytes);
4413
154k
    PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4414
154k
    *b += bytes;
4415
154k
    *length -= bytes;
4416
154k
    return SECSuccess;
4417
155k
}
4418
4419
/* Read up the next "bytes" number of bytes from the (decrypted) input
4420
 * stream "b" (which is *length bytes long), and interpret them as an
4421
 * integer in network byte order.  Sets *num to the received value.
4422
 * Reduces *length by bytes.  Advances *b by bytes.
4423
 *
4424
 * On error, an alert has been sent, and a generic error code has been set.
4425
 */
4426
SECStatus
4427
ssl3_ConsumeHandshakeNumber64(sslSocket *ss, PRUint64 *num, PRUint32 bytes,
4428
                              PRUint8 **b, PRUint32 *length)
4429
1.81M
{
4430
1.81M
    PRUint8 *buf = *b;
4431
1.81M
    PRUint32 i;
4432
4433
1.81M
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4434
1.81M
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4435
4436
1.81M
    *num = 0;
4437
1.81M
    if (bytes > sizeof(*num)) {
4438
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4439
0
        return SECFailure;
4440
0
    }
4441
4442
1.81M
    if (bytes > *length) {
4443
1.30k
        return ssl3_DecodeError(ss);
4444
1.30k
    }
4445
1.80M
    PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4446
4447
5.24M
    for (i = 0; i < bytes; i++) {
4448
3.43M
        *num = (*num << 8) + buf[i];
4449
3.43M
    }
4450
1.80M
    *b += bytes;
4451
1.80M
    *length -= bytes;
4452
1.80M
    return SECSuccess;
4453
1.81M
}
4454
4455
SECStatus
4456
ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRUint32 *num, PRUint32 bytes,
4457
                            PRUint8 **b, PRUint32 *length)
4458
1.79M
{
4459
1.79M
    PRUint64 num64;
4460
1.79M
    SECStatus rv;
4461
4462
1.79M
    PORT_Assert(bytes <= sizeof(*num));
4463
1.79M
    if (bytes > sizeof(*num)) {
4464
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4465
0
        return SECFailure;
4466
0
    }
4467
1.79M
    rv = ssl3_ConsumeHandshakeNumber64(ss, &num64, bytes, b, length);
4468
1.79M
    if (rv != SECSuccess) {
4469
969
        return SECFailure;
4470
969
    }
4471
1.79M
    *num = num64 & 0xffffffff;
4472
1.79M
    return SECSuccess;
4473
1.79M
}
4474
4475
/* Read in two values from the incoming decrypted byte stream "b", which is
4476
 * *length bytes long.  The first value is a number whose size is "bytes"
4477
 * bytes long.  The second value is a byte-string whose size is the value
4478
 * of the first number received.  The latter byte-string, and its length,
4479
 * is returned in the SECItem i.
4480
 *
4481
 * Returns SECFailure (-1) on failure.
4482
 * On error, an alert has been sent, and a generic error code has been set.
4483
 *
4484
 * RADICAL CHANGE for NSS 3.11.  All callers of this function make copies
4485
 * of the data returned in the SECItem *i, so making a copy of it here
4486
 * is simply wasteful.  So, This function now just sets SECItem *i to
4487
 * point to the values in the buffer **b.
4488
 */
4489
SECStatus
4490
ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRUint32 bytes,
4491
                              PRUint8 **b, PRUint32 *length)
4492
590k
{
4493
590k
    PRUint32 count;
4494
590k
    SECStatus rv;
4495
4496
590k
    PORT_Assert(bytes <= 3);
4497
590k
    i->len = 0;
4498
590k
    i->data = NULL;
4499
590k
    i->type = siBuffer;
4500
590k
    rv = ssl3_ConsumeHandshakeNumber(ss, &count, bytes, b, length);
4501
590k
    if (rv != SECSuccess) {
4502
393
        return SECFailure;
4503
393
    }
4504
589k
    if (count > 0) {
4505
400k
        if (count > *length) {
4506
1.08k
            return ssl3_DecodeError(ss);
4507
1.08k
        }
4508
399k
        i->data = *b;
4509
399k
        i->len = count;
4510
399k
        *b += count;
4511
399k
        *length -= count;
4512
399k
    }
4513
588k
    return SECSuccess;
4514
589k
}
4515
4516
/* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
4517
 * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
4518
 *
4519
 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4520
SECOidTag
4521
ssl3_HashTypeToOID(SSLHashType hashType)
4522
4.11M
{
4523
4.11M
    switch (hashType) {
4524
314k
        case ssl_hash_sha1:
4525
314k
            return SEC_OID_SHA1;
4526
2.88M
        case ssl_hash_sha256:
4527
2.88M
            return SEC_OID_SHA256;
4528
408k
        case ssl_hash_sha384:
4529
408k
            return SEC_OID_SHA384;
4530
417k
        case ssl_hash_sha512:
4531
417k
            return SEC_OID_SHA512;
4532
92.9k
        default:
4533
92.9k
            break;
4534
4.11M
    }
4535
92.9k
    return SEC_OID_UNKNOWN;
4536
4.11M
}
4537
4538
SECOidTag
4539
ssl3_AuthTypeToOID(SSLAuthType authType)
4540
2.12M
{
4541
2.12M
    switch (authType) {
4542
413k
        case ssl_auth_rsa_sign:
4543
413k
            return SEC_OID_PKCS1_RSA_ENCRYPTION;
4544
28
        case ssl_auth_rsa_pss:
4545
28
            return SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
4546
1.29M
        case ssl_auth_ecdsa:
4547
1.29M
            return SEC_OID_ANSIX962_EC_PUBLIC_KEY;
4548
319k
        case ssl_auth_dsa:
4549
319k
            return SEC_OID_ANSIX9_DSA_SIGNATURE;
4550
30.7k
        case ssl_auth_mldsa44:
4551
30.7k
            return SEC_OID_ML_DSA_44;
4552
30.5k
        case ssl_auth_mldsa65:
4553
30.5k
            return SEC_OID_ML_DSA_65;
4554
30.6k
        case ssl_auth_mldsa87:
4555
30.6k
            return SEC_OID_ML_DSA_87;
4556
0
        default:
4557
0
            break;
4558
2.12M
    }
4559
    /* shouldn't ever get there */
4560
0
    PORT_Assert(0);
4561
0
    return SEC_OID_UNKNOWN;
4562
2.12M
}
4563
4564
SSLHashType
4565
ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme)
4566
3.94M
{
4567
3.94M
    switch (scheme) {
4568
108k
        case ssl_sig_rsa_pkcs1_sha1:
4569
188k
        case ssl_sig_dsa_sha1:
4570
292k
        case ssl_sig_ecdsa_sha1:
4571
292k
            return ssl_hash_sha1;
4572
96.7k
        case ssl_sig_rsa_pkcs1_sha256:
4573
1.07M
        case ssl_sig_ecdsa_secp256r1_sha256:
4574
2.69M
        case ssl_sig_rsa_pss_rsae_sha256:
4575
2.69M
        case ssl_sig_rsa_pss_pss_sha256:
4576
2.77M
        case ssl_sig_dsa_sha256:
4577
2.77M
            return ssl_hash_sha256;
4578
88.9k
        case ssl_sig_rsa_pkcs1_sha384:
4579
194k
        case ssl_sig_ecdsa_secp384r1_sha384:
4580
293k
        case ssl_sig_rsa_pss_rsae_sha384:
4581
294k
        case ssl_sig_rsa_pss_pss_sha384:
4582
372k
        case ssl_sig_dsa_sha384:
4583
372k
            return ssl_hash_sha384;
4584
127k
        case ssl_sig_rsa_pkcs1_sha512:
4585
232k
        case ssl_sig_ecdsa_secp521r1_sha512:
4586
329k
        case ssl_sig_rsa_pss_rsae_sha512:
4587
329k
        case ssl_sig_rsa_pss_pss_sha512:
4588
411k
        case ssl_sig_dsa_sha512:
4589
411k
            return ssl_hash_sha512;
4590
0
        case ssl_sig_rsa_pkcs1_sha1md5:
4591
0
            return ssl_hash_none; /* Special for TLS 1.0/1.1. */
4592
30.6k
        case ssl_sig_mldsa44:
4593
61.0k
        case ssl_sig_mldsa65:
4594
91.6k
        case ssl_sig_mldsa87:
4595
91.6k
            return ssl_hash_none; /* ml_dsa does no hashing */
4596
0
        case ssl_sig_none:
4597
0
        case ssl_sig_ed25519:
4598
0
        case ssl_sig_ed448:
4599
0
            break;
4600
3.94M
    }
4601
0
    PORT_Assert(0);
4602
0
    return ssl_hash_none;
4603
3.94M
}
4604
4605
static PRBool
4606
ssl_SignatureSchemeMatchesSpkiOid(SSLSignatureScheme scheme, SECOidTag spkiOid)
4607
64.3k
{
4608
64.3k
    SECOidTag authOid = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme));
4609
4610
64.3k
    if (spkiOid == authOid) {
4611
43.2k
        return PR_TRUE;
4612
43.2k
    }
4613
21.0k
    if ((authOid == SEC_OID_PKCS1_RSA_ENCRYPTION) &&
4614
549
        (spkiOid == SEC_OID_X500_RSA_ENCRYPTION)) {
4615
0
        return PR_TRUE;
4616
0
    }
4617
21.0k
    return PR_FALSE;
4618
21.0k
}
4619
4620
/* Validate that the signature scheme works for the given key type. */
4621
PRBool
4622
ssl_SignatureSchemeValid(SSLSignatureScheme scheme, SECOidTag spkiOid,
4623
                         PRBool isTls13)
4624
303k
{
4625
303k
    if (!ssl_IsSupportedSignatureScheme(scheme)) {
4626
195k
        return PR_FALSE;
4627
195k
    }
4628
    /* if we are purposefully passed SEC_OID_UNKNOWN, it means
4629
     * we not checking the scheme against a potential key, so skip
4630
     * the call */
4631
107k
    if ((spkiOid != SEC_OID_UNKNOWN) &&
4632
64.3k
        !ssl_SignatureSchemeMatchesSpkiOid(scheme, spkiOid)) {
4633
21.0k
        return PR_FALSE;
4634
21.0k
    }
4635
86.8k
    if (isTls13) {
4636
18.7k
        if (ssl_SignatureSchemeToHashType(scheme) == ssl_hash_sha1) {
4637
2.82k
            return PR_FALSE;
4638
2.82k
        }
4639
15.8k
        if (ssl_IsRsaPkcs1SignatureScheme(scheme)) {
4640
3.03k
            return PR_FALSE;
4641
3.03k
        }
4642
12.8k
        if (ssl_IsDsaSignatureScheme(scheme)) {
4643
1.45k
            return PR_FALSE;
4644
1.45k
        }
4645
        /* With TLS 1.3, EC keys should have been selected based on calling
4646
         * ssl_SignatureSchemeFromSpki(), reject them otherwise. */
4647
11.4k
        return spkiOid != SEC_OID_ANSIX962_EC_PUBLIC_KEY;
4648
68.1k
    } else {
4649
68.1k
        if (ssl_IsMldsaSignatureScheme(scheme)) {
4650
716
            return PR_FALSE;
4651
716
        }
4652
68.1k
    }
4653
67.3k
    return PR_TRUE;
4654
86.8k
}
4655
4656
static SECStatus
4657
ssl_SignatureSchemeFromPssSpki(const CERTSubjectPublicKeyInfo *spki,
4658
                               SSLSignatureScheme *scheme)
4659
64
{
4660
64
    SECKEYRSAPSSParams pssParam = { 0 };
4661
64
    PORTCheapArenaPool arena;
4662
64
    SECStatus rv;
4663
4664
    /* The key doesn't have parameters, boo. */
4665
64
    if (!spki->algorithm.parameters.len) {
4666
20
        *scheme = ssl_sig_none;
4667
20
        return SECSuccess;
4668
20
    }
4669
4670
44
    PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE);
4671
44
    rv = SEC_QuickDERDecodeItem(&arena.arena, &pssParam,
4672
44
                                SEC_ASN1_GET(SECKEY_RSAPSSParamsTemplate),
4673
44
                                &spki->algorithm.parameters);
4674
44
    if (rv != SECSuccess) {
4675
13
        goto loser;
4676
13
    }
4677
    /* Not having hashAlg means SHA-1 and we don't accept that. */
4678
31
    if (!pssParam.hashAlg) {
4679
8
        goto loser;
4680
8
    }
4681
23
    switch (SECOID_GetAlgorithmTag(pssParam.hashAlg)) {
4682
5
        case SEC_OID_SHA256:
4683
5
            *scheme = ssl_sig_rsa_pss_pss_sha256;
4684
5
            break;
4685
8
        case SEC_OID_SHA384:
4686
8
            *scheme = ssl_sig_rsa_pss_pss_sha384;
4687
8
            break;
4688
4
        case SEC_OID_SHA512:
4689
4
            *scheme = ssl_sig_rsa_pss_pss_sha512;
4690
4
            break;
4691
6
        default:
4692
6
            goto loser;
4693
23
    }
4694
4695
17
    PORT_DestroyCheapArena(&arena);
4696
17
    return SECSuccess;
4697
4698
27
loser:
4699
27
    PORT_DestroyCheapArena(&arena);
4700
27
    PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4701
27
    return SECFailure;
4702
23
}
4703
4704
static SECStatus
4705
ssl_SignatureSchemeFromEcSpki(const CERTSubjectPublicKeyInfo *spki,
4706
                              SSLSignatureScheme *scheme)
4707
4.96k
{
4708
4.96k
    const sslNamedGroupDef *group;
4709
4.96k
    SECKEYPublicKey *key;
4710
4711
4.96k
    key = SECKEY_ExtractPublicKey(spki);
4712
4.96k
    if (!key) {
4713
0
        PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4714
0
        return SECFailure;
4715
0
    }
4716
4.96k
    group = ssl_ECPubKey2NamedGroup(key);
4717
4.96k
    SECKEY_DestroyPublicKey(key);
4718
4.96k
    if (!group) {
4719
0
        PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4720
0
        return SECFailure;
4721
0
    }
4722
4.96k
    switch (group->name) {
4723
2.90k
        case ssl_grp_ec_secp256r1:
4724
2.90k
            *scheme = ssl_sig_ecdsa_secp256r1_sha256;
4725
2.90k
            return SECSuccess;
4726
2.05k
        case ssl_grp_ec_secp384r1:
4727
2.05k
            *scheme = ssl_sig_ecdsa_secp384r1_sha384;
4728
2.05k
            return SECSuccess;
4729
0
        case ssl_grp_ec_secp521r1:
4730
0
            *scheme = ssl_sig_ecdsa_secp521r1_sha512;
4731
0
            return SECSuccess;
4732
0
        default:
4733
0
            break;
4734
4.96k
    }
4735
0
    PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4736
0
    return SECFailure;
4737
4.96k
}
4738
4739
/* Newer signature schemes are designed so that a single SPKI can be used with
4740
 * that scheme.  This determines that scheme from the SPKI. If the SPKI doesn't
4741
 * have a single scheme, |*scheme| is set to ssl_sig_none. */
4742
SECStatus
4743
ssl_SignatureSchemeFromSpki(const CERTSubjectPublicKeyInfo *spki,
4744
                            PRBool isTls13, SSLSignatureScheme *scheme)
4745
35.0k
{
4746
35.0k
    SECOidTag spkiOid = SECOID_GetAlgorithmTag(&spki->algorithm);
4747
4748
35.0k
    *scheme = ssl_sig_none;
4749
35.0k
    switch (spkiOid) {
4750
64
        case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
4751
64
            return ssl_SignatureSchemeFromPssSpki(spki, scheme);
4752
7.05k
        case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
4753
            /* Only do this lookup for TLS 1.3, where the scheme can be
4754
             * determined from the SPKI alone because the ECDSA key size
4755
             * determines the hash. Earlier TLS versions allow the same
4756
             * EC key to be used with different hashes. */
4757
7.05k
            if (isTls13) {
4758
4.96k
                return ssl_SignatureSchemeFromEcSpki(spki, scheme);
4759
4.96k
            }
4760
2.09k
            break;
4761
2.09k
        case SEC_OID_ML_DSA_44:
4762
3
            *scheme = ssl_sig_mldsa44;
4763
3
            break;
4764
4
        case SEC_OID_ML_DSA_65:
4765
4
            *scheme = ssl_sig_mldsa65;
4766
4
            break;
4767
4
        case SEC_OID_ML_DSA_87:
4768
4
            *scheme = ssl_sig_mldsa87;
4769
4
            break;
4770
27.8k
        default:
4771
27.8k
            break;
4772
35.0k
    }
4773
29.9k
    return SECSuccess;
4774
35.0k
}
4775
4776
/* Check that a signature scheme is enabled by configuration. */
4777
PRBool
4778
ssl_SignatureSchemeEnabled(const sslSocket *ss, SSLSignatureScheme scheme)
4779
28.7k
{
4780
28.7k
    unsigned int i;
4781
231k
    for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
4782
231k
        if (scheme == ss->ssl3.signatureSchemes[i]) {
4783
28.7k
            return PR_TRUE;
4784
28.7k
        }
4785
231k
    }
4786
10
    return PR_FALSE;
4787
28.7k
}
4788
4789
static PRBool
4790
ssl_SignatureKeyMatchesSpkiOid(const ssl3KEADef *keaDef, SECOidTag spkiOid)
4791
5.78k
{
4792
5.78k
    switch (spkiOid) {
4793
0
        case SEC_OID_X500_RSA_ENCRYPTION:
4794
2.94k
        case SEC_OID_PKCS1_RSA_ENCRYPTION:
4795
2.95k
        case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
4796
2.95k
            return keaDef->signKeyType == rsaKey;
4797
2.27k
        case SEC_OID_ANSIX9_DSA_SIGNATURE:
4798
2.27k
            return keaDef->signKeyType == dsaKey;
4799
554
        case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
4800
554
            return keaDef->signKeyType == ecKey;
4801
4
        default:
4802
4
            break;
4803
5.78k
    }
4804
4
    return PR_FALSE;
4805
5.78k
}
4806
4807
/* ssl3_CheckSignatureSchemeConsistency checks that the signature algorithm
4808
 * identifier in |scheme| is consistent with the public key in |spki|. It also
4809
 * checks the hash algorithm against the configured signature algorithms.  If
4810
 * all the tests pass, SECSuccess is returned. Otherwise, PORT_SetError is
4811
 * called and SECFailure is returned. */
4812
SECStatus
4813
ssl_CheckSignatureSchemeConsistency(sslSocket *ss, SSLSignatureScheme scheme,
4814
                                    CERTSubjectPublicKeyInfo *spki)
4815
23.9k
{
4816
23.9k
    SSLSignatureScheme spkiScheme;
4817
23.9k
    PRBool isTLS13 = ss->version == SSL_LIBRARY_VERSION_TLS_1_3;
4818
23.9k
    SECOidTag spkiOid;
4819
23.9k
    SECStatus rv;
4820
4821
23.9k
    rv = ssl_SignatureSchemeFromSpki(spki, isTLS13, &spkiScheme);
4822
23.9k
    if (rv != SECSuccess) {
4823
27
        return SECFailure;
4824
27
    }
4825
23.9k
    if (spkiScheme != ssl_sig_none) {
4826
        /* The SPKI in the certificate can only be used for a single scheme. */
4827
28
        if (spkiScheme != scheme ||
4828
26
            !ssl_SignatureSchemeEnabled(ss, scheme)) {
4829
26
            PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4830
26
            return SECFailure;
4831
26
        }
4832
2
        return SECSuccess;
4833
28
    }
4834
4835
23.9k
    spkiOid = SECOID_GetAlgorithmTag(&spki->algorithm);
4836
4837
    /* If we're a client, check that the signature algorithm matches the signing
4838
     * key type of the cipher suite. */
4839
23.9k
    if (!isTLS13 && !ss->sec.isServer) {
4840
5.78k
        if (!ssl_SignatureKeyMatchesSpkiOid(ss->ssl3.hs.kea_def, spkiOid)) {
4841
24
            PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4842
24
            return SECFailure;
4843
24
        }
4844
5.78k
    }
4845
4846
    /* Verify that the signature scheme matches the signing key. */
4847
23.8k
    if ((spkiOid == SEC_OID_UNKNOWN) ||
4848
23.8k
        !ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13)) {
4849
73
        PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4850
73
        return SECFailure;
4851
73
    }
4852
4853
23.8k
    if (!ssl_SignatureSchemeEnabled(ss, scheme)) {
4854
4
        PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
4855
4
        return SECFailure;
4856
4
    }
4857
4858
23.8k
    return SECSuccess;
4859
23.8k
}
4860
4861
PRBool
4862
ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme)
4863
327k
{
4864
327k
    switch (scheme) {
4865
8.07k
        case ssl_sig_rsa_pkcs1_sha1:
4866
17.9k
        case ssl_sig_rsa_pkcs1_sha256:
4867
22.9k
        case ssl_sig_rsa_pkcs1_sha384:
4868
54.2k
        case ssl_sig_rsa_pkcs1_sha512:
4869
66.4k
        case ssl_sig_rsa_pss_rsae_sha256:
4870
72.7k
        case ssl_sig_rsa_pss_rsae_sha384:
4871
78.5k
        case ssl_sig_rsa_pss_rsae_sha512:
4872
79.9k
        case ssl_sig_rsa_pss_pss_sha256:
4873
81.2k
        case ssl_sig_rsa_pss_pss_sha384:
4874
81.7k
        case ssl_sig_rsa_pss_pss_sha512:
4875
91.1k
        case ssl_sig_ecdsa_secp256r1_sha256:
4876
98.8k
        case ssl_sig_ecdsa_secp384r1_sha384:
4877
109k
        case ssl_sig_ecdsa_secp521r1_sha512:
4878
110k
        case ssl_sig_mldsa44:
4879
110k
        case ssl_sig_mldsa65:
4880
110k
        case ssl_sig_mldsa87:
4881
113k
        case ssl_sig_dsa_sha1:
4882
117k
        case ssl_sig_dsa_sha256:
4883
119k
        case ssl_sig_dsa_sha384:
4884
124k
        case ssl_sig_dsa_sha512:
4885
131k
        case ssl_sig_ecdsa_sha1:
4886
131k
            return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy);
4887
0
            break;
4888
4889
0
        case ssl_sig_rsa_pkcs1_sha1md5:
4890
19.1k
        case ssl_sig_none:
4891
19.1k
        case ssl_sig_ed25519:
4892
20.1k
        case ssl_sig_ed448:
4893
20.1k
            return PR_FALSE;
4894
327k
    }
4895
175k
    return PR_FALSE;
4896
327k
}
4897
4898
PRBool
4899
ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme)
4900
7.93M
{
4901
7.93M
    switch (scheme) {
4902
3.20M
        case ssl_sig_rsa_pss_rsae_sha256:
4903
3.37M
        case ssl_sig_rsa_pss_rsae_sha384:
4904
3.55M
        case ssl_sig_rsa_pss_rsae_sha512:
4905
3.55M
        case ssl_sig_rsa_pss_pss_sha256:
4906
3.55M
        case ssl_sig_rsa_pss_pss_sha384:
4907
3.55M
        case ssl_sig_rsa_pss_pss_sha512:
4908
3.55M
            return PR_TRUE;
4909
4910
4.37M
        default:
4911
4.37M
            return PR_FALSE;
4912
7.93M
    }
4913
0
    return PR_FALSE;
4914
7.93M
}
4915
4916
PRBool
4917
ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme)
4918
149k
{
4919
149k
    switch (scheme) {
4920
8.31k
        case ssl_sig_rsa_pss_rsae_sha256:
4921
16.6k
        case ssl_sig_rsa_pss_rsae_sha384:
4922
24.9k
        case ssl_sig_rsa_pss_rsae_sha512:
4923
24.9k
            return PR_TRUE;
4924
4925
124k
        default:
4926
124k
            return PR_FALSE;
4927
149k
    }
4928
0
    return PR_FALSE;
4929
149k
}
4930
4931
PRBool
4932
ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme)
4933
1.06M
{
4934
1.06M
    switch (scheme) {
4935
16.1k
        case ssl_sig_rsa_pkcs1_sha256:
4936
32.0k
        case ssl_sig_rsa_pkcs1_sha384:
4937
48.0k
        case ssl_sig_rsa_pkcs1_sha512:
4938
63.0k
        case ssl_sig_rsa_pkcs1_sha1:
4939
63.0k
            return PR_TRUE;
4940
4941
1.00M
        default:
4942
1.00M
            return PR_FALSE;
4943
1.06M
    }
4944
0
    return PR_FALSE;
4945
1.06M
}
4946
4947
PRBool
4948
ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme)
4949
1.93M
{
4950
1.93M
    switch (scheme) {
4951
94.5k
        case ssl_sig_dsa_sha256:
4952
189k
        case ssl_sig_dsa_sha384:
4953
283k
        case ssl_sig_dsa_sha512:
4954
377k
        case ssl_sig_dsa_sha1:
4955
377k
            return PR_TRUE;
4956
4957
1.55M
        default:
4958
1.55M
            return PR_FALSE;
4959
1.93M
    }
4960
0
    return PR_FALSE;
4961
1.93M
}
4962
4963
PRBool
4964
ssl_IsMldsaSignatureScheme(SSLSignatureScheme scheme)
4965
2.32M
{
4966
2.32M
    switch (scheme) {
4967
91.0k
        case ssl_sig_mldsa44:
4968
181k
        case ssl_sig_mldsa65:
4969
272k
        case ssl_sig_mldsa87:
4970
272k
            return PR_TRUE;
4971
4972
2.05M
        default:
4973
2.05M
            return PR_FALSE;
4974
2.32M
    }
4975
0
    return PR_FALSE;
4976
2.32M
}
4977
4978
SSLAuthType
4979
ssl_SignatureSchemeToAuthType(SSLSignatureScheme scheme)
4980
10.4M
{
4981
10.4M
    switch (scheme) {
4982
126k
        case ssl_sig_rsa_pkcs1_sha1:
4983
128k
        case ssl_sig_rsa_pkcs1_sha1md5:
4984
224k
        case ssl_sig_rsa_pkcs1_sha256:
4985
313k
        case ssl_sig_rsa_pkcs1_sha384:
4986
441k
        case ssl_sig_rsa_pkcs1_sha512:
4987
        /* We report based on the key type for PSS signatures. */
4988
1.95M
        case ssl_sig_rsa_pss_rsae_sha256:
4989
1.96M
        case ssl_sig_rsa_pss_rsae_sha384:
4990
1.96M
        case ssl_sig_rsa_pss_rsae_sha512:
4991
1.96M
            return ssl_auth_rsa_sign;
4992
11
        case ssl_sig_rsa_pss_pss_sha256:
4993
20
        case ssl_sig_rsa_pss_pss_sha384:
4994
28
        case ssl_sig_rsa_pss_pss_sha512:
4995
28
            return ssl_auth_rsa_pss;
4996
3.23M
        case ssl_sig_ecdsa_secp256r1_sha256:
4997
4.84M
        case ssl_sig_ecdsa_secp384r1_sha384:
4998
6.46M
        case ssl_sig_ecdsa_secp521r1_sha512:
4999
8.08M
        case ssl_sig_ecdsa_sha1:
5000
8.08M
            return ssl_auth_ecdsa;
5001
78.5k
        case ssl_sig_dsa_sha1:
5002
162k
        case ssl_sig_dsa_sha256:
5003
239k
        case ssl_sig_dsa_sha384:
5004
321k
        case ssl_sig_dsa_sha512:
5005
321k
            return ssl_auth_dsa;
5006
        /* while there is one mechanism for ML-DSA,
5007
         * server cert selection depends on which
5008
         * flavor (paramset) is being used, so
5009
         * we need one auth foreach param set.
5010
         */
5011
30.7k
        case ssl_sig_mldsa44:
5012
30.7k
            return ssl_auth_mldsa44;
5013
30.5k
        case ssl_sig_mldsa65:
5014
30.5k
            return ssl_auth_mldsa65;
5015
30.6k
        case ssl_sig_mldsa87:
5016
30.6k
            return ssl_auth_mldsa87;
5017
5018
0
        default:
5019
0
            PORT_Assert(0);
5020
10.4M
    }
5021
0
    return ssl_auth_null;
5022
10.4M
}
5023
5024
/* ssl_ConsumeSignatureScheme reads a SSLSignatureScheme (formerly
5025
 * SignatureAndHashAlgorithm) structure from |b| and puts the resulting value
5026
 * into |out|. |b| and |length| are updated accordingly.
5027
 *
5028
 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
5029
SECStatus
5030
ssl_ConsumeSignatureScheme(sslSocket *ss, PRUint8 **b,
5031
                           PRUint32 *length, SSLSignatureScheme *out)
5032
24.0k
{
5033
24.0k
    PRUint32 tmp;
5034
24.0k
    SECStatus rv;
5035
5036
24.0k
    rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
5037
24.0k
    if (rv != SECSuccess) {
5038
15
        return SECFailure; /* Alert sent, Error code set already. */
5039
15
    }
5040
24.0k
    if (!ssl_IsSupportedSignatureScheme((SSLSignatureScheme)tmp)) {
5041
49
        SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
5042
49
        PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
5043
49
        return SECFailure;
5044
49
    }
5045
23.9k
    *out = (SSLSignatureScheme)tmp;
5046
23.9k
    return SECSuccess;
5047
24.0k
}
5048
5049
/**************************************************************************
5050
 * end of Consume Handshake functions.
5051
 **************************************************************************/
5052
5053
static SECStatus
5054
ssl3_ComputeHandshakeHash(unsigned char *buf, unsigned int len,
5055
                          SSLHashType hashAlg, SSL3Hashes *hashes)
5056
151k
{
5057
151k
    SECStatus rv = SECFailure;
5058
151k
    PK11Context *hashContext = PK11_CreateDigestContext(
5059
151k
        ssl3_HashTypeToOID(hashAlg));
5060
5061
151k
    if (!hashContext) {
5062
0
        return rv;
5063
0
    }
5064
151k
    rv = PK11_DigestBegin(hashContext);
5065
151k
    if (rv == SECSuccess) {
5066
151k
        rv = PK11_DigestOp(hashContext, buf, len);
5067
151k
    }
5068
151k
    if (rv == SECSuccess) {
5069
151k
        rv = PK11_DigestFinal(hashContext, hashes->u.raw, &hashes->len,
5070
151k
                              sizeof(hashes->u.raw));
5071
151k
    }
5072
151k
    if (rv == SECSuccess) {
5073
151k
        hashes->hashAlg = hashAlg;
5074
151k
    }
5075
151k
    PK11_DestroyContext(hashContext, PR_TRUE);
5076
151k
    return rv;
5077
151k
}
5078
5079
/* Extract the hashes of handshake messages to this point.
5080
 * Called from ssl3_SendCertificateVerify
5081
 *             ssl3_SendFinished
5082
 *             ssl3_HandleHandshakeMessage
5083
 *
5084
 * Caller must hold the SSL3HandshakeLock.
5085
 * Caller must hold a read or write lock on the Spec R/W lock.
5086
 *  (There is presently no way to assert on a Read lock.)
5087
 */
5088
SECStatus
5089
ssl3_ComputeHandshakeHashes(sslSocket *ss,
5090
                            ssl3CipherSpec *spec, /* uses ->master_secret */
5091
                            SSL3Hashes *hashes,   /* output goes here. */
5092
                            PRUint32 sender)
5093
207k
{
5094
207k
    SECStatus rv = SECSuccess;
5095
207k
    PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
5096
207k
    unsigned int outLength;
5097
207k
    PRUint8 md5_inner[MAX_MAC_LENGTH];
5098
207k
    PRUint8 sha_inner[MAX_MAC_LENGTH];
5099
5100
207k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5101
207k
    if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
5102
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5103
0
        return SECFailure;
5104
0
    }
5105
5106
207k
    hashes->hashAlg = ssl_hash_none;
5107
5108
207k
    if (ss->ssl3.hs.hashType == handshake_hash_single) {
5109
0
        PK11Context *h;
5110
0
        unsigned int stateLen;
5111
0
        unsigned char stackBuf[1024];
5112
0
        unsigned char *stateBuf = NULL;
5113
5114
0
        h = ss->ssl3.hs.sha;
5115
0
        stateBuf = PK11_SaveContextAlloc(h, stackBuf,
5116
0
                                         sizeof(stackBuf), &stateLen);
5117
0
        if (stateBuf == NULL) {
5118
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
5119
0
            rv = SECFailure;
5120
0
            goto tls12_loser;
5121
0
        }
5122
0
        rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
5123
0
                               sizeof(hashes->u.raw));
5124
0
        if (rv != SECSuccess) {
5125
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
5126
0
            rv = SECFailure;
5127
0
            goto tls12_loser;
5128
0
        }
5129
5130
0
        hashes->hashAlg = ssl3_GetSuitePrfHash(ss);
5131
5132
0
    tls12_loser:
5133
0
        if (stateBuf) {
5134
0
            if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
5135
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
5136
0
                rv = SECFailure;
5137
0
            }
5138
0
            if (stateBuf != stackBuf) {
5139
0
                PORT_ZFree(stateBuf, stateLen);
5140
0
            }
5141
0
        }
5142
207k
    } else if (ss->ssl3.hs.hashType == handshake_hash_record) {
5143
133k
        rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
5144
133k
                                       ss->ssl3.hs.messages.len,
5145
133k
                                       ssl3_GetSuitePrfHash(ss),
5146
133k
                                       hashes);
5147
133k
    } else {
5148
74.0k
        PK11Context *md5;
5149
74.0k
        PK11Context *sha = NULL;
5150
74.0k
        unsigned char *md5StateBuf = NULL;
5151
74.0k
        unsigned char *shaStateBuf = NULL;
5152
74.0k
        unsigned int md5StateLen, shaStateLen;
5153
74.0k
        unsigned char md5StackBuf[256];
5154
74.0k
        unsigned char shaStackBuf[512];
5155
74.0k
        const int md5Pad = ssl_GetMacDefByAlg(ssl_mac_md5)->pad_size;
5156
74.0k
        const int shaPad = ssl_GetMacDefByAlg(ssl_mac_sha)->pad_size;
5157
5158
74.0k
        md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
5159
74.0k
                                            sizeof md5StackBuf, &md5StateLen);
5160
74.0k
        if (md5StateBuf == NULL) {
5161
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
5162
0
            rv = SECFailure;
5163
0
            goto loser;
5164
0
        }
5165
74.0k
        md5 = ss->ssl3.hs.md5;
5166
5167
74.0k
        shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
5168
74.0k
                                            sizeof shaStackBuf, &shaStateLen);
5169
74.0k
        if (shaStateBuf == NULL) {
5170
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5171
0
            rv = SECFailure;
5172
0
            goto loser;
5173
0
        }
5174
74.0k
        sha = ss->ssl3.hs.sha;
5175
5176
74.0k
        if (!isTLS) {
5177
            /* compute hashes for SSL3. */
5178
0
            unsigned char s[4];
5179
5180
0
            if (!spec->masterSecret) {
5181
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
5182
0
                rv = SECFailure;
5183
0
                goto loser;
5184
0
            }
5185
5186
0
            s[0] = (unsigned char)(sender >> 24);
5187
0
            s[1] = (unsigned char)(sender >> 16);
5188
0
            s[2] = (unsigned char)(sender >> 8);
5189
0
            s[3] = (unsigned char)sender;
5190
5191
0
            if (sender != 0) {
5192
0
                rv |= PK11_DigestOp(md5, s, 4);
5193
0
                PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
5194
0
            }
5195
5196
0
            PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, md5Pad));
5197
5198
0
            rv |= PK11_DigestKey(md5, spec->masterSecret);
5199
0
            rv |= PK11_DigestOp(md5, mac_pad_1, md5Pad);
5200
0
            rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
5201
0
            PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
5202
0
            if (rv != SECSuccess) {
5203
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
5204
0
                rv = SECFailure;
5205
0
                goto loser;
5206
0
            }
5207
5208
0
            PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
5209
5210
0
            if (sender != 0) {
5211
0
                rv |= PK11_DigestOp(sha, s, 4);
5212
0
                PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
5213
0
            }
5214
5215
0
            PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, shaPad));
5216
5217
0
            rv |= PK11_DigestKey(sha, spec->masterSecret);
5218
0
            rv |= PK11_DigestOp(sha, mac_pad_1, shaPad);
5219
0
            rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
5220
0
            PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
5221
0
            if (rv != SECSuccess) {
5222
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5223
0
                rv = SECFailure;
5224
0
                goto loser;
5225
0
            }
5226
5227
0
            PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
5228
5229
0
            PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, md5Pad));
5230
0
            PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
5231
5232
0
            rv |= PK11_DigestBegin(md5);
5233
0
            rv |= PK11_DigestKey(md5, spec->masterSecret);
5234
0
            rv |= PK11_DigestOp(md5, mac_pad_2, md5Pad);
5235
0
            rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
5236
0
        }
5237
74.0k
        rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH);
5238
74.0k
        PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
5239
74.0k
        if (rv != SECSuccess) {
5240
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
5241
0
            rv = SECFailure;
5242
0
            goto loser;
5243
0
        }
5244
5245
74.0k
        PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
5246
5247
74.0k
        if (!isTLS) {
5248
0
            PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, shaPad));
5249
0
            PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
5250
5251
0
            rv |= PK11_DigestBegin(sha);
5252
0
            rv |= PK11_DigestKey(sha, spec->masterSecret);
5253
0
            rv |= PK11_DigestOp(sha, mac_pad_2, shaPad);
5254
0
            rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
5255
0
        }
5256
74.0k
        rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH);
5257
74.0k
        PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
5258
74.0k
        if (rv != SECSuccess) {
5259
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5260
0
            rv = SECFailure;
5261
0
            goto loser;
5262
0
        }
5263
5264
74.0k
        PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
5265
5266
74.0k
        hashes->len = MD5_LENGTH + SHA1_LENGTH;
5267
5268
74.0k
    loser:
5269
74.0k
        if (md5StateBuf) {
5270
74.0k
            if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) !=
5271
74.0k
                SECSuccess) {
5272
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
5273
0
                rv = SECFailure;
5274
0
            }
5275
74.0k
            if (md5StateBuf != md5StackBuf) {
5276
0
                PORT_ZFree(md5StateBuf, md5StateLen);
5277
0
            }
5278
74.0k
        }
5279
74.0k
        if (shaStateBuf) {
5280
74.0k
            if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) !=
5281
74.0k
                SECSuccess) {
5282
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5283
0
                rv = SECFailure;
5284
0
            }
5285
74.0k
            if (shaStateBuf != shaStackBuf) {
5286
0
                PORT_ZFree(shaStateBuf, shaStateLen);
5287
0
            }
5288
74.0k
        }
5289
74.0k
    }
5290
207k
    return rv;
5291
207k
}
5292
5293
/**************************************************************************
5294
 * end of Handshake Hash functions.
5295
 * Begin Send and Handle functions for handshakes.
5296
 **************************************************************************/
5297
5298
#ifdef TRACE
5299
#define CHTYPE(t)          \
5300
0
    case client_hello_##t: \
5301
0
        return #t;
5302
5303
static const char *
5304
ssl_ClientHelloTypeName(sslClientHelloType type)
5305
0
{
5306
0
    switch (type) {
5307
0
        CHTYPE(initial);
5308
0
        CHTYPE(retry);
5309
0
        CHTYPE(retransmit);    /* DTLS only */
5310
0
        CHTYPE(renegotiation); /* TLS <= 1.2 only */
5311
0
    }
5312
0
    PORT_Assert(0);
5313
0
    return NULL;
5314
0
}
5315
#undef CHTYPE
5316
#endif
5317
5318
PR_STATIC_ASSERT(SSL3_SESSIONID_BYTES == SSL3_RANDOM_LENGTH);
5319
static void
5320
ssl_MakeFakeSid(sslSocket *ss, PRUint8 *buf)
5321
4.52k
{
5322
4.52k
    PRUint8 x = 0x5a;
5323
4.52k
    int i;
5324
149k
    for (i = 0; i < SSL3_SESSIONID_BYTES; ++i) {
5325
144k
        x += ss->ssl3.hs.client_random[i];
5326
144k
        buf[i] = x;
5327
144k
    }
5328
4.52k
}
5329
5330
/* Set the version fields of the cipher spec for a ClientHello. */
5331
static void
5332
ssl_SetClientHelloSpecVersion(sslSocket *ss, ssl3CipherSpec *spec)
5333
31.2k
{
5334
31.2k
    ssl_GetSpecWriteLock(ss);
5335
31.2k
    PORT_Assert(spec->cipherDef->cipher == cipher_null);
5336
    /* This is - a best guess - but it doesn't matter here. */
5337
31.2k
    spec->version = ss->vrange.max;
5338
31.2k
    if (IS_DTLS(ss)) {
5339
14.4k
        spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_0_WIRE;
5340
16.7k
    } else {
5341
        /* For new connections, cap the record layer version number of TLS
5342
         * ClientHello to { 3, 1 } (TLS 1.0). Some TLS 1.0 servers (which seem
5343
         * to use F5 BIG-IP) ignore ClientHello.client_version and use the
5344
         * record layer version number (TLSPlaintext.version) instead when
5345
         * negotiating protocol versions. In addition, if the record layer
5346
         * version number of ClientHello is { 3, 2 } (TLS 1.1) or higher, these
5347
         * servers reset the TCP connections. Lastly, some F5 BIG-IP servers
5348
         * hang if a record containing a ClientHello has a version greater than
5349
         * { 3, 1 } and a length greater than 255. Set this flag to work around
5350
         * such servers.
5351
         *
5352
         * The final version is set when a version is negotiated.
5353
         */
5354
16.7k
        spec->recordVersion = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0,
5355
16.7k
                                     ss->vrange.max);
5356
16.7k
    }
5357
31.2k
    ssl_ReleaseSpecWriteLock(ss);
5358
31.2k
}
5359
5360
SECStatus
5361
ssl3_InsertChHeaderSize(const sslSocket *ss, sslBuffer *preamble, const sslBuffer *extensions)
5362
151k
{
5363
151k
    SECStatus rv;
5364
151k
    unsigned int msgLen = preamble->len;
5365
151k
    msgLen += extensions->len ? (2 + extensions->len) : 0;
5366
151k
    unsigned int headerLen = IS_DTLS(ss) ? 12 : 4;
5367
5368
    /* Record the message length. */
5369
151k
    rv = sslBuffer_InsertNumber(preamble, 1, msgLen - headerLen, 3);
5370
151k
    if (rv != SECSuccess) {
5371
0
        return SECFailure; /* code set */
5372
0
    }
5373
151k
    if (IS_DTLS(ss)) {
5374
        /* Record the (unfragmented) fragment length. */
5375
34.6k
        unsigned int offset = 1 /* ch */ + 3 /* len */ +
5376
34.6k
                              2 /* seq */ + 3 /* fragment offset */;
5377
34.6k
        rv = sslBuffer_InsertNumber(preamble, offset, msgLen - headerLen, 3);
5378
34.6k
        if (rv != SECSuccess) {
5379
0
            return SECFailure; /* code set */
5380
0
        }
5381
34.6k
    }
5382
5383
151k
    return SECSuccess;
5384
151k
}
5385
5386
static SECStatus
5387
ssl3_AppendCipherSuites(sslSocket *ss, PRBool fallbackSCSV, sslBuffer *buf)
5388
77.8k
{
5389
77.8k
    SECStatus rv;
5390
77.8k
    unsigned int offset;
5391
77.8k
    unsigned int i;
5392
77.8k
    unsigned int saveLen;
5393
5394
77.8k
    rv = sslBuffer_Skip(buf, 2, &offset);
5395
77.8k
    if (rv != SECSuccess) {
5396
0
        return SECFailure;
5397
0
    }
5398
5399
77.8k
    if (ss->ssl3.hs.sendingSCSV) {
5400
        /* Add the actual SCSV */
5401
0
        rv = sslBuffer_AppendNumber(buf, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
5402
0
                                    sizeof(ssl3CipherSuite));
5403
0
        if (rv != SECSuccess) {
5404
0
            return SECFailure;
5405
0
        }
5406
0
    }
5407
77.8k
    if (fallbackSCSV) {
5408
36.0k
        rv = sslBuffer_AppendNumber(buf, TLS_FALLBACK_SCSV,
5409
36.0k
                                    sizeof(ssl3CipherSuite));
5410
36.0k
        if (rv != SECSuccess) {
5411
0
            return SECFailure;
5412
0
        }
5413
36.0k
    }
5414
5415
77.8k
    saveLen = SSL_BUFFER_LEN(buf);
5416
    /* CipherSuites are appended to Hello message here */
5417
5.60M
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
5418
5.52M
        ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
5419
5.52M
        if (ssl3_config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) {
5420
4.59M
            rv = sslBuffer_AppendNumber(buf, suite->cipher_suite,
5421
4.59M
                                        sizeof(ssl3CipherSuite));
5422
4.59M
            if (rv != SECSuccess) {
5423
0
                return SECFailure;
5424
0
            }
5425
4.59M
        }
5426
5.52M
    }
5427
5428
    /* GREASE CipherSuites:
5429
     * A client MAY select one or more GREASE cipher suite values and advertise
5430
     * them in the "cipher_suites" field [RFC8701, Section 3.1]. */
5431
77.8k
    if (ss->opt.enableGrease && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
5432
10.3k
        rv = sslBuffer_AppendNumber(buf, ss->ssl3.hs.grease->idx[grease_cipher],
5433
10.3k
                                    sizeof(ssl3CipherSuite));
5434
10.3k
        if (rv != SECSuccess) {
5435
0
            return SECFailure;
5436
0
        }
5437
10.3k
    }
5438
5439
77.8k
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange) ||
5440
77.8k
        (SSL_BUFFER_LEN(buf) - saveLen) == 0) {
5441
0
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
5442
0
        return SECFailure;
5443
0
    }
5444
5445
77.8k
    return sslBuffer_InsertLength(buf, offset, 2);
5446
77.8k
}
5447
5448
SECStatus
5449
ssl3_CreateClientHelloPreamble(sslSocket *ss, const sslSessionID *sid,
5450
                               PRBool realSid, PRUint16 version, PRBool isEchInner,
5451
                               const sslBuffer *extensions, sslBuffer *preamble)
5452
77.8k
{
5453
77.8k
    SECStatus rv;
5454
77.8k
    sslBuffer constructed = SSL_BUFFER_EMPTY;
5455
77.8k
    const PRUint8 *client_random = isEchInner ? ss->ssl3.hs.client_inner_random : ss->ssl3.hs.client_random;
5456
77.8k
    PORT_Assert(sid);
5457
77.8k
    PRBool fallbackSCSV = ss->opt.enableFallbackSCSV && !isEchInner &&
5458
36.0k
                          (!realSid || version < sid->version);
5459
5460
77.8k
    rv = sslBuffer_AppendNumber(&constructed, ssl_hs_client_hello, 1);
5461
77.8k
    if (rv != SECSuccess) {
5462
0
        goto loser;
5463
0
    }
5464
5465
77.8k
    rv = sslBuffer_Skip(&constructed, 3, NULL);
5466
77.8k
    if (rv != SECSuccess) {
5467
0
        goto loser;
5468
0
    }
5469
5470
77.8k
    if (IS_DTLS(ss)) {
5471
        /* Note that we make an unfragmented message here. We fragment in the
5472
         * transmission code, if necessary */
5473
17.3k
        rv = sslBuffer_AppendNumber(&constructed, ss->ssl3.hs.sendMessageSeq, 2);
5474
17.3k
        if (rv != SECSuccess) {
5475
0
            goto loser;
5476
0
        }
5477
17.3k
        ss->ssl3.hs.sendMessageSeq++;
5478
5479
        /* 0 is the fragment offset, because it's not fragmented yet */
5480
17.3k
        rv = sslBuffer_AppendNumber(&constructed, 0, 3);
5481
17.3k
        if (rv != SECSuccess) {
5482
0
            goto loser;
5483
0
        }
5484
5485
        /* Fragment length -- set to the packet length because not fragmented */
5486
17.3k
        rv = sslBuffer_Skip(&constructed, 3, NULL);
5487
17.3k
        if (rv != SECSuccess) {
5488
0
            goto loser;
5489
0
        }
5490
17.3k
    }
5491
5492
77.8k
    if (ss->firstHsDone) {
5493
        /* The client hello version must stay unchanged to work around
5494
         * the Windows SChannel bug described in ssl3_SendClientHello. */
5495
38.5k
        PORT_Assert(version == ss->clientHelloVersion);
5496
38.5k
    }
5497
5498
77.8k
    ss->clientHelloVersion = PR_MIN(version, SSL_LIBRARY_VERSION_TLS_1_2);
5499
77.8k
    if (IS_DTLS(ss)) {
5500
17.3k
        PRUint16 dtlsVersion = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
5501
17.3k
        rv = sslBuffer_AppendNumber(&constructed, dtlsVersion, 2);
5502
60.5k
    } else {
5503
60.5k
        rv = sslBuffer_AppendNumber(&constructed, ss->clientHelloVersion, 2);
5504
60.5k
    }
5505
77.8k
    if (rv != SECSuccess) {
5506
0
        goto loser;
5507
0
    }
5508
5509
77.8k
    rv = sslBuffer_Append(&constructed, client_random, SSL3_RANDOM_LENGTH);
5510
77.8k
    if (rv != SECSuccess) {
5511
0
        goto loser;
5512
0
    }
5513
5514
77.8k
    if (sid->version < SSL_LIBRARY_VERSION_TLS_1_3 && !isEchInner) {
5515
56.7k
        rv = sslBuffer_AppendVariable(&constructed, sid->u.ssl3.sessionID,
5516
56.7k
                                      sid->u.ssl3.sessionIDLength, 1);
5517
56.7k
    } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) {
5518
        /* We're faking session resumption, so rather than create new
5519
         * randomness, just mix up the client random a little. */
5520
3.74k
        PRUint8 buf[SSL3_SESSIONID_BYTES];
5521
3.74k
        ssl_MakeFakeSid(ss, buf);
5522
3.74k
        rv = sslBuffer_AppendVariable(&constructed, buf, SSL3_SESSIONID_BYTES, 1);
5523
17.3k
    } else {
5524
17.3k
        rv = sslBuffer_AppendNumber(&constructed, 0, 1);
5525
17.3k
    }
5526
77.8k
    if (rv != SECSuccess) {
5527
0
        goto loser;
5528
0
    }
5529
5530
77.8k
    if (IS_DTLS(ss)) {
5531
        /* This cookieLen applies to the cookie that appears in the DTLS
5532
         * ClientHello, which isn't used in DTLS 1.3. */
5533
17.3k
        rv = sslBuffer_AppendVariable(&constructed, ss->ssl3.hs.cookie.data,
5534
17.3k
                                      ss->ssl3.hs.helloRetry ? 0 : ss->ssl3.hs.cookie.len,
5535
17.3k
                                      1);
5536
17.3k
        if (rv != SECSuccess) {
5537
0
            goto loser;
5538
0
        }
5539
17.3k
    }
5540
5541
77.8k
    rv = ssl3_AppendCipherSuites(ss, fallbackSCSV, &constructed);
5542
77.8k
    if (rv != SECSuccess) {
5543
0
        goto loser;
5544
0
    }
5545
5546
    /* Compression methods: count is always 1, null compression. */
5547
77.8k
    rv = sslBuffer_AppendNumber(&constructed, 1, 1);
5548
77.8k
    if (rv != SECSuccess) {
5549
0
        goto loser;
5550
0
    }
5551
77.8k
    rv = sslBuffer_AppendNumber(&constructed, ssl_compression_null, 1);
5552
77.8k
    if (rv != SECSuccess) {
5553
0
        goto loser;
5554
0
    }
5555
5556
77.8k
    rv = ssl3_InsertChHeaderSize(ss, &constructed, extensions);
5557
77.8k
    if (rv != SECSuccess) {
5558
0
        goto loser;
5559
0
    }
5560
5561
77.8k
    *preamble = constructed;
5562
77.8k
    return SECSuccess;
5563
0
loser:
5564
0
    sslBuffer_Clear(&constructed);
5565
0
    return SECFailure;
5566
77.8k
}
5567
5568
/* Called from ssl3_HandleHelloRequest(),
5569
 *             ssl3_RedoHandshake()
5570
 *             ssl_BeginClientHandshake (when resuming ssl3 session)
5571
 *             dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
5572
 *
5573
 * The |type| argument indicates what is going on here:
5574
 * - client_hello_initial is set for the very first ClientHello
5575
 * - client_hello_retry indicates that this is a second attempt after receiving
5576
 *   a HelloRetryRequest (in TLS 1.3)
5577
 * - client_hello_retransmit is used in DTLS when resending
5578
 * - client_hello_renegotiation is used to renegotiate (in TLS <1.3)
5579
 */
5580
SECStatus
5581
ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type)
5582
73.9k
{
5583
73.9k
    sslSessionID *sid;
5584
73.9k
    SECStatus rv;
5585
73.9k
    PRBool isTLS = PR_FALSE;
5586
73.9k
    PRBool requestingResume = PR_FALSE;
5587
73.9k
    PRBool unlockNeeded = PR_FALSE;
5588
73.9k
    sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
5589
73.9k
    PRUint16 version = ss->vrange.max;
5590
73.9k
    PRInt32 flags;
5591
73.9k
    sslBuffer chBuf = SSL_BUFFER_EMPTY;
5592
5593
73.9k
    SSL_TRC(3, ("%d: SSL3[%d]: send %s ClientHello handshake", SSL_GETPID(),
5594
73.9k
                ss->fd, ssl_ClientHelloTypeName(type)));
5595
5596
73.9k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5597
73.9k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5598
5599
    /* shouldn't get here if SSL3 is disabled, but ... */
5600
73.9k
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
5601
0
        PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
5602
0
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
5603
0
        return SECFailure;
5604
0
    }
5605
5606
    /* If we are responding to a HelloRetryRequest, don't reinitialize. We need
5607
     * to maintain the handshake hashes. */
5608
73.9k
    if (!ss->ssl3.hs.helloRetry) {
5609
71.0k
        ssl3_RestartHandshakeHashes(ss);
5610
71.0k
    }
5611
73.9k
    PORT_Assert(!ss->ssl3.hs.helloRetry || type == client_hello_retry);
5612
5613
73.9k
    if (type == client_hello_initial) {
5614
31.2k
        ssl_SetClientHelloSpecVersion(ss, ss->ssl3.cwSpec);
5615
31.2k
    }
5616
    /* These must be reset every handshake. */
5617
73.9k
    ssl3_ResetExtensionData(&ss->xtnData, ss);
5618
73.9k
    ss->ssl3.hs.sendingSCSV = PR_FALSE;
5619
73.9k
    ss->ssl3.hs.preliminaryInfo = 0;
5620
73.9k
    PORT_Assert(IS_DTLS(ss) || type != client_hello_retransmit);
5621
73.9k
    SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
5622
73.9k
    ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
5623
5624
    /* How many suites does our PKCS11 support (regardless of policy)? */
5625
73.9k
    if (ssl3_config_match_init(ss) == 0) {
5626
0
        return SECFailure; /* ssl3_config_match_init has set error code. */
5627
0
    }
5628
5629
    /*
5630
     * During a renegotiation, ss->clientHelloVersion will be used again to
5631
     * work around a Windows SChannel bug. Ensure that it is still enabled.
5632
     */
5633
73.9k
    if (ss->firstHsDone) {
5634
38.5k
        PORT_Assert(type != client_hello_initial);
5635
38.5k
        if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
5636
0
            PORT_SetError(SSL_ERROR_SSL_DISABLED);
5637
0
            return SECFailure;
5638
0
        }
5639
5640
38.5k
        if (ss->clientHelloVersion < ss->vrange.min ||
5641
38.5k
            ss->clientHelloVersion > ss->vrange.max) {
5642
0
            PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
5643
0
            return SECFailure;
5644
0
        }
5645
38.5k
    }
5646
5647
    /* Check if we have a ss->sec.ci.sid.
5648
     * Check that it's not expired.
5649
     * If we have an sid and it comes from an external cache, we use it. */
5650
73.9k
    if (ss->sec.ci.sid && ss->sec.ci.sid->cached == in_external_cache) {
5651
0
        PORT_Assert(!ss->sec.isServer);
5652
0
        sid = ssl_ReferenceSID(ss->sec.ci.sid);
5653
0
        SSL_TRC(3, ("%d: SSL3[%d]: using external resumption token in ClientHello",
5654
0
                    SSL_GETPID(), ss->fd));
5655
73.9k
    } else if (ss->sec.ci.sid && ss->statelessResume && type == client_hello_retry) {
5656
        /* If we are sending a second ClientHello, reuse the same SID
5657
         * as the original one. */
5658
0
        sid = ssl_ReferenceSID(ss->sec.ci.sid);
5659
73.9k
    } else if (!ss->opt.noCache) {
5660
        /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
5661
         * handles expired entries and other details.
5662
         * XXX If we've been called from ssl_BeginClientHandshake, then
5663
         * this lookup is duplicative and wasteful.
5664
         */
5665
36.0k
        sid = ssl_LookupSID(ssl_Time(ss), &ss->sec.ci.peer,
5666
36.0k
                            ss->sec.ci.port, ss->peerID, ss->url);
5667
37.8k
    } else {
5668
37.8k
        sid = NULL;
5669
37.8k
    }
5670
5671
    /* We can't resume based on a different token. If the sid exists,
5672
     * make sure the token that holds the master secret still exists ...
5673
     * If we previously did client-auth, make sure that the token that holds
5674
     * the private key still exists, is logged in, hasn't been removed, etc.
5675
     */
5676
73.9k
    if (sid) {
5677
0
        PRBool sidOK = PR_TRUE;
5678
5679
0
        if (sid->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
5680
0
            if (!tls13_ResumptionCompatible(ss, sid->u.ssl3.cipherSuite)) {
5681
0
                sidOK = PR_FALSE;
5682
0
            }
5683
0
        } else {
5684
            /* Check that the cipher suite we need is enabled. */
5685
0
            const ssl3CipherSuiteCfg *suite =
5686
0
                ssl_LookupCipherSuiteCfg(sid->u.ssl3.cipherSuite,
5687
0
                                         ss->cipherSuites);
5688
0
            SSLVersionRange vrange = { sid->version, sid->version };
5689
0
            if (!suite || !ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
5690
0
                sidOK = PR_FALSE;
5691
0
            }
5692
5693
            /* Check that no (valid) ECHConfigs are setup in combination with a
5694
             * (resumable) TLS < 1.3 session id. */
5695
0
            if (!PR_CLIST_IS_EMPTY(&ss->echConfigs)) {
5696
                /* If there are ECH configs, the client must not resume but
5697
                 * offer ECH. */
5698
0
                sidOK = PR_FALSE;
5699
0
            }
5700
0
        }
5701
5702
        /* Check that we can recover the master secret. */
5703
0
        if (sidOK) {
5704
0
            PK11SlotInfo *slot = NULL;
5705
0
            if (sid->u.ssl3.masterValid) {
5706
0
                slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
5707
0
                                         sid->u.ssl3.masterSlotID);
5708
0
            }
5709
0
            if (slot == NULL) {
5710
0
                sidOK = PR_FALSE;
5711
0
            } else {
5712
0
                PK11SymKey *wrapKey = NULL;
5713
0
                if (!PK11_IsPresent(slot) ||
5714
0
                    ((wrapKey = PK11_GetWrapKey(slot,
5715
0
                                                sid->u.ssl3.masterWrapIndex,
5716
0
                                                sid->u.ssl3.masterWrapMech,
5717
0
                                                sid->u.ssl3.masterWrapSeries,
5718
0
                                                ss->pkcs11PinArg)) == NULL)) {
5719
0
                    sidOK = PR_FALSE;
5720
0
                }
5721
0
                if (wrapKey)
5722
0
                    PK11_FreeSymKey(wrapKey);
5723
0
                PK11_FreeSlot(slot);
5724
0
                slot = NULL;
5725
0
            }
5726
0
        }
5727
        /* If we previously did client-auth, make sure that the token that
5728
        ** holds the private key still exists, is logged in, hasn't been
5729
        ** removed, etc.
5730
        */
5731
0
        if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
5732
0
            sidOK = PR_FALSE;
5733
0
        }
5734
5735
0
        if (sidOK) {
5736
            /* Set version based on the sid. */
5737
0
            if (ss->firstHsDone) {
5738
                /*
5739
                 * Windows SChannel compares the client_version inside the RSA
5740
                 * EncryptedPreMasterSecret of a renegotiation with the
5741
                 * client_version of the initial ClientHello rather than the
5742
                 * ClientHello in the renegotiation. To work around this bug, we
5743
                 * continue to use the client_version used in the initial
5744
                 * ClientHello when renegotiating.
5745
                 *
5746
                 * The client_version of the initial ClientHello is still
5747
                 * available in ss->clientHelloVersion. Ensure that
5748
                 * sid->version is bounded within
5749
                 * [ss->vrange.min, ss->clientHelloVersion], otherwise we
5750
                 * can't use sid.
5751
                 */
5752
0
                if (sid->version >= ss->vrange.min &&
5753
0
                    sid->version <= ss->clientHelloVersion) {
5754
0
                    version = ss->clientHelloVersion;
5755
0
                } else {
5756
0
                    sidOK = PR_FALSE;
5757
0
                }
5758
0
            } else {
5759
                /*
5760
                 * Check sid->version is OK first.
5761
                 * Previously, we would cap the version based on sid->version,
5762
                 * but that prevents negotiation of a higher version if the
5763
                 * previous session was reduced (e.g., with version fallback)
5764
                 */
5765
0
                if (sid->version < ss->vrange.min ||
5766
0
                    sid->version > ss->vrange.max) {
5767
0
                    sidOK = PR_FALSE;
5768
0
                }
5769
0
            }
5770
0
        }
5771
5772
0
        if (!sidOK) {
5773
0
            SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_not_ok);
5774
0
            ssl_UncacheSessionID(ss);
5775
0
            ssl_FreeSID(sid);
5776
0
            sid = NULL;
5777
0
        }
5778
0
    }
5779
5780
73.9k
    if (sid) {
5781
0
        requestingResume = PR_TRUE;
5782
0
        SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_hits);
5783
5784
0
        PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
5785
0
                      sid->u.ssl3.sessionIDLength));
5786
5787
0
        ss->ssl3.policy = sid->u.ssl3.policy;
5788
73.9k
    } else {
5789
73.9k
        SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_misses);
5790
5791
        /*
5792
         * Windows SChannel compares the client_version inside the RSA
5793
         * EncryptedPreMasterSecret of a renegotiation with the
5794
         * client_version of the initial ClientHello rather than the
5795
         * ClientHello in the renegotiation. To work around this bug, we
5796
         * continue to use the client_version used in the initial
5797
         * ClientHello when renegotiating.
5798
         */
5799
73.9k
        if (ss->firstHsDone) {
5800
38.5k
            version = ss->clientHelloVersion;
5801
38.5k
        }
5802
5803
73.9k
        sid = ssl3_NewSessionID(ss, PR_FALSE);
5804
73.9k
        if (!sid) {
5805
0
            return SECFailure; /* memory error is set */
5806
0
        }
5807
        /* ss->version isn't set yet, but the sid needs a sane value. */
5808
73.9k
        sid->version = version;
5809
73.9k
    }
5810
5811
73.9k
    isTLS = (version > SSL_LIBRARY_VERSION_3_0);
5812
73.9k
    ssl_GetSpecWriteLock(ss);
5813
73.9k
    if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
5814
        /* SSL records are not being MACed. */
5815
35.4k
        ss->ssl3.cwSpec->version = version;
5816
35.4k
    }
5817
73.9k
    ssl_ReleaseSpecWriteLock(ss);
5818
5819
73.9k
    ssl_SetSocketSID(ss, sid); /* releases the old sid */
5820
5821
    /* HACK for SCSV in SSL 3.0.  On initial handshake, prepend SCSV,
5822
     * only if TLS is disabled.
5823
     */
5824
73.9k
    if (!ss->firstHsDone && !isTLS) {
5825
        /* Must set this before calling Hello Extension Senders,
5826
         * to suppress sending of empty RI extension.
5827
         */
5828
0
        ss->ssl3.hs.sendingSCSV = PR_TRUE;
5829
0
    }
5830
5831
    /* When we attempt session resumption (only), we must lock the sid to
5832
     * prevent races with other resumption connections that receive a
5833
     * NewSessionTicket that will cause the ticket in the sid to be replaced.
5834
     * Once we've copied the session ticket into our ClientHello message, it
5835
     * is OK for the ticket to change, so we just need to make sure we hold
5836
     * the lock across the calls to ssl_ConstructExtensions.
5837
     */
5838
73.9k
    if (sid->u.ssl3.lock) {
5839
0
        unlockNeeded = PR_TRUE;
5840
0
        PR_RWLock_Rlock(sid->u.ssl3.lock);
5841
0
    }
5842
5843
    /* Generate a new random if this is the first attempt or renegotiation. */
5844
73.9k
    if (type == client_hello_initial ||
5845
69.7k
        type == client_hello_renegotiation) {
5846
69.7k
        rv = ssl3_GetNewRandom(ss->ssl3.hs.client_random);
5847
69.7k
        if (rv != SECSuccess) {
5848
0
            goto loser; /* err set by GetNewRandom. */
5849
0
        }
5850
69.7k
    }
5851
5852
73.9k
    if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
5853
17.2k
        rv = tls13_SetupClientHello(ss, type);
5854
17.2k
        if (rv != SECSuccess) {
5855
92
            goto loser;
5856
92
        }
5857
17.2k
    }
5858
5859
    /* Setup TLS ClientHello Extension Permutation? */
5860
73.8k
    if (type == client_hello_initial &&
5861
31.1k
        ss->vrange.max > SSL_LIBRARY_VERSION_3_0 &&
5862
31.1k
        ss->opt.enableChXtnPermutation) {
5863
15.8k
        rv = tls_ClientHelloExtensionPermutationSetup(ss);
5864
15.8k
        if (rv != SECSuccess) {
5865
0
            goto loser;
5866
0
        }
5867
15.8k
    }
5868
5869
73.8k
    if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
5870
73.8k
        rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_client_hello);
5871
73.8k
        if (rv != SECSuccess) {
5872
0
            goto loser;
5873
0
        }
5874
73.8k
    }
5875
5876
73.8k
    if (IS_DTLS(ss)) {
5877
17.3k
        ssl3_DisableNonDTLSSuites(ss);
5878
17.3k
    }
5879
5880
73.8k
    rv = ssl3_CreateClientHelloPreamble(ss, sid, requestingResume, version,
5881
73.8k
                                        PR_FALSE, &extensionBuf, &chBuf);
5882
73.8k
    if (rv != SECSuccess) {
5883
0
        goto loser; /* err set by ssl3_CreateClientHelloPreamble. */
5884
0
    }
5885
5886
73.8k
    if (!ss->ssl3.hs.echHpkeCtx) {
5887
69.9k
        if (extensionBuf.len) {
5888
69.9k
            rv = tls13_MaybeGreaseEch(ss, &chBuf, &extensionBuf);
5889
69.9k
            if (rv != SECSuccess) {
5890
0
                goto loser; /* err set by tls13_MaybeGreaseEch. */
5891
0
            }
5892
69.9k
            rv = ssl_InsertPaddingExtension(ss, chBuf.len, &extensionBuf);
5893
69.9k
            if (rv != SECSuccess) {
5894
0
                goto loser; /* err set by ssl_InsertPaddingExtension. */
5895
0
            }
5896
5897
69.9k
            rv = ssl3_InsertChHeaderSize(ss, &chBuf, &extensionBuf);
5898
69.9k
            if (rv != SECSuccess) {
5899
0
                goto loser; /* err set by ssl3_InsertChHeaderSize. */
5900
0
            }
5901
5902
            /* If we are sending a PSK binder, replace the dummy value. */
5903
69.9k
            if (ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)) {
5904
6.20k
                rv = tls13_WriteExtensionsWithBinder(ss, &extensionBuf, &chBuf);
5905
63.6k
            } else {
5906
63.6k
                rv = sslBuffer_AppendNumber(&chBuf, extensionBuf.len, 2);
5907
63.6k
                if (rv != SECSuccess) {
5908
0
                    goto loser;
5909
0
                }
5910
63.6k
                rv = sslBuffer_AppendBuffer(&chBuf, &extensionBuf);
5911
63.6k
            }
5912
69.9k
            if (rv != SECSuccess) {
5913
0
                goto loser; /* err set by sslBuffer_Append*. */
5914
0
            }
5915
69.9k
        }
5916
5917
        /* If we already have a message in place, we need to enqueue it.
5918
         * This empties the buffer. This is a convenient place to call
5919
         * dtls_StageHandshakeMessage to mark the message boundary.  */
5920
69.9k
        if (IS_DTLS(ss)) {
5921
17.3k
            rv = dtls_StageHandshakeMessage(ss);
5922
17.3k
            if (rv != SECSuccess) {
5923
0
                goto loser;
5924
0
            }
5925
17.3k
        }
5926
5927
        /* As here the function takes the full message and hashes it in one go,
5928
         * For DTLS1.3, we skip hashing the unnecessary header fields.
5929
         * See ssl3_AppendHandshakeHeader. */
5930
69.9k
        if (IS_DTLS(ss) && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
5931
9.18k
            rv = ssl3_AppendHandshakeSuppressHash(ss, chBuf.buf, chBuf.len);
5932
9.18k
            if (rv != SECSuccess) {
5933
0
                goto loser; /* code set */
5934
0
            }
5935
9.18k
            if (!ss->firstHsDone) {
5936
9.18k
                PORT_Assert(type == client_hello_retransmit ||
5937
9.18k
                            ss->ssl3.hs.dtls13ClientMessageBuffer.len == 0);
5938
9.18k
                sslBuffer_Clear(&ss->ssl3.hs.dtls13ClientMessageBuffer);
5939
                /* Here instead of computing the hash, we copy the data to a buffer.*/
5940
9.18k
                rv = sslBuffer_Append(&ss->ssl3.hs.dtls13ClientMessageBuffer, chBuf.buf, chBuf.len);
5941
9.18k
            }
5942
60.7k
        } else {
5943
60.7k
            rv = ssl3_AppendHandshake(ss, chBuf.buf, chBuf.len);
5944
60.7k
        }
5945
5946
69.9k
    } else {
5947
3.97k
        PORT_Assert(!IS_DTLS(ss));
5948
3.97k
        rv = tls13_ConstructClientHelloWithEch(ss, sid, !requestingResume, &chBuf, &extensionBuf);
5949
3.97k
        if (rv != SECSuccess) {
5950
0
            goto loser; /* code set */
5951
0
        }
5952
3.97k
        rv = ssl3_UpdateDefaultHandshakeHashes(ss, chBuf.buf, chBuf.len);
5953
3.97k
        if (rv != SECSuccess) {
5954
0
            goto loser; /* code set */
5955
0
        }
5956
5957
3.97k
        if (IS_DTLS(ss)) {
5958
0
            rv = dtls_StageHandshakeMessage(ss);
5959
0
            if (rv != SECSuccess) {
5960
0
                goto loser;
5961
0
            }
5962
0
        }
5963
        /* By default, all messagess are added to both the inner and
5964
         * outer transcripts. For CH (or CH2 if HRR), that's problematic. */
5965
3.97k
        rv = ssl3_AppendHandshakeSuppressHash(ss, chBuf.buf, chBuf.len);
5966
3.97k
    }
5967
73.8k
    if (rv != SECSuccess) {
5968
0
        goto loser;
5969
0
    }
5970
5971
73.8k
    if (unlockNeeded) {
5972
        /* Note: goto loser can't be used past this point. */
5973
0
        PR_RWLock_Unlock(sid->u.ssl3.lock);
5974
0
    }
5975
5976
73.8k
    if (ss->xtnData.sentSessionTicketInClientHello) {
5977
0
        SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes);
5978
0
    }
5979
5980
73.8k
    if (ss->ssl3.hs.sendingSCSV) {
5981
        /* Since we sent the SCSV, pretend we sent empty RI extension. */
5982
0
        TLSExtensionData *xtnData = &ss->xtnData;
5983
0
        xtnData->advertised[xtnData->numAdvertised++] =
5984
0
            ssl_renegotiation_info_xtn;
5985
0
    }
5986
5987
73.8k
    flags = 0;
5988
73.8k
    rv = ssl3_FlushHandshake(ss, flags);
5989
73.8k
    if (rv != SECSuccess) {
5990
0
        return rv; /* error code set by ssl3_FlushHandshake */
5991
0
    }
5992
5993
73.8k
    if (version >= SSL_LIBRARY_VERSION_TLS_1_3) {
5994
17.1k
        rv = tls13_MaybeDo0RTTHandshake(ss);
5995
17.1k
        if (rv != SECSuccess) {
5996
0
            return SECFailure; /* error code set already. */
5997
0
        }
5998
17.1k
    }
5999
6000
73.8k
    ss->ssl3.hs.ws = wait_server_hello;
6001
73.8k
    sslBuffer_Clear(&chBuf);
6002
73.8k
    sslBuffer_Clear(&extensionBuf);
6003
73.8k
    return SECSuccess;
6004
6005
92
loser:
6006
92
    if (unlockNeeded) {
6007
0
        PR_RWLock_Unlock(sid->u.ssl3.lock);
6008
0
    }
6009
92
    sslBuffer_Clear(&chBuf);
6010
92
    sslBuffer_Clear(&extensionBuf);
6011
92
    return SECFailure;
6012
73.8k
}
6013
6014
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
6015
 * complete ssl3 Hello Request.
6016
 * Caller must hold Handshake and RecvBuf locks.
6017
 */
6018
static SECStatus
6019
ssl3_HandleHelloRequest(sslSocket *ss)
6020
43.2k
{
6021
43.2k
    sslSessionID *sid = ss->sec.ci.sid;
6022
43.2k
    SECStatus rv;
6023
6024
43.2k
    SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
6025
43.2k
                SSL_GETPID(), ss->fd));
6026
6027
43.2k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
6028
43.2k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6029
43.2k
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
6030
6031
43.2k
    if (ss->ssl3.hs.ws == wait_server_hello)
6032
4.64k
        return SECSuccess;
6033
38.5k
    if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
6034
18
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
6035
18
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
6036
18
        return SECFailure;
6037
18
    }
6038
38.5k
    if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
6039
1
        (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation);
6040
1
        PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
6041
1
        return SECFailure;
6042
1
    }
6043
6044
38.5k
    if (sid) {
6045
38.5k
        ssl_UncacheSessionID(ss);
6046
38.5k
        ssl_SetSocketSID(ss, NULL);
6047
38.5k
    }
6048
6049
38.5k
    if (IS_DTLS(ss)) {
6050
0
        dtls_RehandshakeCleanup(ss);
6051
0
    }
6052
6053
38.5k
    ssl_GetXmitBufLock(ss);
6054
38.5k
    rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
6055
38.5k
    ssl_ReleaseXmitBufLock(ss);
6056
6057
38.5k
    return rv;
6058
38.5k
}
6059
6060
static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
6061
    CKM_DES3_ECB,
6062
    CKM_CAST5_ECB,
6063
    CKM_DES_ECB,
6064
    CKM_KEY_WRAP_LYNKS,
6065
    CKM_IDEA_ECB,
6066
    CKM_CAST3_ECB,
6067
    CKM_CAST_ECB,
6068
    CKM_RC5_ECB,
6069
    CKM_RC2_ECB,
6070
    CKM_CDMF_ECB,
6071
    CKM_SKIPJACK_WRAP,
6072
    CKM_SKIPJACK_CBC64,
6073
    CKM_AES_ECB,
6074
    CKM_CAMELLIA_ECB,
6075
    CKM_SEED_ECB
6076
};
6077
6078
static SECStatus
6079
ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech, unsigned int *wrapMechIndex)
6080
32.7k
{
6081
32.7k
    unsigned int i;
6082
32.7k
    for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
6083
32.7k
        if (wrapMechanismList[i] == mech) {
6084
32.7k
            *wrapMechIndex = i;
6085
32.7k
            return SECSuccess;
6086
32.7k
        }
6087
32.7k
    }
6088
0
    PORT_Assert(0);
6089
0
    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6090
0
    return SECFailure;
6091
32.7k
}
6092
6093
/* Each process sharing the server session ID cache has its own array of SymKey
6094
 * pointers for the symmetric wrapping keys that are used to wrap the master
6095
 * secrets.  There is one key for each authentication type.  These Symkeys
6096
 * correspond to the wrapped SymKeys kept in the server session cache.
6097
 */
6098
const SSLAuthType ssl_wrap_key_auth_type[SSL_NUM_WRAP_KEYS] = {
6099
    ssl_auth_rsa_decrypt,
6100
    ssl_auth_rsa_sign,
6101
    ssl_auth_rsa_pss,
6102
    ssl_auth_ecdsa,
6103
    ssl_auth_ecdh_rsa,
6104
    ssl_auth_ecdh_ecdsa
6105
};
6106
6107
static SECStatus
6108
ssl_FindIndexByWrapKey(const sslServerCert *serverCert, unsigned int *wrapKeyIndex)
6109
32.7k
{
6110
32.7k
    unsigned int i;
6111
43.1k
    for (i = 0; i < SSL_NUM_WRAP_KEYS; ++i) {
6112
43.1k
        if (SSL_CERT_IS(serverCert, ssl_wrap_key_auth_type[i])) {
6113
32.7k
            *wrapKeyIndex = i;
6114
32.7k
            return SECSuccess;
6115
32.7k
        }
6116
43.1k
    }
6117
    /* Can't assert here because we still get people using DSA certificates. */
6118
0
    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6119
0
    return SECFailure;
6120
32.7k
}
6121
6122
static PK11SymKey *
6123
ssl_UnwrapSymWrappingKey(
6124
    SSLWrappedSymWrappingKey *pWswk,
6125
    SECKEYPrivateKey *svrPrivKey,
6126
    unsigned int wrapKeyIndex,
6127
    CK_MECHANISM_TYPE masterWrapMech,
6128
    void *pwArg)
6129
0
{
6130
0
    PK11SymKey *unwrappedWrappingKey = NULL;
6131
0
    SECItem wrappedKey;
6132
0
    PK11SymKey *Ks;
6133
0
    SECKEYPublicKey pubWrapKey;
6134
0
    ECCWrappedKeyInfo *ecWrapped;
6135
6136
    /* found the wrapping key on disk. */
6137
0
    PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
6138
0
    PORT_Assert(pWswk->wrapKeyIndex == wrapKeyIndex);
6139
0
    if (pWswk->symWrapMechanism != masterWrapMech ||
6140
0
        pWswk->wrapKeyIndex != wrapKeyIndex) {
6141
0
        goto loser;
6142
0
    }
6143
0
    wrappedKey.type = siBuffer;
6144
0
    wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
6145
0
    wrappedKey.len = pWswk->wrappedSymKeyLen;
6146
0
    PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
6147
6148
0
    switch (ssl_wrap_key_auth_type[wrapKeyIndex]) {
6149
6150
0
        case ssl_auth_rsa_decrypt:
6151
0
        case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
6152
0
            unwrappedWrappingKey =
6153
0
                PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
6154
0
                                     masterWrapMech, CKA_UNWRAP, 0);
6155
0
            break;
6156
6157
0
        case ssl_auth_ecdsa:
6158
0
        case ssl_auth_ecdh_rsa:
6159
0
        case ssl_auth_ecdh_ecdsa:
6160
            /*
6161
             * For ssl_auth_ecd*, we first create an EC public key based on
6162
             * data stored with the wrappedSymmetricWrappingkey. Next,
6163
             * we do an ECDH computation involving this public key and
6164
             * the SSL server's (long-term) EC private key. The resulting
6165
             * shared secret is treated the same way as Fortezza's Ks, i.e.,
6166
             * it is used to recover the symmetric wrapping key.
6167
             *
6168
             * The data in wrappedSymmetricWrappingkey is laid out as defined
6169
             * in the ECCWrappedKeyInfo structure.
6170
             */
6171
0
            ecWrapped = (ECCWrappedKeyInfo *)pWswk->wrappedSymmetricWrappingkey;
6172
6173
0
            PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
6174
0
                            ecWrapped->wrappedKeyLen <=
6175
0
                        MAX_EC_WRAPPED_KEY_BUFLEN);
6176
6177
0
            if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
6178
0
                    ecWrapped->wrappedKeyLen >
6179
0
                MAX_EC_WRAPPED_KEY_BUFLEN) {
6180
0
                PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6181
0
                goto loser;
6182
0
            }
6183
6184
0
            pubWrapKey.keyType = ecKey;
6185
0
            pubWrapKey.u.ec.size = ecWrapped->size;
6186
0
            pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
6187
0
            pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
6188
0
            pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
6189
0
            pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
6190
0
                                               ecWrapped->encodedParamLen;
6191
6192
0
            wrappedKey.len = ecWrapped->wrappedKeyLen;
6193
0
            wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
6194
0
                              ecWrapped->pubValueLen;
6195
6196
            /* Derive Ks using ECDH */
6197
0
            Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
6198
0
                                       NULL, CKM_ECDH1_DERIVE, masterWrapMech,
6199
0
                                       CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
6200
0
            if (Ks == NULL) {
6201
0
                goto loser;
6202
0
            }
6203
6204
            /*  Use Ks to unwrap the wrapping key */
6205
0
            unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL,
6206
0
                                                     &wrappedKey, masterWrapMech,
6207
0
                                                     CKA_UNWRAP, 0);
6208
0
            PK11_FreeSymKey(Ks);
6209
6210
0
            break;
6211
6212
0
        default:
6213
0
            PORT_Assert(0);
6214
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6215
0
            goto loser;
6216
0
    }
6217
0
loser:
6218
0
    return unwrappedWrappingKey;
6219
0
}
6220
6221
typedef struct {
6222
    PK11SymKey *symWrapKey[SSL_NUM_WRAP_KEYS];
6223
} ssl3SymWrapKey;
6224
6225
static PRLock *symWrapKeysLock = NULL;
6226
static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS];
6227
6228
SECStatus
6229
ssl_FreeSymWrapKeysLock(void)
6230
8
{
6231
8
    if (symWrapKeysLock) {
6232
8
        PR_DestroyLock(symWrapKeysLock);
6233
8
        symWrapKeysLock = NULL;
6234
8
        return SECSuccess;
6235
8
    }
6236
0
    PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
6237
0
    return SECFailure;
6238
8
}
6239
6240
SECStatus
6241
SSL3_ShutdownServerCache(void)
6242
4
{
6243
4
    int i, j;
6244
6245
4
    if (!symWrapKeysLock)
6246
0
        return SECSuccess; /* lock was never initialized */
6247
4
    PR_Lock(symWrapKeysLock);
6248
    /* get rid of all symWrapKeys */
6249
64
    for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
6250
420
        for (j = 0; j < SSL_NUM_WRAP_KEYS; ++j) {
6251
360
            PK11SymKey **pSymWrapKey;
6252
360
            pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
6253
360
            if (*pSymWrapKey) {
6254
4
                PK11_FreeSymKey(*pSymWrapKey);
6255
4
                *pSymWrapKey = NULL;
6256
4
            }
6257
360
        }
6258
60
    }
6259
6260
4
    PR_Unlock(symWrapKeysLock);
6261
4
    ssl_FreeSessionCacheLocks();
6262
4
    return SECSuccess;
6263
4
}
6264
6265
SECStatus
6266
ssl_InitSymWrapKeysLock(void)
6267
8
{
6268
8
    symWrapKeysLock = PR_NewLock();
6269
8
    return symWrapKeysLock ? SECSuccess : SECFailure;
6270
8
}
6271
6272
/* Try to get wrapping key for mechanism from in-memory array.
6273
 * If that fails, look for one on disk.
6274
 * If that fails, generate a new one, put the new one on disk,
6275
 * Put the new key in the in-memory array.
6276
 *
6277
 * Note that this function performs some fairly inadvisable functions with
6278
 * certificate private keys.  ECDSA keys are used with ECDH; similarly, RSA
6279
 * signing keys are used to encrypt.  Bug 1248320.
6280
 */
6281
PK11SymKey *
6282
ssl3_GetWrappingKey(sslSocket *ss,
6283
                    PK11SlotInfo *masterSecretSlot,
6284
                    CK_MECHANISM_TYPE masterWrapMech,
6285
                    void *pwArg)
6286
32.7k
{
6287
32.7k
    SSLAuthType authType;
6288
32.7k
    SECKEYPrivateKey *svrPrivKey;
6289
32.7k
    SECKEYPublicKey *svrPubKey = NULL;
6290
32.7k
    PK11SymKey *unwrappedWrappingKey = NULL;
6291
32.7k
    PK11SymKey **pSymWrapKey;
6292
32.7k
    CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM;
6293
32.7k
    int length;
6294
32.7k
    unsigned int wrapMechIndex;
6295
32.7k
    unsigned int wrapKeyIndex;
6296
32.7k
    SECStatus rv;
6297
32.7k
    SECItem wrappedKey;
6298
32.7k
    SSLWrappedSymWrappingKey wswk;
6299
32.7k
    PK11SymKey *Ks = NULL;
6300
32.7k
    SECKEYPublicKey *pubWrapKey = NULL;
6301
32.7k
    SECKEYPrivateKey *privWrapKey = NULL;
6302
32.7k
    ECCWrappedKeyInfo *ecWrapped;
6303
32.7k
    const sslServerCert *serverCert = ss->sec.serverCert;
6304
6305
32.7k
    PORT_Assert(serverCert);
6306
32.7k
    PORT_Assert(serverCert->serverKeyPair);
6307
32.7k
    PORT_Assert(serverCert->serverKeyPair->privKey);
6308
32.7k
    PORT_Assert(serverCert->serverKeyPair->pubKey);
6309
32.7k
    if (!serverCert || !serverCert->serverKeyPair ||
6310
32.7k
        !serverCert->serverKeyPair->privKey ||
6311
32.7k
        !serverCert->serverKeyPair->pubKey) {
6312
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6313
0
        return NULL; /* hmm */
6314
0
    }
6315
6316
32.7k
    rv = ssl_FindIndexByWrapKey(serverCert, &wrapKeyIndex);
6317
32.7k
    if (rv != SECSuccess)
6318
0
        return NULL; /* unusable wrapping key. */
6319
6320
32.7k
    rv = ssl_FindIndexByWrapMechanism(masterWrapMech, &wrapMechIndex);
6321
32.7k
    if (rv != SECSuccess)
6322
0
        return NULL; /* invalid masterWrapMech. */
6323
6324
32.7k
    authType = ssl_wrap_key_auth_type[wrapKeyIndex];
6325
32.7k
    svrPrivKey = serverCert->serverKeyPair->privKey;
6326
32.7k
    pSymWrapKey = &symWrapKeys[wrapMechIndex].symWrapKey[wrapKeyIndex];
6327
6328
32.7k
    ssl_InitSessionCacheLocks(PR_TRUE);
6329
6330
32.7k
    PR_Lock(symWrapKeysLock);
6331
6332
32.7k
    unwrappedWrappingKey = *pSymWrapKey;
6333
32.7k
    if (unwrappedWrappingKey != NULL) {
6334
32.7k
        if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
6335
32.7k
            unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
6336
32.7k
            goto done;
6337
32.7k
        }
6338
        /* slot series has changed, so this key is no good any more. */
6339
0
        PK11_FreeSymKey(unwrappedWrappingKey);
6340
0
        *pSymWrapKey = unwrappedWrappingKey = NULL;
6341
0
    }
6342
6343
    /* Try to get wrapped SymWrapping key out of the (disk) cache. */
6344
    /* Following call fills in wswk on success. */
6345
68
    rv = ssl_GetWrappingKey(wrapMechIndex, wrapKeyIndex, &wswk);
6346
68
    if (rv == SECSuccess) {
6347
        /* found the wrapped sym wrapping key on disk. */
6348
0
        unwrappedWrappingKey =
6349
0
            ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
6350
0
                                     masterWrapMech, pwArg);
6351
0
        if (unwrappedWrappingKey) {
6352
0
            goto install;
6353
0
        }
6354
0
    }
6355
6356
68
    if (!masterSecretSlot) /* caller doesn't want to create a new one. */
6357
0
        goto loser;
6358
6359
68
    length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
6360
    /* Zero length means fixed key length algorithm, or error.
6361
     * It's ambiguous.
6362
     */
6363
68
    unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
6364
68
                                       length, pwArg);
6365
68
    if (!unwrappedWrappingKey) {
6366
0
        goto loser;
6367
0
    }
6368
6369
    /* Prepare the buffer to receive the wrappedWrappingKey,
6370
     * the symmetric wrapping key wrapped using the server's pub key.
6371
     */
6372
68
    PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */
6373
6374
68
    svrPubKey = serverCert->serverKeyPair->pubKey;
6375
68
    wrappedKey.type = siBuffer;
6376
68
    wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey);
6377
68
    wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
6378
6379
68
    PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
6380
68
    if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
6381
0
        goto loser;
6382
6383
    /* wrap symmetric wrapping key in server's public key. */
6384
68
    switch (authType) {
6385
2
        case ssl_auth_rsa_decrypt:
6386
2
        case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
6387
2
        case ssl_auth_rsa_pss:
6388
2
            asymWrapMechanism = CKM_RSA_PKCS;
6389
2
            rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
6390
2
                                    unwrappedWrappingKey, &wrappedKey);
6391
2
            break;
6392
6393
66
        case ssl_auth_ecdsa:
6394
66
        case ssl_auth_ecdh_rsa:
6395
66
        case ssl_auth_ecdh_ecdsa:
6396
            /*
6397
             * We generate an ephemeral EC key pair. Perform an ECDH
6398
             * computation involving this ephemeral EC public key and
6399
             * the SSL server's (long-term) EC private key. The resulting
6400
             * shared secret is treated in the same way as Fortezza's Ks,
6401
             * i.e., it is used to wrap the wrapping key. To facilitate
6402
             * unwrapping in ssl_UnwrapWrappingKey, we also store all
6403
             * relevant info about the ephemeral EC public key in
6404
             * wswk.wrappedSymmetricWrappingkey and lay it out as
6405
             * described in the ECCWrappedKeyInfo structure.
6406
             */
6407
66
            PORT_Assert(SECKEY_GetPublicKeyType(svrPubKey) == ecKey);
6408
66
            if (SECKEY_GetPublicKeyType(svrPubKey) != ecKey) {
6409
                /* something is wrong in sslsecur.c if this isn't an ecKey */
6410
0
                PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6411
0
                rv = SECFailure;
6412
0
                goto ec_cleanup;
6413
0
            }
6414
6415
66
            privWrapKey = SECKEY_CreateECPrivateKey(
6416
66
                &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
6417
66
            if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
6418
0
                rv = SECFailure;
6419
0
                goto ec_cleanup;
6420
0
            }
6421
6422
            /* Set the key size in bits */
6423
66
            if (pubWrapKey->u.ec.size == 0) {
6424
66
                pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
6425
66
            }
6426
6427
66
            PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +
6428
66
                            pubWrapKey->u.ec.publicValue.len <
6429
66
                        MAX_EC_WRAPPED_KEY_BUFLEN);
6430
66
            if (pubWrapKey->u.ec.DEREncodedParams.len +
6431
66
                    pubWrapKey->u.ec.publicValue.len >=
6432
66
                MAX_EC_WRAPPED_KEY_BUFLEN) {
6433
0
                PORT_SetError(SEC_ERROR_INVALID_KEY);
6434
0
                rv = SECFailure;
6435
0
                goto ec_cleanup;
6436
0
            }
6437
6438
            /* Derive Ks using ECDH */
6439
66
            Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
6440
66
                                       NULL, CKM_ECDH1_DERIVE, masterWrapMech,
6441
66
                                       CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
6442
66
            if (Ks == NULL) {
6443
64
                rv = SECFailure;
6444
64
                goto ec_cleanup;
6445
64
            }
6446
6447
2
            ecWrapped = (ECCWrappedKeyInfo *)(wswk.wrappedSymmetricWrappingkey);
6448
2
            ecWrapped->size = pubWrapKey->u.ec.size;
6449
2
            ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
6450
2
            PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
6451
2
                        pubWrapKey->u.ec.DEREncodedParams.len);
6452
6453
2
            ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
6454
2
            PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen,
6455
2
                        pubWrapKey->u.ec.publicValue.data,
6456
2
                        pubWrapKey->u.ec.publicValue.len);
6457
6458
2
            wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN -
6459
2
                             (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
6460
2
            wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
6461
2
                              ecWrapped->pubValueLen;
6462
6463
            /* wrap symmetricWrapping key with the local Ks */
6464
2
            rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
6465
2
                                 unwrappedWrappingKey, &wrappedKey);
6466
6467
2
            if (rv != SECSuccess) {
6468
0
                goto ec_cleanup;
6469
0
            }
6470
6471
            /* Write down the length of wrapped key in the buffer
6472
             * wswk.wrappedSymmetricWrappingkey at the appropriate offset
6473
             */
6474
2
            ecWrapped->wrappedKeyLen = wrappedKey.len;
6475
6476
66
        ec_cleanup:
6477
66
            if (privWrapKey)
6478
66
                SECKEY_DestroyPrivateKey(privWrapKey);
6479
66
            if (pubWrapKey)
6480
66
                SECKEY_DestroyPublicKey(pubWrapKey);
6481
66
            if (Ks)
6482
2
                PK11_FreeSymKey(Ks);
6483
66
            asymWrapMechanism = masterWrapMech;
6484
66
            break;
6485
6486
0
        default:
6487
0
            rv = SECFailure;
6488
0
            break;
6489
68
    }
6490
6491
68
    if (rv != SECSuccess) {
6492
64
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6493
64
        goto loser;
6494
64
    }
6495
6496
4
    PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
6497
6498
4
    wswk.symWrapMechanism = masterWrapMech;
6499
4
    wswk.asymWrapMechanism = asymWrapMechanism;
6500
4
    wswk.wrapMechIndex = wrapMechIndex;
6501
4
    wswk.wrapKeyIndex = wrapKeyIndex;
6502
4
    wswk.wrappedSymKeyLen = wrappedKey.len;
6503
6504
    /* put it on disk. */
6505
    /* If the wrapping key for this KEA type has already been set,
6506
     * then abandon the value we just computed and
6507
     * use the one we got from the disk.
6508
     */
6509
4
    rv = ssl_SetWrappingKey(&wswk);
6510
4
    if (rv == SECSuccess) {
6511
        /* somebody beat us to it.  The original contents of our wswk
6512
         * has been replaced with the content on disk.  Now, discard
6513
         * the key we just created and unwrap this new one.
6514
         */
6515
0
        PK11_FreeSymKey(unwrappedWrappingKey);
6516
6517
0
        unwrappedWrappingKey =
6518
0
            ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
6519
0
                                     masterWrapMech, pwArg);
6520
0
    }
6521
6522
4
install:
6523
4
    if (unwrappedWrappingKey) {
6524
4
        *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
6525
4
    }
6526
6527
68
loser:
6528
32.7k
done:
6529
32.7k
    PR_Unlock(symWrapKeysLock);
6530
32.7k
    return unwrappedWrappingKey;
6531
68
}
6532
6533
#ifdef NSS_ALLOW_SSLKEYLOGFILE
6534
/* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
6535
 * bytes to |out|. */
6536
static void
6537
hexEncode(char *out, const unsigned char *in, unsigned int length)
6538
0
{
6539
0
    static const char hextable[] = "0123456789abcdef";
6540
0
    unsigned int i;
6541
6542
0
    for (i = 0; i < length; i++) {
6543
0
        *(out++) = hextable[in[i] >> 4];
6544
0
        *(out++) = hextable[in[i] & 15];
6545
0
    }
6546
0
}
6547
#endif
6548
6549
/* Called from ssl3_SendClientKeyExchange(). */
6550
static SECStatus
6551
ssl3_SendRSAClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
6552
15.1k
{
6553
15.1k
    PK11SymKey *pms = NULL;
6554
15.1k
    SECStatus rv = SECFailure;
6555
15.1k
    SECItem enc_pms = { siBuffer, NULL, 0 };
6556
15.1k
    PRBool isTLS;
6557
6558
15.1k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6559
15.1k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6560
6561
    /* Generate the pre-master secret ...  */
6562
15.1k
    ssl_GetSpecWriteLock(ss);
6563
15.1k
    isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
6564
6565
15.1k
    pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
6566
15.1k
    ssl_ReleaseSpecWriteLock(ss);
6567
15.1k
    if (pms == NULL) {
6568
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6569
0
        goto loser;
6570
0
    }
6571
6572
    /* Get the wrapped (encrypted) pre-master secret, enc_pms */
6573
15.1k
    unsigned int svrPubKeyBits = SECKEY_PublicKeyStrengthInBits(svrPubKey);
6574
15.1k
    enc_pms.len = (svrPubKeyBits + 7) / 8;
6575
    /* Check that the RSA key isn't larger than 8k bit. */
6576
15.1k
    if (svrPubKeyBits > SSL_MAX_RSA_KEY_BITS) {
6577
13
        (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
6578
13
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6579
13
        goto loser;
6580
13
    }
6581
15.0k
    enc_pms.data = (unsigned char *)PORT_Alloc(enc_pms.len);
6582
15.0k
    if (enc_pms.data == NULL) {
6583
0
        goto loser; /* err set by PORT_Alloc */
6584
0
    }
6585
6586
    /* Wrap pre-master secret in server's public key. */
6587
15.0k
    rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
6588
15.0k
    if (rv != SECSuccess) {
6589
159
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6590
159
        goto loser;
6591
159
    }
6592
6593
14.9k
#ifdef TRACE
6594
14.9k
    if (ssl_trace >= 100) {
6595
0
        SECStatus extractRV = PK11_ExtractKeyValue(pms);
6596
0
        if (extractRV == SECSuccess) {
6597
0
            SECItem *keyData = PK11_GetKeyData(pms);
6598
0
            if (keyData && keyData->data && keyData->len) {
6599
0
                ssl_PrintBuf(ss, "Pre-Master Secret",
6600
0
                             keyData->data, keyData->len);
6601
0
            }
6602
0
        }
6603
0
    }
6604
14.9k
#endif
6605
6606
14.9k
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
6607
14.9k
                                    isTLS ? enc_pms.len + 2
6608
14.9k
                                          : enc_pms.len);
6609
14.9k
    if (rv != SECSuccess) {
6610
0
        goto loser; /* err set by ssl3_AppendHandshake* */
6611
0
    }
6612
14.9k
    if (isTLS) {
6613
14.9k
        rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
6614
14.9k
    } else {
6615
0
        rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
6616
0
    }
6617
14.9k
    if (rv != SECSuccess) {
6618
0
        goto loser; /* err set by ssl3_AppendHandshake* */
6619
0
    }
6620
6621
14.9k
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
6622
14.9k
    PK11_FreeSymKey(pms);
6623
14.9k
    pms = NULL;
6624
6625
14.9k
    if (rv != SECSuccess) {
6626
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6627
0
        goto loser;
6628
0
    }
6629
6630
14.9k
    rv = SECSuccess;
6631
6632
15.1k
loser:
6633
15.1k
    if (enc_pms.data != NULL) {
6634
15.0k
        PORT_Free(enc_pms.data);
6635
15.0k
    }
6636
15.1k
    if (pms != NULL) {
6637
172
        PK11_FreeSymKey(pms);
6638
172
    }
6639
15.1k
    return rv;
6640
14.9k
}
6641
6642
/* DH shares need to be padded to the size of their prime.  Some implementations
6643
 * require this.  TLS 1.3 also requires this. */
6644
SECStatus
6645
ssl_AppendPaddedDHKeyShare(sslBuffer *buf, const SECKEYPublicKey *pubKey,
6646
                           PRBool appendLength)
6647
6.45k
{
6648
6.45k
    SECStatus rv;
6649
6.45k
    unsigned int pad = pubKey->u.dh.prime.len - pubKey->u.dh.publicValue.len;
6650
6651
6.45k
    if (appendLength) {
6652
3.86k
        rv = sslBuffer_AppendNumber(buf, pubKey->u.dh.prime.len, 2);
6653
3.86k
        if (rv != SECSuccess) {
6654
0
            return rv;
6655
0
        }
6656
3.86k
    }
6657
6.45k
    while (pad) {
6658
1
        rv = sslBuffer_AppendNumber(buf, 0, 1);
6659
1
        if (rv != SECSuccess) {
6660
0
            return rv;
6661
0
        }
6662
1
        --pad;
6663
1
    }
6664
6.45k
    rv = sslBuffer_Append(buf, pubKey->u.dh.publicValue.data,
6665
6.45k
                          pubKey->u.dh.publicValue.len);
6666
6.45k
    if (rv != SECSuccess) {
6667
0
        return rv;
6668
0
    }
6669
6.45k
    return SECSuccess;
6670
6.45k
}
6671
6672
/* Called from ssl3_SendClientKeyExchange(). */
6673
static SECStatus
6674
ssl3_SendDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
6675
73
{
6676
73
    PK11SymKey *pms = NULL;
6677
73
    SECStatus rv;
6678
73
    PRBool isTLS;
6679
73
    CK_MECHANISM_TYPE target;
6680
6681
73
    const ssl3DHParams *params;
6682
73
    ssl3DHParams customParams;
6683
73
    const sslNamedGroupDef *groupDef;
6684
73
    static const sslNamedGroupDef customGroupDef = {
6685
73
        ssl_grp_ffdhe_custom, 0, ssl_kea_dh, SEC_OID_TLS_DHE_CUSTOM, PR_FALSE
6686
73
    };
6687
73
    sslEphemeralKeyPair *keyPair = NULL;
6688
73
    SECKEYPublicKey *pubKey;
6689
73
    PRUint8 dhData[SSL_MAX_DH_KEY_BITS / 8 + 2];
6690
73
    sslBuffer dhBuf = SSL_BUFFER(dhData);
6691
6692
73
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6693
73
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6694
6695
73
    isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
6696
6697
    /* Copy DH parameters from server key */
6698
6699
73
    if (SECKEY_GetPublicKeyType(svrPubKey) != dhKey) {
6700
0
        PORT_SetError(SEC_ERROR_BAD_KEY);
6701
0
        return SECFailure;
6702
0
    }
6703
6704
    /* Work out the parameters. */
6705
73
    rv = ssl_ValidateDHENamedGroup(ss, &svrPubKey->u.dh.prime,
6706
73
                                   &svrPubKey->u.dh.base,
6707
73
                                   &groupDef, &params);
6708
73
    if (rv != SECSuccess) {
6709
        /* If we require named groups, we will have already validated the group
6710
         * in ssl_HandleDHServerKeyExchange() */
6711
69
        PORT_Assert(!ss->opt.requireDHENamedGroups &&
6712
69
                    !ss->xtnData.peerSupportsFfdheGroups);
6713
6714
69
        customParams.name = ssl_grp_ffdhe_custom;
6715
69
        customParams.prime.data = svrPubKey->u.dh.prime.data;
6716
69
        customParams.prime.len = svrPubKey->u.dh.prime.len;
6717
69
        customParams.base.data = svrPubKey->u.dh.base.data;
6718
69
        customParams.base.len = svrPubKey->u.dh.base.len;
6719
69
        params = &customParams;
6720
69
        groupDef = &customGroupDef;
6721
69
    }
6722
73
    ss->sec.keaGroup = groupDef;
6723
6724
73
    rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
6725
73
    if (rv != SECSuccess) {
6726
66
        ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
6727
66
        goto loser;
6728
66
    }
6729
7
    pubKey = keyPair->keys->pubKey;
6730
7
    PRINT_BUF(50, (ss, "DH public value:",
6731
7
                   pubKey->u.dh.publicValue.data,
6732
7
                   pubKey->u.dh.publicValue.len));
6733
6734
7
    if (isTLS)
6735
7
        target = CKM_TLS_MASTER_KEY_DERIVE_DH;
6736
0
    else
6737
0
        target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
6738
6739
    /* Determine the PMS */
6740
7
    pms = PK11_PubDerive(keyPair->keys->privKey, svrPubKey,
6741
7
                         PR_FALSE, NULL, NULL, CKM_DH_PKCS_DERIVE,
6742
7
                         target, CKA_DERIVE, 0, NULL);
6743
6744
7
    if (pms == NULL) {
6745
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6746
0
        goto loser;
6747
0
    }
6748
6749
    /* Note: send the DH share padded to avoid triggering bugs. */
6750
7
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
6751
7
                                    params->prime.len + 2);
6752
7
    if (rv != SECSuccess) {
6753
0
        goto loser; /* err set by ssl3_AppendHandshake* */
6754
0
    }
6755
7
    rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE);
6756
7
    if (rv != SECSuccess) {
6757
0
        goto loser; /* err set by ssl_AppendPaddedDHKeyShare */
6758
0
    }
6759
7
    rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
6760
7
    if (rv != SECSuccess) {
6761
0
        goto loser; /* err set by ssl3_AppendBufferToHandshake */
6762
0
    }
6763
6764
7
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
6765
7
    if (rv != SECSuccess) {
6766
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6767
0
        goto loser;
6768
0
    }
6769
6770
7
    sslBuffer_Clear(&dhBuf);
6771
7
    PK11_FreeSymKey(pms);
6772
7
    ssl_FreeEphemeralKeyPair(keyPair);
6773
7
    return SECSuccess;
6774
6775
66
loser:
6776
66
    if (pms)
6777
0
        PK11_FreeSymKey(pms);
6778
66
    if (keyPair)
6779
0
        ssl_FreeEphemeralKeyPair(keyPair);
6780
66
    sslBuffer_Clear(&dhBuf);
6781
66
    return SECFailure;
6782
7
}
6783
6784
/* Called from ssl3_HandleServerHelloDone(). */
6785
static SECStatus
6786
ssl3_SendClientKeyExchange(sslSocket *ss)
6787
45.8k
{
6788
45.8k
    SECKEYPublicKey *serverKey = NULL;
6789
45.8k
    SECStatus rv = SECFailure;
6790
6791
45.8k
    SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
6792
45.8k
                SSL_GETPID(), ss->fd));
6793
6794
45.8k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6795
45.8k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6796
6797
45.8k
    if (ss->sec.peerKey == NULL) {
6798
45.7k
        serverKey = SECKEY_ExtractPublicKey(ss->sec.peerCertSPKI);
6799
45.7k
        if (serverKey == NULL) {
6800
0
            ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
6801
0
            return SECFailure;
6802
0
        }
6803
45.7k
    } else {
6804
179
        serverKey = ss->sec.peerKey;
6805
179
        ss->sec.peerKey = NULL; /* we're done with it now */
6806
179
    }
6807
6808
45.8k
    ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
6809
45.8k
    ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
6810
6811
45.8k
    switch (ss->ssl3.hs.kea_def->exchKeyType) {
6812
15.1k
        case ssl_kea_rsa:
6813
15.1k
            rv = ssl3_SendRSAClientKeyExchange(ss, serverKey);
6814
15.1k
            break;
6815
6816
73
        case ssl_kea_dh:
6817
73
            rv = ssl3_SendDHClientKeyExchange(ss, serverKey);
6818
73
            break;
6819
6820
30.7k
        case ssl_kea_ecdh:
6821
30.7k
            rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
6822
30.7k
            break;
6823
6824
0
        default:
6825
0
            PORT_Assert(0);
6826
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6827
0
            break;
6828
45.8k
    }
6829
6830
45.8k
    SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
6831
45.8k
                SSL_GETPID(), ss->fd));
6832
6833
45.8k
    SECKEY_DestroyPublicKey(serverKey);
6834
45.8k
    return rv; /* err code already set. */
6835
45.8k
}
6836
6837
/* Used by ssl_PickSignatureScheme(). */
6838
PRBool
6839
ssl_CanUseSignatureScheme(SSLSignatureScheme scheme,
6840
                          const SSLSignatureScheme *peerSchemes,
6841
                          unsigned int peerSchemeCount,
6842
                          PRBool requireSha1,
6843
                          PRBool slotDoesPss)
6844
24.3k
{
6845
24.3k
    SSLHashType hashType;
6846
24.3k
    unsigned int i;
6847
6848
    /* Skip RSA-PSS schemes when the certificate's private key slot does
6849
     * not support this signature mechanism. */
6850
24.3k
    if (ssl_IsRsaPssSignatureScheme(scheme) && !slotDoesPss) {
6851
0
        return PR_FALSE;
6852
0
    }
6853
6854
24.3k
    hashType = ssl_SignatureSchemeToHashType(scheme);
6855
24.3k
    if (requireSha1 && (hashType != ssl_hash_sha1)) {
6856
0
        return PR_FALSE;
6857
0
    }
6858
6859
24.3k
    if (!ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy)) {
6860
0
        return PR_FALSE;
6861
0
    }
6862
6863
81.2k
    for (i = 0; i < peerSchemeCount; i++) {
6864
63.7k
        if (peerSchemes[i] == scheme) {
6865
6.92k
            return PR_TRUE;
6866
6.92k
        }
6867
63.7k
    }
6868
17.4k
    return PR_FALSE;
6869
24.3k
}
6870
6871
SECStatus
6872
ssl_PrivateKeySupportsRsaPss(SECKEYPrivateKey *privKey, CERTCertificate *cert,
6873
                             void *pwarg, PRBool *supportsRsaPss)
6874
11.0k
{
6875
11.0k
    PK11SlotInfo *slot = NULL;
6876
11.0k
    if (privKey) {
6877
11.0k
        slot = PK11_GetSlotFromPrivateKey(privKey);
6878
11.0k
    } else {
6879
0
        CK_OBJECT_HANDLE certID = PK11_FindObjectForCert(cert, pwarg, &slot);
6880
0
        if (certID == CK_INVALID_HANDLE) {
6881
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6882
0
            return SECFailure;
6883
0
        }
6884
0
    }
6885
11.0k
    if (!slot) {
6886
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6887
0
        return SECFailure;
6888
0
    }
6889
11.0k
    *supportsRsaPss = PK11_DoesMechanism(slot, auth_alg_defs[ssl_auth_rsa_pss]);
6890
11.0k
    PK11_FreeSlot(slot);
6891
11.0k
    return SECSuccess;
6892
11.0k
}
6893
6894
SECStatus
6895
ssl_PickSignatureScheme(sslSocket *ss,
6896
                        CERTCertificate *cert,
6897
                        SECKEYPublicKey *pubKey,
6898
                        SECKEYPrivateKey *privKey,
6899
                        const SSLSignatureScheme *peerSchemes,
6900
                        unsigned int peerSchemeCount,
6901
                        PRBool requireSha1,
6902
                        SSLSignatureScheme *schemePtr)
6903
11.0k
{
6904
11.0k
    unsigned int i;
6905
11.0k
    PRBool doesRsaPss;
6906
11.0k
    PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
6907
11.0k
    SECStatus rv;
6908
11.0k
    SSLSignatureScheme scheme;
6909
11.0k
    SECOidTag spkiOid;
6910
6911
    /* We can't require SHA-1 in TLS 1.3. */
6912
11.0k
    PORT_Assert(!(requireSha1 && isTLS13));
6913
11.0k
    if (!pubKey || !cert) {
6914
0
        PORT_Assert(0);
6915
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6916
0
        return SECFailure;
6917
0
    }
6918
11.0k
    rv = ssl_PrivateKeySupportsRsaPss(privKey, cert, ss->pkcs11PinArg,
6919
11.0k
                                      &doesRsaPss);
6920
11.0k
    if (rv != SECSuccess) {
6921
0
        return SECFailure;
6922
0
    }
6923
6924
    /* If the certificate SPKI indicates a single scheme, don't search. */
6925
11.0k
    rv = ssl_SignatureSchemeFromSpki(&cert->subjectPublicKeyInfo,
6926
11.0k
                                     isTLS13, &scheme);
6927
11.0k
    if (rv != SECSuccess) {
6928
0
        return SECFailure;
6929
0
    }
6930
11.0k
    if (scheme != ssl_sig_none) {
6931
4.96k
        if (!ssl_SignatureSchemeEnabled(ss, scheme) ||
6932
4.96k
            !ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
6933
4.96k
                                       requireSha1, doesRsaPss)) {
6934
3.95k
            PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
6935
3.95k
            return SECFailure;
6936
3.95k
        }
6937
1.00k
        *schemePtr = scheme;
6938
1.00k
        return SECSuccess;
6939
4.96k
    }
6940
6941
6.06k
    spkiOid = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm);
6942
6.06k
    if (spkiOid == SEC_OID_UNKNOWN) {
6943
0
        return SECFailure;
6944
0
    }
6945
6946
    /* Now we have to search based on the key type. Go through our preferred
6947
     * schemes in order and find the first that can be used. */
6948
40.5k
    for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
6949
40.4k
        scheme = ss->ssl3.signatureSchemes[i];
6950
6951
40.4k
        if (ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13) &&
6952
19.3k
            ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
6953
19.3k
                                      requireSha1, doesRsaPss)) {
6954
5.91k
            *schemePtr = scheme;
6955
5.91k
            return SECSuccess;
6956
5.91k
        }
6957
40.4k
    }
6958
6959
150
    PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
6960
150
    return SECFailure;
6961
6.06k
}
6962
6963
static SECStatus
6964
ssl_PickFallbackSignatureScheme(sslSocket *ss, SECKEYPublicKey *pubKey)
6965
24.2k
{
6966
24.2k
    PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
6967
6968
24.2k
    switch (SECKEY_GetPublicKeyType(pubKey)) {
6969
18.4k
        case rsaKey:
6970
18.4k
            if (isTLS12) {
6971
17.9k
                ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1;
6972
17.9k
            } else {
6973
581
                ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1md5;
6974
581
            }
6975
18.4k
            break;
6976
5.75k
        case ecKey:
6977
5.75k
            ss->ssl3.hs.signatureScheme = ssl_sig_ecdsa_sha1;
6978
5.75k
            break;
6979
0
        case dsaKey:
6980
0
            ss->ssl3.hs.signatureScheme = ssl_sig_dsa_sha1;
6981
0
            break;
6982
0
        default:
6983
0
            PORT_Assert(0);
6984
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
6985
0
            return SECFailure;
6986
24.2k
    }
6987
24.2k
    return SECSuccess;
6988
24.2k
}
6989
6990
/* ssl3_PickServerSignatureScheme selects a signature scheme for signing the
6991
 * handshake.  Most of this is determined by the key pair we are using.
6992
 * Prior to TLS 1.2, the MD5/SHA1 combination is always used. With TLS 1.2, a
6993
 * client may advertise its support for signature and hash combinations. */
6994
static SECStatus
6995
ssl3_PickServerSignatureScheme(sslSocket *ss)
6996
28.4k
{
6997
28.4k
    const sslServerCert *cert = ss->sec.serverCert;
6998
28.4k
    PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
6999
7000
28.4k
    if (!isTLS12 || !ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) {
7001
        /* If the client didn't provide any signature_algorithms extension then
7002
         * we can assume that they support SHA-1: RFC5246, Section 7.4.1.4.1. */
7003
24.2k
        return ssl_PickFallbackSignatureScheme(ss, cert->serverKeyPair->pubKey);
7004
24.2k
    }
7005
7006
    /* Sets error code, if needed. */
7007
4.15k
    return ssl_PickSignatureScheme(ss, cert->serverCert,
7008
4.15k
                                   cert->serverKeyPair->pubKey,
7009
4.15k
                                   cert->serverKeyPair->privKey,
7010
4.15k
                                   ss->xtnData.sigSchemes,
7011
4.15k
                                   ss->xtnData.numSigSchemes,
7012
4.15k
                                   PR_FALSE /* requireSha1 */,
7013
4.15k
                                   &ss->ssl3.hs.signatureScheme);
7014
28.4k
}
7015
7016
SECStatus
7017
ssl_PickClientSignatureScheme(sslSocket *ss, CERTCertificate *clientCertificate,
7018
                              SECKEYPrivateKey *privKey,
7019
                              const SSLSignatureScheme *schemes,
7020
                              unsigned int numSchemes,
7021
                              SSLSignatureScheme *schemePtr)
7022
0
{
7023
0
    SECStatus rv;
7024
0
    PRBool isTLS13 = (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
7025
0
    SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(clientCertificate);
7026
7027
0
    PORT_Assert(pubKey);
7028
7029
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
7030
        /* We should have already checked that a signature scheme was
7031
         * listed in the request. */
7032
0
        PORT_Assert(schemes && numSchemes > 0);
7033
0
    }
7034
7035
0
    if (!isTLS13 &&
7036
0
        (SECKEY_GetPublicKeyType(pubKey) == rsaKey ||
7037
0
         SECKEY_GetPublicKeyType(pubKey) == dsaKey) &&
7038
0
        SECKEY_PublicKeyStrengthInBits(pubKey) <= 1024) {
7039
        /* If the key is a 1024-bit RSA or DSA key, assume conservatively that
7040
         * it may be unable to sign SHA-256 hashes. This is the case for older
7041
         * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and
7042
         * older, DSA key size is at most 1024 bits and the hash function must
7043
         * be SHA-1.
7044
         */
7045
0
        rv = ssl_PickSignatureScheme(ss, clientCertificate,
7046
0
                                     pubKey, privKey, schemes, numSchemes,
7047
0
                                     PR_TRUE /* requireSha1 */, schemePtr);
7048
0
        if (rv == SECSuccess) {
7049
0
            SECKEY_DestroyPublicKey(pubKey);
7050
0
            return SECSuccess;
7051
0
        }
7052
        /* If this fails, that's because the peer doesn't advertise SHA-1,
7053
         * so fall back to the full negotiation. */
7054
0
    }
7055
0
    rv = ssl_PickSignatureScheme(ss, clientCertificate,
7056
0
                                 pubKey, privKey, schemes, numSchemes,
7057
0
                                 PR_FALSE /* requireSha1 */, schemePtr);
7058
0
    SECKEY_DestroyPublicKey(pubKey);
7059
0
    return rv;
7060
0
}
7061
7062
/* Called from ssl3_HandleServerHelloDone(). */
7063
static SECStatus
7064
ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
7065
0
{
7066
0
    SECStatus rv = SECFailure;
7067
0
    PRBool isTLS12;
7068
0
    SECItem buf = { siBuffer, NULL, 0 };
7069
0
    SSL3Hashes hashes;
7070
0
    unsigned int len;
7071
0
    SSLHashType hashAlg;
7072
7073
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
7074
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7075
7076
0
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
7077
0
                SSL_GETPID(), ss->fd));
7078
7079
0
    ssl_GetSpecReadLock(ss);
7080
7081
0
    if (ss->ssl3.hs.hashType == handshake_hash_record) {
7082
0
        hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
7083
0
    } else {
7084
        /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
7085
0
        hashAlg = ssl_hash_none;
7086
0
    }
7087
0
    if (ss->ssl3.hs.hashType == handshake_hash_record &&
7088
0
        hashAlg != ssl3_GetSuitePrfHash(ss)) {
7089
0
        rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
7090
0
                                       ss->ssl3.hs.messages.len,
7091
0
                                       hashAlg, &hashes);
7092
0
        if (rv != SECSuccess) {
7093
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
7094
0
        }
7095
0
    } else {
7096
0
        rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
7097
0
    }
7098
0
    ssl_ReleaseSpecReadLock(ss);
7099
0
    if (rv != SECSuccess) {
7100
0
        goto done; /* err code was set by ssl3_ComputeHandshakeHash(es) */
7101
0
    }
7102
7103
0
    isTLS12 = (PRBool)(ss->version == SSL_LIBRARY_VERSION_TLS_1_2);
7104
0
    PORT_Assert(ss->version <= SSL_LIBRARY_VERSION_TLS_1_2);
7105
7106
0
    rv = ssl3_SignHashes(ss, &hashes, privKey, &buf);
7107
0
    if (rv == SECSuccess && !ss->sec.isServer) {
7108
        /* Remember the info about the slot that did the signing.
7109
        ** Later, when doing an SSL restart handshake, verify this.
7110
        ** These calls are mere accessors, and can't fail.
7111
        */
7112
0
        PK11SlotInfo *slot;
7113
0
        sslSessionID *sid = ss->sec.ci.sid;
7114
7115
0
        slot = PK11_GetSlotFromPrivateKey(privKey);
7116
0
        sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
7117
0
        sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
7118
0
        sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
7119
0
        sid->u.ssl3.clAuthValid = PR_TRUE;
7120
0
        PK11_FreeSlot(slot);
7121
0
    }
7122
0
    if (rv != SECSuccess) {
7123
0
        goto done; /* err code was set by ssl3_SignHashes */
7124
0
    }
7125
7126
0
    len = buf.len + 2 + (isTLS12 ? 2 : 0);
7127
7128
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len);
7129
0
    if (rv != SECSuccess) {
7130
0
        goto done; /* error code set by AppendHandshake */
7131
0
    }
7132
0
    if (isTLS12) {
7133
0
        rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
7134
0
        if (rv != SECSuccess) {
7135
0
            goto done; /* err set by AppendHandshake. */
7136
0
        }
7137
0
    }
7138
0
    rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
7139
0
    if (rv != SECSuccess) {
7140
0
        goto done; /* error code set by AppendHandshake */
7141
0
    }
7142
7143
0
done:
7144
0
    if (buf.data)
7145
0
        PORT_Free(buf.data);
7146
0
    return rv;
7147
0
}
7148
7149
/* Once a cipher suite has been selected, make sure that the necessary secondary
7150
 * information is properly set. */
7151
SECStatus
7152
ssl3_SetupCipherSuite(sslSocket *ss, PRBool initHashes)
7153
145k
{
7154
145k
    ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
7155
145k
    if (!ss->ssl3.hs.suite_def) {
7156
0
        PORT_Assert(0);
7157
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
7158
0
        return SECFailure;
7159
0
    }
7160
7161
145k
    ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg];
7162
145k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite;
7163
7164
145k
    if (!initHashes) {
7165
7.10k
        return SECSuccess;
7166
7.10k
    }
7167
    /* Now we have a cipher suite, initialize the handshake hashes. */
7168
138k
    return ssl3_InitHandshakeHashes(ss);
7169
145k
}
7170
7171
SECStatus
7172
ssl_ClientSetCipherSuite(sslSocket *ss, SSL3ProtocolVersion version,
7173
                         ssl3CipherSuite suite, PRBool initHashes)
7174
66.1k
{
7175
66.1k
    unsigned int i;
7176
66.1k
    if (ssl3_config_match_init(ss) == 0) {
7177
0
        PORT_Assert(PR_FALSE);
7178
0
        return SECFailure;
7179
0
    }
7180
2.77M
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
7181
2.77M
        ssl3CipherSuiteCfg *suiteCfg = &ss->cipherSuites[i];
7182
2.77M
        if (suite == suiteCfg->cipher_suite) {
7183
66.1k
            SSLVersionRange vrange = { version, version };
7184
66.1k
            if (!ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) {
7185
                /* config_match already checks whether the cipher suite is
7186
                 * acceptable for the version, but the check is repeated here
7187
                 * in order to give a more precise error code. */
7188
123
                if (!ssl3_CipherSuiteAllowedForVersionRange(suite, &vrange)) {
7189
114
                    PORT_SetError(SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION);
7190
114
                } else {
7191
9
                    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
7192
9
                }
7193
123
                return SECFailure;
7194
123
            }
7195
66.0k
            break;
7196
66.1k
        }
7197
2.77M
    }
7198
66.0k
    if (i >= ssl_V3_SUITES_IMPLEMENTED) {
7199
47
        PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
7200
47
        return SECFailure;
7201
47
    }
7202
7203
    /* Don't let the server change its mind. */
7204
66.0k
    if (ss->ssl3.hs.helloRetry && suite != ss->ssl3.hs.cipher_suite) {
7205
4
        (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
7206
4
        PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
7207
4
        return SECFailure;
7208
4
    }
7209
7210
66.0k
    ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)suite;
7211
66.0k
    return ssl3_SetupCipherSuite(ss, initHashes);
7212
66.0k
}
7213
7214
/* Check that session ID we received from the server, if any, matches our
7215
 * expectations, depending on whether we're in compat mode and whether we
7216
 * negotiated TLS 1.3+ or TLS 1.2-.
7217
 */
7218
static PRBool
7219
ssl_CheckServerSessionIdCorrectness(sslSocket *ss, SECItem *sidBytes)
7220
66.1k
{
7221
66.1k
    sslSessionID *sid = ss->sec.ci.sid;
7222
66.1k
    PRBool sidMatch = PR_FALSE;
7223
66.1k
    PRBool sentFakeSid = PR_FALSE;
7224
66.1k
    PRBool sentRealSid = sid && sid->version < SSL_LIBRARY_VERSION_TLS_1_3;
7225
7226
    /* If attempting to resume a TLS 1.2 connection, the session ID won't be a
7227
     * fake. Check for the real value. */
7228
66.1k
    if (sentRealSid) {
7229
52.9k
        sidMatch = (sidBytes->len == sid->u.ssl3.sessionIDLength) &&
7230
48.0k
                   (!sidBytes->len || PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len) == 0);
7231
52.9k
    } else {
7232
        /* Otherwise, the session ID was a fake if TLS 1.3 compat mode is
7233
         * enabled.  If so, check for the fake value. */
7234
13.2k
        sentFakeSid = ss->opt.enableTls13CompatMode && !IS_DTLS(ss);
7235
13.2k
        if (sentFakeSid && sidBytes->len == SSL3_SESSIONID_BYTES) {
7236
780
            PRUint8 buf[SSL3_SESSIONID_BYTES];
7237
780
            ssl_MakeFakeSid(ss, buf);
7238
780
            sidMatch = PORT_Memcmp(buf, sidBytes->data, sidBytes->len) == 0;
7239
780
        }
7240
13.2k
    }
7241
7242
    /* TLS 1.2: Session ID shouldn't match if we sent a fake. */
7243
66.1k
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
7244
60.5k
        if (sentFakeSid) {
7245
2.09k
            return !sidMatch;
7246
2.09k
        }
7247
58.4k
        return PR_TRUE;
7248
60.5k
    }
7249
7250
    /* TLS 1.3: We sent a session ID.  The server's should match. */
7251
5.61k
    if (!IS_DTLS(ss) && (sentRealSid || sentFakeSid)) {
7252
15
        return sidMatch;
7253
15
    }
7254
7255
    /* TLS 1.3 (no SID)/DTLS 1.3: The server shouldn't send a session ID. */
7256
5.59k
    return sidBytes->len == 0;
7257
5.61k
}
7258
7259
static SECStatus
7260
ssl_CheckServerRandom(sslSocket *ss)
7261
70.0k
{
7262
    /* Check the ServerHello.random per [RFC 8446 Section 4.1.3].
7263
     *
7264
     * TLS 1.3 clients receiving a ServerHello indicating TLS 1.2 or below
7265
     * MUST check that the last 8 bytes are not equal to either of these
7266
     * values.  TLS 1.2 clients SHOULD also check that the last 8 bytes are
7267
     * not equal to the second value if the ServerHello indicates TLS 1.1 or
7268
     * below.  If a match is found, the client MUST abort the handshake with
7269
     * an "illegal_parameter" alert.
7270
     */
7271
70.0k
    SSL3ProtocolVersion checkVersion =
7272
70.0k
        ss->ssl3.downgradeCheckVersion ? ss->ssl3.downgradeCheckVersion
7273
70.0k
                                       : ss->vrange.max;
7274
7275
70.0k
    if (checkVersion >= SSL_LIBRARY_VERSION_TLS_1_2 &&
7276
50.5k
        checkVersion > ss->version) {
7277
        /* Both sections use the same sentinel region. */
7278
22.4k
        PRUint8 *downgrade_sentinel =
7279
22.4k
            ss->ssl3.hs.server_random +
7280
22.4k
            SSL3_RANDOM_LENGTH - sizeof(tls12_downgrade_random);
7281
7282
22.4k
        if (!PORT_Memcmp(downgrade_sentinel,
7283
22.4k
                         tls12_downgrade_random,
7284
22.4k
                         sizeof(tls12_downgrade_random)) ||
7285
22.4k
            !PORT_Memcmp(downgrade_sentinel,
7286
22.4k
                         tls1_downgrade_random,
7287
22.4k
                         sizeof(tls1_downgrade_random))) {
7288
8
            return SECFailure;
7289
8
        }
7290
22.4k
    }
7291
7292
70.0k
    return SECSuccess;
7293
70.0k
}
7294
7295
/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7296
 * ssl3 ServerHello message.
7297
 * Caller must hold Handshake and RecvBuf locks.
7298
 */
7299
static SECStatus
7300
ssl3_HandleServerHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
7301
67.4k
{
7302
67.4k
    PRUint32 cipher;
7303
67.4k
    int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7304
67.4k
    PRUint32 compression;
7305
67.4k
    SECStatus rv;
7306
67.4k
    SECItem sidBytes = { siBuffer, NULL, 0 };
7307
67.4k
    PRBool isHelloRetry;
7308
67.4k
    SSL3AlertDescription desc = illegal_parameter;
7309
67.4k
    const PRUint8 *savedMsg = b;
7310
67.4k
    const PRUint32 savedLength = length;
7311
7312
67.4k
    SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
7313
67.4k
                SSL_GETPID(), ss->fd));
7314
67.4k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7315
67.4k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7316
7317
67.4k
    if (ss->ssl3.hs.ws != wait_server_hello) {
7318
85
        errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
7319
85
        desc = unexpected_message;
7320
85
        goto alert_loser;
7321
85
    }
7322
7323
    /* clean up anything left from previous handshake. */
7324
67.3k
    if (ss->ssl3.clientCertChain != NULL) {
7325
0
        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
7326
0
        ss->ssl3.clientCertChain = NULL;
7327
0
    }
7328
67.3k
    if (ss->ssl3.clientCertificate != NULL) {
7329
0
        CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7330
0
        ss->ssl3.clientCertificate = NULL;
7331
0
    }
7332
67.3k
    if (ss->ssl3.clientPrivateKey != NULL) {
7333
0
        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7334
0
        ss->ssl3.clientPrivateKey = NULL;
7335
0
    }
7336
    // TODO(djackson) - Bob removed this. Why?
7337
67.3k
    if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL) {
7338
0
        PR_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
7339
0
        ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
7340
0
        ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
7341
0
    }
7342
7343
    /* Note that if the server selects TLS 1.3, this will set the version to TLS
7344
     * 1.2.  We will amend that once all other fields have been read. */
7345
67.3k
    rv = ssl_ClientReadVersion(ss, &b, &length, &ss->version);
7346
67.3k
    if (rv != SECSuccess) {
7347
71
        goto loser; /* alert has been sent */
7348
71
    }
7349
7350
67.2k
    rv = ssl3_ConsumeHandshake(
7351
67.2k
        ss, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
7352
67.2k
    if (rv != SECSuccess) {
7353
57
        goto loser; /* alert has been sent */
7354
57
    }
7355
67.1k
    isHelloRetry = !PORT_Memcmp(ss->ssl3.hs.server_random,
7356
67.1k
                                ssl_hello_retry_random, SSL3_RANDOM_LENGTH);
7357
7358
67.1k
    rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
7359
67.1k
    if (rv != SECSuccess) {
7360
429
        goto loser; /* alert has been sent */
7361
429
    }
7362
66.7k
    if (sidBytes.len > SSL3_SESSIONID_BYTES) {
7363
34
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_0)
7364
10
            desc = decode_error;
7365
34
        goto alert_loser; /* malformed. */
7366
34
    }
7367
7368
    /* Read the cipher suite. */
7369
66.7k
    rv = ssl3_ConsumeHandshakeNumber(ss, &cipher, 2, &b, &length);
7370
66.7k
    if (rv != SECSuccess) {
7371
78
        goto loser; /* alert has been sent */
7372
78
    }
7373
7374
    /* Compression method. */
7375
66.6k
    rv = ssl3_ConsumeHandshakeNumber(ss, &compression, 1, &b, &length);
7376
66.6k
    if (rv != SECSuccess) {
7377
10
        goto loser; /* alert has been sent */
7378
10
    }
7379
66.6k
    if (compression != ssl_compression_null) {
7380
31
        desc = illegal_parameter;
7381
31
        errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7382
31
        goto alert_loser;
7383
31
    }
7384
7385
    /* Parse extensions. */
7386
66.6k
    if (length != 0) {
7387
13.2k
        PRUint32 extensionLength;
7388
13.2k
        rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
7389
13.2k
        if (rv != SECSuccess) {
7390
4
            goto loser; /* alert already sent */
7391
4
        }
7392
13.2k
        if (extensionLength != length) {
7393
97
            desc = decode_error;
7394
97
            goto alert_loser;
7395
97
        }
7396
13.1k
        rv = ssl3_ParseExtensions(ss, &b, &length);
7397
13.1k
        if (rv != SECSuccess) {
7398
153
            goto alert_loser; /* malformed */
7399
153
        }
7400
13.1k
    }
7401
7402
    /* Read supported_versions if present. */
7403
66.3k
    rv = tls13_ClientReadSupportedVersion(ss);
7404
66.3k
    if (rv != SECSuccess) {
7405
64
        goto loser;
7406
64
    }
7407
7408
    /* RFC 9147. 5.2.
7409
     * DTLS Handshake Message Format states the difference between the computation
7410
     * of the transcript if the version is DTLS1.2 or DTLS1.3.
7411
     *
7412
     * At this moment we are sure which version
7413
     * we are planning to use during the connection, so we can compute the hash. */
7414
66.2k
    rv = ssl3_MaybeUpdateHashWithSavedRecord(ss);
7415
66.2k
    if (rv != SECSuccess) {
7416
0
        goto loser;
7417
0
    }
7418
7419
66.2k
    PORT_Assert(!SSL_ALL_VERSIONS_DISABLED(&ss->vrange));
7420
    /* Check that the version is within the configured range. */
7421
66.2k
    if (ss->vrange.min > ss->version || ss->vrange.max < ss->version) {
7422
76
        desc = (ss->version > SSL_LIBRARY_VERSION_3_0)
7423
76
                   ? protocol_version
7424
76
                   : handshake_failure;
7425
76
        errCode = SSL_ERROR_UNSUPPORTED_VERSION;
7426
76
        goto alert_loser;
7427
76
    }
7428
7429
66.2k
    if (isHelloRetry && ss->ssl3.hs.helloRetry) {
7430
4
        SSL_TRC(3, ("%d: SSL3[%d]: received a second hello_retry_request",
7431
4
                    SSL_GETPID(), ss->fd));
7432
4
        desc = unexpected_message;
7433
4
        errCode = SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST;
7434
4
        goto alert_loser;
7435
4
    }
7436
7437
    /* A server that sent HelloVerifyRequest is DTLS 1.2 or earlier;
7438
     * reject a subsequent TLS 1.3 ServerHello as illegal. */
7439
66.2k
    if (ss->ssl3.hs.dtlsReceivedHVR &&
7440
16
        ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
7441
2
        desc = illegal_parameter;
7442
2
        errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7443
2
        goto alert_loser;
7444
2
    }
7445
7446
    /* There are three situations in which the server must pick
7447
     * TLS 1.3.
7448
     *
7449
     * 1. We received HRR
7450
     * 2. We sent early app data
7451
     * 3. ECH was accepted (checked in MaybeHandleEchSignal)
7452
     *
7453
     * If we offered ECH and the server negotiated a lower version,
7454
     * authenticate to the public name for secure disablement.
7455
     *
7456
     */
7457
66.2k
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
7458
60.5k
        if (isHelloRetry || ss->ssl3.hs.helloRetry) {
7459
            /* SSL3_SendAlert() will uncache the SID. */
7460
10
            desc = illegal_parameter;
7461
10
            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7462
10
            goto alert_loser;
7463
10
        }
7464
60.5k
        if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
7465
            /* SSL3_SendAlert() will uncache the SID. */
7466
0
            desc = illegal_parameter;
7467
0
            errCode = SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA;
7468
0
            goto alert_loser;
7469
0
        }
7470
60.5k
    }
7471
7472
    /* Check that the server negotiated the same version as it did
7473
     * in the first handshake. This isn't really the best place for
7474
     * us to be getting this version number, but it's what we have.
7475
     * (1294697). */
7476
66.1k
    if (ss->firstHsDone && (ss->version != ss->ssl3.crSpec->version)) {
7477
3
        desc = protocol_version;
7478
3
        errCode = SSL_ERROR_UNSUPPORTED_VERSION;
7479
3
        goto alert_loser;
7480
3
    }
7481
7482
66.1k
    if (ss->opt.enableHelloDowngradeCheck) {
7483
66.1k
        rv = ssl_CheckServerRandom(ss);
7484
66.1k
        if (rv != SECSuccess) {
7485
8
            desc = illegal_parameter;
7486
8
            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7487
8
            goto alert_loser;
7488
8
        }
7489
66.1k
    }
7490
7491
    /* Finally, now all the version-related checks have passed. */
7492
66.1k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
7493
    /* Update the write cipher spec to match the version. But not after
7494
     * HelloRetryRequest, because cwSpec might be a 0-RTT cipher spec,
7495
     * in which case this is a no-op. */
7496
66.1k
    if (!ss->firstHsDone && !isHelloRetry) {
7497
24.9k
        ssl_GetSpecWriteLock(ss);
7498
24.9k
        ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
7499
24.9k
        ssl_ReleaseSpecWriteLock(ss);
7500
24.9k
    }
7501
7502
    /* Check that the session ID is as expected. */
7503
66.1k
    if (!ssl_CheckServerSessionIdCorrectness(ss, &sidBytes)) {
7504
6
        desc = illegal_parameter;
7505
6
        errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7506
6
        goto alert_loser;
7507
6
    }
7508
7509
    /* Only initialize hashes if this isn't a Hello Retry. */
7510
66.1k
    rv = ssl_ClientSetCipherSuite(ss, ss->version, cipher,
7511
66.1k
                                  !isHelloRetry);
7512
66.1k
    if (rv != SECSuccess) {
7513
174
        desc = illegal_parameter;
7514
174
        errCode = PORT_GetError();
7515
174
        goto alert_loser;
7516
174
    }
7517
7518
66.0k
    dtls_ReceivedFirstMessageInFlight(ss);
7519
7520
66.0k
    if (isHelloRetry) {
7521
2.93k
        rv = tls13_HandleHelloRetryRequest(ss, savedMsg, savedLength);
7522
2.93k
        if (rv != SECSuccess) {
7523
42
            goto loser;
7524
42
        }
7525
2.89k
        return SECSuccess;
7526
2.93k
    }
7527
7528
63.0k
    rv = ssl3_HandleParsedExtensions(ss, ssl_hs_server_hello);
7529
63.0k
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
7530
63.0k
    if (rv != SECSuccess) {
7531
525
        goto alert_loser;
7532
525
    }
7533
7534
62.5k
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_server_hello,
7535
62.5k
                                  savedMsg, savedLength);
7536
62.5k
    if (rv != SECSuccess) {
7537
0
        goto loser;
7538
0
    }
7539
7540
62.5k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
7541
2.52k
        rv = tls13_HandleServerHelloPart2(ss, savedMsg, savedLength);
7542
2.52k
        if (rv != SECSuccess) {
7543
224
            errCode = PORT_GetError();
7544
224
            goto loser;
7545
224
        }
7546
60.0k
    } else {
7547
60.0k
        rv = ssl3_HandleServerHelloPart2(ss, &sidBytes, &errCode);
7548
60.0k
        if (rv != SECSuccess)
7549
93
            goto loser;
7550
60.0k
    }
7551
7552
62.2k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
7553
62.2k
    return SECSuccess;
7554
7555
1.20k
alert_loser:
7556
1.20k
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
7557
7558
2.28k
loser:
7559
    /* Clean up the temporary pointer to the handshake buffer. */
7560
2.28k
    ss->xtnData.signedCertTimestamps.len = 0;
7561
2.28k
    ssl_MapLowLevelError(errCode);
7562
2.28k
    return SECFailure;
7563
1.20k
}
7564
7565
static SECStatus
7566
ssl3_UnwrapMasterSecretClient(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
7567
0
{
7568
0
    PK11SlotInfo *slot;
7569
0
    PK11SymKey *wrapKey;
7570
0
    CK_FLAGS keyFlags = 0;
7571
0
    SECItem wrappedMS = {
7572
0
        siBuffer,
7573
0
        sid->u.ssl3.keys.wrapped_master_secret,
7574
0
        sid->u.ssl3.keys.wrapped_master_secret_len
7575
0
    };
7576
7577
    /* unwrap master secret */
7578
0
    slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
7579
0
                             sid->u.ssl3.masterSlotID);
7580
0
    if (slot == NULL) {
7581
0
        return SECFailure;
7582
0
    }
7583
0
    if (!PK11_IsPresent(slot)) {
7584
0
        PK11_FreeSlot(slot);
7585
0
        return SECFailure;
7586
0
    }
7587
0
    wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
7588
0
                              sid->u.ssl3.masterWrapMech,
7589
0
                              sid->u.ssl3.masterWrapSeries,
7590
0
                              ss->pkcs11PinArg);
7591
0
    PK11_FreeSlot(slot);
7592
0
    if (wrapKey == NULL) {
7593
0
        return SECFailure;
7594
0
    }
7595
7596
0
    if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
7597
0
        keyFlags = CKF_SIGN | CKF_VERIFY;
7598
0
    }
7599
7600
0
    *ms = PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
7601
0
                                     NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
7602
0
                                     CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH, keyFlags);
7603
0
    PK11_FreeSymKey(wrapKey);
7604
0
    if (!*ms) {
7605
0
        return SECFailure;
7606
0
    }
7607
0
    return SECSuccess;
7608
0
}
7609
7610
static SECStatus
7611
ssl3_HandleServerHelloPart2(sslSocket *ss, const SECItem *sidBytes,
7612
                            int *retErrCode)
7613
60.0k
{
7614
60.0k
    SSL3AlertDescription desc = handshake_failure;
7615
60.0k
    int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7616
60.0k
    SECStatus rv;
7617
60.0k
    PRBool sid_match;
7618
60.0k
    sslSessionID *sid = ss->sec.ci.sid;
7619
7620
60.0k
    if ((ss->opt.requireSafeNegotiation ||
7621
56.7k
         (ss->firstHsDone && (ss->peerRequestedProtection ||
7622
38.2k
                              ss->opt.enableRenegotiation ==
7623
38.2k
                                  SSL_RENEGOTIATE_REQUIRES_XTN))) &&
7624
3.29k
        !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7625
93
        desc = handshake_failure;
7626
93
        errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
7627
93
                                  : SSL_ERROR_UNSAFE_NEGOTIATION;
7628
93
        goto alert_loser;
7629
93
    }
7630
7631
    /* Any errors after this point are not "malformed" errors. */
7632
59.9k
    desc = handshake_failure;
7633
7634
    /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
7635
     * key exchange algorithm. */
7636
59.9k
    rv = ssl3_SetupBothPendingCipherSpecs(ss);
7637
59.9k
    if (rv != SECSuccess) {
7638
0
        goto alert_loser; /* error code is set. */
7639
0
    }
7640
7641
    /* We may or may not have sent a session id, we may get one back or
7642
     * not and if so it may match the one we sent.
7643
     * Attempt to restore the master secret to see if this is so...
7644
     * Don't consider failure to find a matching SID an error.
7645
     */
7646
59.9k
    sid_match = (PRBool)(sidBytes->len > 0 &&
7647
7.15k
                         sidBytes->len ==
7648
7.15k
                             sid->u.ssl3.sessionIDLength &&
7649
0
                         !PORT_Memcmp(sid->u.ssl3.sessionID,
7650
0
                                      sidBytes->data, sidBytes->len));
7651
7652
59.9k
    if (sid_match) {
7653
0
        if (sid->version != ss->version ||
7654
0
            sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
7655
0
            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7656
0
            goto alert_loser;
7657
0
        }
7658
0
        do {
7659
0
            PK11SymKey *masterSecret;
7660
7661
            /* [draft-ietf-tls-session-hash-06; Section 5.3]
7662
             *
7663
             * o  If the original session did not use the "extended_master_secret"
7664
             *    extension but the new ServerHello contains the extension, the
7665
             *    client MUST abort the handshake.
7666
             */
7667
0
            if (!sid->u.ssl3.keys.extendedMasterSecretUsed &&
7668
0
                ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
7669
0
                errCode = SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET;
7670
0
                goto alert_loser;
7671
0
            }
7672
7673
            /*
7674
             *   o  If the original session used an extended master secret but the new
7675
             *      ServerHello does not contain the "extended_master_secret"
7676
             *      extension, the client SHOULD abort the handshake.
7677
             *
7678
             * TODO(ekr@rtfm.com): Add option to refuse to resume when EMS is not
7679
             * used at all (bug 1176526).
7680
             */
7681
0
            if (sid->u.ssl3.keys.extendedMasterSecretUsed &&
7682
0
                !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
7683
0
                errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
7684
0
                goto alert_loser;
7685
0
            }
7686
7687
0
            ss->sec.authType = sid->authType;
7688
0
            ss->sec.authKeyBits = sid->authKeyBits;
7689
0
            ss->sec.keaType = sid->keaType;
7690
0
            ss->sec.keaKeyBits = sid->keaKeyBits;
7691
0
            ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
7692
0
            ss->sec.signatureScheme = sid->sigScheme;
7693
7694
0
            rv = ssl3_UnwrapMasterSecretClient(ss, sid, &masterSecret);
7695
0
            if (rv != SECSuccess) {
7696
0
                break; /* not considered an error */
7697
0
            }
7698
7699
            /* Got a Match */
7700
0
            SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_hits);
7701
7702
            /* If we sent a session ticket, then this is a stateless resume. */
7703
0
            if (ss->xtnData.sentSessionTicketInClientHello)
7704
0
                SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_stateless_resumes);
7705
7706
0
            if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
7707
0
                ss->ssl3.hs.ws = wait_new_session_ticket;
7708
0
            else
7709
0
                ss->ssl3.hs.ws = wait_change_cipher;
7710
7711
0
            ss->ssl3.hs.isResuming = PR_TRUE;
7712
7713
            /* copy the peer cert from the SID */
7714
0
            if (sid->peerCertDER.data != NULL) {
7715
0
                rv = ssl_SetPeerCertificate(&ss->sec, &sid->peerCertDER);
7716
0
                if (rv != SECSuccess) {
7717
0
                    errCode = PORT_GetError();
7718
0
                    goto loser;
7719
0
                }
7720
0
            }
7721
7722
            /* We are re-using the old MS, so no need to derive again. */
7723
0
            rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE);
7724
0
            if (rv != SECSuccess) {
7725
0
                goto alert_loser; /* err code was set */
7726
0
            }
7727
0
            return SECSuccess;
7728
0
        } while (0);
7729
0
    }
7730
7731
59.9k
    if (sid_match)
7732
0
        SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_not_ok);
7733
59.9k
    else
7734
59.9k
        SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_misses);
7735
7736
    /* We tried to resume a 1.3 session but the server negotiated 1.2. */
7737
59.9k
    if (ss->statelessResume) {
7738
0
        PORT_Assert(sid->version == SSL_LIBRARY_VERSION_TLS_1_3);
7739
0
        PORT_Assert(ss->ssl3.hs.currentSecret);
7740
7741
        /* Reset resumption state, only used by 1.3 code. */
7742
0
        ss->statelessResume = PR_FALSE;
7743
7744
        /* Clear TLS 1.3 early data traffic key. */
7745
0
        PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
7746
0
        ss->ssl3.hs.currentSecret = NULL;
7747
0
    }
7748
7749
    /* throw the old one away */
7750
59.9k
    sid->u.ssl3.keys.resumable = PR_FALSE;
7751
59.9k
    ssl_UncacheSessionID(ss);
7752
7753
    /* get a new sid */
7754
59.9k
    sid = ssl3_NewSessionID(ss, PR_FALSE);
7755
59.9k
    ssl_SetSocketSID(ss, sid); /* releases the old sid */
7756
59.9k
    if (sid == NULL) {
7757
0
        goto alert_loser; /* memory error is set. */
7758
0
    }
7759
7760
59.9k
    sid->version = ss->version;
7761
59.9k
    sid->u.ssl3.sessionIDLength = sidBytes->len;
7762
59.9k
    if (sidBytes->len > 0) {
7763
7.15k
        PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len);
7764
7.15k
    }
7765
7766
59.9k
    sid->u.ssl3.keys.extendedMasterSecretUsed =
7767
59.9k
        ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
7768
7769
    /* Copy Signed Certificate Timestamps, if any. */
7770
59.9k
    if (ss->xtnData.signedCertTimestamps.len) {
7771
12
        rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps,
7772
12
                              &ss->xtnData.signedCertTimestamps);
7773
12
        ss->xtnData.signedCertTimestamps.len = 0;
7774
12
        if (rv != SECSuccess)
7775
0
            goto loser;
7776
12
    }
7777
7778
59.9k
    ss->ssl3.hs.isResuming = PR_FALSE;
7779
59.9k
    if (ss->ssl3.hs.kea_def->authKeyType != ssl_auth_null) {
7780
        /* All current cipher suites other than those with ssl_auth_null (i.e.,
7781
         * (EC)DH_anon_* suites) require a certificate, so use that signal. */
7782
59.9k
        ss->ssl3.hs.ws = wait_server_cert;
7783
59.9k
    } else {
7784
        /* All the remaining cipher suites must be (EC)DH_anon_* and so
7785
         * must be ephemeral. Note, if we ever add PSK this might
7786
         * change. */
7787
0
        PORT_Assert(ss->ssl3.hs.kea_def->ephemeral);
7788
0
        ss->ssl3.hs.ws = wait_server_key;
7789
0
    }
7790
59.9k
    return SECSuccess;
7791
7792
93
alert_loser:
7793
93
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
7794
7795
93
loser:
7796
93
    *retErrCode = errCode;
7797
93
    return SECFailure;
7798
93
}
7799
7800
static SECStatus
7801
ssl_HandleDHServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
7802
2.81k
{
7803
2.81k
    SECStatus rv;
7804
2.81k
    int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
7805
2.81k
    SSL3AlertDescription desc = illegal_parameter;
7806
2.81k
    SSLHashType hashAlg;
7807
2.81k
    PRBool isTLS = ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0;
7808
2.81k
    SSLSignatureScheme sigScheme;
7809
7810
2.81k
    SECItem dh_p = { siBuffer, NULL, 0 };
7811
2.81k
    SECItem dh_g = { siBuffer, NULL, 0 };
7812
2.81k
    SECItem dh_Ys = { siBuffer, NULL, 0 };
7813
2.81k
    unsigned dh_p_bits;
7814
2.81k
    unsigned dh_g_bits;
7815
2.81k
    PRInt32 minDH = 0;
7816
2.81k
    PRInt32 optval;
7817
7818
2.81k
    SSL3Hashes hashes;
7819
2.81k
    SECItem signature = { siBuffer, NULL, 0 };
7820
2.81k
    PLArenaPool *arena = NULL;
7821
2.81k
    SECKEYPublicKey *peerKey = NULL;
7822
7823
2.81k
    rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
7824
2.81k
    if (rv != SECSuccess) {
7825
59
        goto loser; /* malformed. */
7826
59
    }
7827
2.76k
    rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS, &optval);
7828
2.76k
    if ((rv == SECSuccess) && (optval & NSS_KEY_SIZE_POLICY_SSL_FLAG)) {
7829
2.76k
        (void)NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH);
7830
2.76k
    }
7831
7832
2.76k
    if (minDH <= 0) {
7833
0
        minDH = SSL_DH_MIN_P_BITS;
7834
0
    }
7835
2.76k
    dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p);
7836
2.76k
    if (dh_p_bits < (unsigned)minDH) {
7837
20
        errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
7838
20
        goto alert_loser;
7839
20
    }
7840
2.74k
    if (dh_p_bits > SSL_MAX_DH_KEY_BITS) {
7841
15
        errCode = SSL_ERROR_DH_KEY_TOO_LONG;
7842
15
        goto alert_loser;
7843
15
    }
7844
2.72k
    rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
7845
2.72k
    if (rv != SECSuccess) {
7846
88
        goto loser; /* malformed. */
7847
88
    }
7848
    /* Abort if dh_g is 0, 1, or obviously too big. */
7849
2.63k
    dh_g_bits = SECKEY_BigIntegerBitLength(&dh_g);
7850
2.63k
    if (dh_g_bits > dh_p_bits || dh_g_bits <= 1) {
7851
64
        goto alert_loser;
7852
64
    }
7853
2.57k
    if (ss->opt.requireDHENamedGroups) {
7854
        /* If we're doing named groups, make sure it's good. */
7855
67
        rv = ssl_ValidateDHENamedGroup(ss, &dh_p, &dh_g, NULL, NULL);
7856
67
        if (rv != SECSuccess) {
7857
37
            errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
7858
37
            goto alert_loser;
7859
37
        }
7860
67
    }
7861
7862
2.53k
    rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
7863
2.53k
    if (rv != SECSuccess) {
7864
10
        goto loser; /* malformed. */
7865
10
    }
7866
2.52k
    if (!ssl_IsValidDHEShare(&dh_p, &dh_Ys)) {
7867
93
        errCode = SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE;
7868
93
        goto alert_loser;
7869
93
    }
7870
7871
2.43k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
7872
2.34k
        rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
7873
2.34k
        if (rv != SECSuccess) {
7874
14
            goto loser; /* alert already sent */
7875
14
        }
7876
2.32k
        rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme,
7877
2.32k
                                                 ss->sec.peerCertSPKI);
7878
2.32k
        if (rv != SECSuccess) {
7879
8
            goto alert_loser;
7880
8
        }
7881
2.32k
        hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
7882
2.32k
    } else {
7883
        /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
7884
90
        hashAlg = ssl_hash_none;
7885
90
        sigScheme = ssl_sig_none;
7886
90
    }
7887
2.41k
    rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
7888
2.41k
    if (rv != SECSuccess) {
7889
13
        goto loser; /* malformed. */
7890
13
    }
7891
2.39k
    if (length != 0) {
7892
18
        if (isTLS) {
7893
18
            desc = decode_error;
7894
18
        }
7895
18
        goto alert_loser; /* malformed. */
7896
18
    }
7897
7898
2.38k
    PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
7899
2.38k
    PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
7900
2.38k
    PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
7901
7902
    /* failures after this point are not malformed handshakes. */
7903
    /* TLS: send decrypt_error if signature failed. */
7904
2.38k
    desc = isTLS ? decrypt_error : handshake_failure;
7905
7906
    /*
7907
     * Check to make sure the hash is signed by right guy.
7908
     */
7909
2.38k
    rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
7910
2.38k
                               dh_p, dh_g, dh_Ys, PR_FALSE /* padY */);
7911
2.38k
    if (rv != SECSuccess) {
7912
0
        errCode =
7913
0
            ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7914
0
        goto alert_loser;
7915
0
    }
7916
2.38k
    rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signature);
7917
2.38k
    if (rv != SECSuccess) {
7918
952
        errCode =
7919
952
            ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7920
952
        goto alert_loser;
7921
952
    }
7922
7923
    /*
7924
     * we really need to build a new key here because we can no longer
7925
     * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
7926
     * pkcs11 slots and ID's.
7927
     */
7928
1.42k
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7929
1.42k
    if (arena == NULL) {
7930
0
        errCode = SEC_ERROR_NO_MEMORY;
7931
0
        goto loser;
7932
0
    }
7933
7934
1.42k
    peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
7935
1.42k
    if (peerKey == NULL) {
7936
0
        errCode = SEC_ERROR_NO_MEMORY;
7937
0
        goto loser;
7938
0
    }
7939
7940
1.42k
    peerKey->arena = arena;
7941
1.42k
    peerKey->keyType = dhKey;
7942
1.42k
    peerKey->pkcs11Slot = NULL;
7943
1.42k
    peerKey->pkcs11ID = CK_INVALID_HANDLE;
7944
7945
1.42k
    if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) ||
7946
1.42k
        SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) ||
7947
1.42k
        SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) {
7948
0
        errCode = SEC_ERROR_NO_MEMORY;
7949
0
        goto loser;
7950
0
    }
7951
1.42k
    ss->sec.peerKey = peerKey;
7952
1.42k
    return SECSuccess;
7953
7954
1.20k
alert_loser:
7955
1.20k
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
7956
1.39k
loser:
7957
1.39k
    if (arena) {
7958
0
        PORT_FreeArena(arena, PR_FALSE);
7959
0
    }
7960
1.39k
    PORT_SetError(ssl_MapLowLevelError(errCode));
7961
1.39k
    return SECFailure;
7962
1.20k
}
7963
7964
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
7965
 * complete ssl3 ServerKeyExchange message.
7966
 * Caller must hold Handshake and RecvBuf locks.
7967
 */
7968
static SECStatus
7969
ssl3_HandleServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
7970
7.49k
{
7971
7.49k
    SECStatus rv;
7972
7973
7.49k
    SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
7974
7.49k
                SSL_GETPID(), ss->fd));
7975
7.49k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7976
7.49k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7977
7978
7.49k
    if (ss->ssl3.hs.ws != wait_server_key) {
7979
35
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
7980
35
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
7981
35
        return SECFailure;
7982
35
    }
7983
7984
7.45k
    switch (ss->ssl3.hs.kea_def->exchKeyType) {
7985
2.81k
        case ssl_kea_dh:
7986
2.81k
            rv = ssl_HandleDHServerKeyExchange(ss, b, length);
7987
2.81k
            break;
7988
7989
4.64k
        case ssl_kea_ecdh:
7990
4.64k
            rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
7991
4.64k
            break;
7992
7993
0
        default:
7994
0
            SSL3_SendAlert(ss, alert_fatal, handshake_failure);
7995
0
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
7996
0
            rv = SECFailure;
7997
0
            break;
7998
7.45k
    }
7999
8000
7.45k
    if (rv == SECSuccess) {
8001
4.00k
        ss->ssl3.hs.ws = wait_cert_request;
8002
4.00k
    }
8003
    /* All Handle*ServerKeyExchange functions set the error code. */
8004
7.45k
    return rv;
8005
7.45k
}
8006
8007
typedef struct dnameNode {
8008
    struct dnameNode *next;
8009
    SECItem name;
8010
} dnameNode;
8011
8012
/*
8013
 * Parse the ca_list structure in a CertificateRequest.
8014
 *
8015
 * Called from:
8016
 * ssl3_HandleCertificateRequest
8017
 * tls13_HandleCertificateRequest
8018
 */
8019
SECStatus
8020
ssl3_ParseCertificateRequestCAs(sslSocket *ss, PRUint8 **b, PRUint32 *length,
8021
                                CERTDistNames *ca_list)
8022
789
{
8023
789
    PRUint32 remaining;
8024
789
    int nnames = 0;
8025
789
    dnameNode *node;
8026
789
    SECStatus rv;
8027
789
    int i;
8028
8029
789
    rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 2, b, length);
8030
789
    if (rv != SECSuccess)
8031
127
        return SECFailure; /* malformed, alert has been sent */
8032
8033
662
    if (remaining > *length)
8034
323
        goto alert_loser;
8035
8036
339
    ca_list->head = node = PORT_ArenaZNew(ca_list->arena, dnameNode);
8037
339
    if (node == NULL)
8038
0
        goto no_mem;
8039
8040
4.40k
    while (remaining > 0) {
8041
4.27k
        PRUint32 len;
8042
8043
4.27k
        if (remaining < 2)
8044
13
            goto alert_loser; /* malformed */
8045
8046
4.26k
        rv = ssl3_ConsumeHandshakeNumber(ss, &len, 2, b, length);
8047
4.26k
        if (rv != SECSuccess)
8048
0
            return SECFailure; /* malformed, alert has been sent */
8049
4.26k
        if (len == 0 || remaining < len + 2)
8050
154
            goto alert_loser; /* malformed */
8051
8052
4.10k
        remaining -= 2;
8053
4.10k
        if (SECITEM_MakeItem(ca_list->arena, &node->name, *b, len) != SECSuccess) {
8054
0
            goto no_mem;
8055
0
        }
8056
4.10k
        node->name.len = len;
8057
4.10k
        *b += len;
8058
4.10k
        *length -= len;
8059
4.10k
        remaining -= len;
8060
4.10k
        nnames++;
8061
4.10k
        if (remaining <= 0)
8062
37
            break; /* success */
8063
8064
4.07k
        node->next = PORT_ArenaZNew(ca_list->arena, dnameNode);
8065
4.07k
        node = node->next;
8066
4.07k
        if (node == NULL)
8067
0
            goto no_mem;
8068
4.07k
    }
8069
8070
172
    ca_list->nnames = nnames;
8071
172
    ca_list->names = PORT_ArenaNewArray(ca_list->arena, SECItem, nnames);
8072
172
    if (nnames > 0 && ca_list->names == NULL)
8073
0
        goto no_mem;
8074
8075
172
    for (i = 0, node = (dnameNode *)ca_list->head;
8076
3.49k
         i < nnames;
8077
3.32k
         i++, node = node->next) {
8078
3.32k
        ca_list->names[i] = node->name;
8079
3.32k
    }
8080
8081
172
    return SECSuccess;
8082
8083
0
no_mem:
8084
0
    return SECFailure;
8085
8086
490
alert_loser:
8087
490
    (void)SSL3_SendAlert(ss, alert_fatal,
8088
490
                         ss->version < SSL_LIBRARY_VERSION_TLS_1_0 ? illegal_parameter
8089
490
                                                                   : decode_error);
8090
490
    PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
8091
490
    return SECFailure;
8092
172
}
8093
8094
SECStatus
8095
ssl_ParseSignatureSchemes(const sslSocket *ss, PLArenaPool *arena,
8096
                          SSLSignatureScheme **schemesOut,
8097
                          unsigned int *numSchemesOut,
8098
                          unsigned char **b, unsigned int *len)
8099
10.1k
{
8100
10.1k
    SECStatus rv;
8101
10.1k
    SECItem buf;
8102
10.1k
    SSLSignatureScheme *schemes = NULL;
8103
10.1k
    unsigned int numSupported = 0;
8104
10.1k
    unsigned int numRemaining = 0;
8105
10.1k
    unsigned int max;
8106
8107
10.1k
    rv = ssl3_ExtConsumeHandshakeVariable(ss, &buf, 2, b, len);
8108
10.1k
    if (rv != SECSuccess) {
8109
37
        return SECFailure;
8110
37
    }
8111
    /* An odd-length value is invalid. */
8112
10.0k
    if ((buf.len & 1) != 0) {
8113
9
        ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
8114
9
        return SECFailure;
8115
9
    }
8116
8117
    /* Let the caller decide whether to alert here. */
8118
10.0k
    if (buf.len == 0) {
8119
13
        goto done;
8120
13
    }
8121
8122
    /* Limit the number of schemes we read. */
8123
10.0k
    numRemaining = buf.len / 2;
8124
10.0k
    max = PR_MIN(numRemaining, MAX_SIGNATURE_SCHEMES);
8125
8126
10.0k
    if (arena) {
8127
619
        schemes = PORT_ArenaZNewArray(arena, SSLSignatureScheme, max);
8128
9.45k
    } else {
8129
9.45k
        schemes = PORT_ZNewArray(SSLSignatureScheme, max);
8130
9.45k
    }
8131
10.0k
    if (!schemes) {
8132
0
        ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
8133
0
        return SECFailure;
8134
0
    }
8135
8136
249k
    for (; numRemaining && numSupported < MAX_SIGNATURE_SCHEMES; --numRemaining) {
8137
239k
        PRUint32 tmp;
8138
239k
        rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2, &buf.data, &buf.len);
8139
239k
        if (rv != SECSuccess) {
8140
0
            PORT_Assert(0);
8141
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
8142
0
            return SECFailure;
8143
0
        }
8144
239k
        if (ssl_SignatureSchemeValid((SSLSignatureScheme)tmp, SEC_OID_UNKNOWN,
8145
239k
                                     (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)) {
8146
35.6k
            ;
8147
35.6k
            schemes[numSupported++] = (SSLSignatureScheme)tmp;
8148
35.6k
        }
8149
239k
    }
8150
8151
10.0k
    if (!numSupported) {
8152
262
        if (!arena) {
8153
228
            PORT_Free(schemes);
8154
228
        }
8155
262
        schemes = NULL;
8156
262
    }
8157
8158
10.0k
done:
8159
10.0k
    *schemesOut = schemes;
8160
10.0k
    *numSchemesOut = numSupported;
8161
10.0k
    return SECSuccess;
8162
10.0k
}
8163
8164
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
8165
 * a complete ssl3 Certificate Request message.
8166
 * Caller must hold Handshake and RecvBuf locks.
8167
 */
8168
static SECStatus
8169
ssl3_HandleCertificateRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
8170
886
{
8171
886
    PLArenaPool *arena = NULL;
8172
886
    PRBool isTLS = PR_FALSE;
8173
886
    PRBool isTLS12 = PR_FALSE;
8174
886
    int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
8175
886
    SECStatus rv;
8176
886
    SSL3AlertDescription desc = illegal_parameter;
8177
886
    SECItem cert_types = { siBuffer, NULL, 0 };
8178
886
    SSLSignatureScheme *signatureSchemes = NULL;
8179
886
    unsigned int signatureSchemeCount = 0;
8180
886
    CERTDistNames ca_list;
8181
8182
886
    SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
8183
886
                SSL_GETPID(), ss->fd));
8184
886
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
8185
886
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8186
8187
886
    if (ss->ssl3.hs.ws != wait_cert_request) {
8188
26
        desc = unexpected_message;
8189
26
        errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
8190
26
        goto alert_loser;
8191
26
    }
8192
8193
860
    PORT_Assert(ss->ssl3.clientCertChain == NULL);
8194
860
    PORT_Assert(ss->ssl3.clientCertificate == NULL);
8195
860
    PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
8196
8197
860
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
8198
860
    isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
8199
860
    rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
8200
860
    if (rv != SECSuccess)
8201
22
        goto loser; /* malformed, alert has been sent */
8202
8203
838
    arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
8204
838
    if (arena == NULL)
8205
0
        goto no_mem;
8206
8207
838
    if (isTLS12) {
8208
634
        rv = ssl_ParseSignatureSchemes(ss, arena,
8209
634
                                       &signatureSchemes,
8210
634
                                       &signatureSchemeCount,
8211
634
                                       &b, &length);
8212
634
        if (rv != SECSuccess) {
8213
10
            PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
8214
10
            goto loser; /* malformed, alert has been sent */
8215
10
        }
8216
624
        if (signatureSchemeCount == 0) {
8217
39
            errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
8218
39
            desc = handshake_failure;
8219
39
            goto alert_loser;
8220
39
        }
8221
624
    }
8222
8223
789
    rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, &ca_list);
8224
789
    if (rv != SECSuccess)
8225
617
        goto done; /* alert sent in ssl3_ParseCertificateRequestCAs */
8226
8227
172
    if (length != 0)
8228
72
        goto alert_loser; /* malformed */
8229
8230
100
    ss->ssl3.hs.ws = wait_hello_done;
8231
8232
100
    rv = ssl3_BeginHandleCertificateRequest(ss, signatureSchemes,
8233
100
                                            signatureSchemeCount, &ca_list);
8234
100
    if (rv != SECSuccess) {
8235
0
        PORT_Assert(0);
8236
0
        errCode = SEC_ERROR_LIBRARY_FAILURE;
8237
0
        desc = internal_error;
8238
0
        goto alert_loser;
8239
0
    }
8240
100
    goto done;
8241
8242
100
no_mem:
8243
0
    rv = SECFailure;
8244
0
    PORT_SetError(SEC_ERROR_NO_MEMORY);
8245
0
    goto done;
8246
8247
137
alert_loser:
8248
137
    if (isTLS && desc == illegal_parameter)
8249
72
        desc = decode_error;
8250
137
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
8251
169
loser:
8252
169
    PORT_SetError(errCode);
8253
169
    rv = SECFailure;
8254
886
done:
8255
886
    if (arena != NULL)
8256
838
        PORT_FreeArena(arena, PR_FALSE);
8257
886
    return rv;
8258
169
}
8259
8260
static void
8261
ssl3_ClientAuthCallbackOutcome(sslSocket *ss, SECStatus outcome)
8262
100
{
8263
100
    SECStatus rv;
8264
100
    switch (outcome) {
8265
0
        case SECSuccess:
8266
            /* check what the callback function returned */
8267
0
            if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
8268
                /* we are missing either the key or cert */
8269
0
                goto send_no_certificate;
8270
0
            }
8271
            /* Setting ssl3.clientCertChain non-NULL will cause
8272
             * ssl3_HandleServerHelloDone to call SendCertificate.
8273
             */
8274
0
            ss->ssl3.clientCertChain = CERT_CertChainFromCert(
8275
0
                ss->ssl3.clientCertificate,
8276
0
                certUsageSSLClient, PR_FALSE);
8277
0
            if (ss->ssl3.clientCertChain == NULL) {
8278
0
                goto send_no_certificate;
8279
0
            }
8280
0
            if (ss->ssl3.hs.hashType == handshake_hash_record ||
8281
0
                ss->ssl3.hs.hashType == handshake_hash_single) {
8282
0
                rv = ssl_PickClientSignatureScheme(ss,
8283
0
                                                   ss->ssl3.clientCertificate,
8284
0
                                                   ss->ssl3.clientPrivateKey,
8285
0
                                                   ss->ssl3.hs.clientAuthSignatureSchemes,
8286
0
                                                   ss->ssl3.hs.clientAuthSignatureSchemesLen,
8287
0
                                                   &ss->ssl3.hs.signatureScheme);
8288
0
                if (rv != SECSuccess) {
8289
                    /* This should only happen if our schemes changed or
8290
                     * if an RSA-PSS cert was selected, but the token
8291
                     * does not support PSS schemes.
8292
                     */
8293
0
                    goto send_no_certificate;
8294
0
                }
8295
0
            }
8296
0
            break;
8297
8298
100
        case SECFailure:
8299
100
        default:
8300
100
        send_no_certificate:
8301
100
            CERT_DestroyCertificate(ss->ssl3.clientCertificate);
8302
100
            SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
8303
100
            ss->ssl3.clientCertificate = NULL;
8304
100
            ss->ssl3.clientPrivateKey = NULL;
8305
100
            if (ss->ssl3.clientCertChain) {
8306
0
                CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
8307
0
                ss->ssl3.clientCertChain = NULL;
8308
0
            }
8309
8310
100
            if (ss->version > SSL_LIBRARY_VERSION_3_0) {
8311
100
                ss->ssl3.sendEmptyCert = PR_TRUE;
8312
100
            } else {
8313
0
                (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
8314
0
            }
8315
100
            break;
8316
100
    }
8317
8318
    /* Release the cached parameters */
8319
100
    PORT_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
8320
100
    ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
8321
100
    ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
8322
100
}
8323
8324
SECStatus
8325
ssl3_BeginHandleCertificateRequest(sslSocket *ss,
8326
                                   const SSLSignatureScheme *signatureSchemes,
8327
                                   unsigned int signatureSchemeCount,
8328
                                   CERTDistNames *ca_list)
8329
100
{
8330
100
    SECStatus rv;
8331
8332
100
    PR_ASSERT(!ss->ssl3.hs.clientCertificatePending);
8333
8334
    /* Should not send a client cert when (non-GREASE) ECH is rejected. */
8335
100
    if (ss->ssl3.hs.echHpkeCtx && !ss->ssl3.hs.echAccepted) {
8336
13
        PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn));
8337
13
        rv = SECFailure;
8338
87
    } else if (ss->getClientAuthData != NULL) {
8339
0
        PORT_Assert(signatureSchemes || !signatureSchemeCount);
8340
0
        PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
8341
0
                    ssl_preinfo_all);
8342
0
        PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
8343
0
        PORT_Assert(ss->ssl3.clientCertificate == NULL);
8344
0
        PORT_Assert(ss->ssl3.clientCertChain == NULL);
8345
8346
        /* Previously cached parameters should be empty */
8347
0
        PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemes == NULL);
8348
0
        PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemesLen == 0);
8349
        /*
8350
         * Peer signatures are only available while in the context of
8351
         * of a getClientAuthData callback. It is required for proper
8352
         * functioning of SSL_CertIsUsable and SSL_FilterClientCertListBySocket
8353
         * Calling these functions outside the context of a getClientAuthData
8354
         * callback will result in no filtering.*/
8355
8356
0
        ss->ssl3.hs.clientAuthSignatureSchemes = PORT_ZNewArray(SSLSignatureScheme, signatureSchemeCount);
8357
0
        if (signatureSchemes) {
8358
0
            PORT_Memcpy(ss->ssl3.hs.clientAuthSignatureSchemes, signatureSchemes, signatureSchemeCount * sizeof(SSLSignatureScheme));
8359
0
        }
8360
0
        ss->ssl3.hs.clientAuthSignatureSchemesLen = signatureSchemeCount;
8361
8362
0
        rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
8363
0
                                                 ss->fd, ca_list,
8364
0
                                                 &ss->ssl3.clientCertificate,
8365
0
                                                 &ss->ssl3.clientPrivateKey);
8366
87
    } else {
8367
87
        rv = SECFailure; /* force it to send a no_certificate alert */
8368
87
    }
8369
8370
100
    if (rv == SECWouldBlock) {
8371
        /* getClientAuthData needs more time (e.g. for user interaction) */
8372
8373
        /* The out parameters should not have changed. */
8374
0
        PORT_Assert(ss->ssl3.clientCertificate == NULL);
8375
0
        PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
8376
8377
        /* Mark the handshake as blocked */
8378
0
        ss->ssl3.hs.clientCertificatePending = PR_TRUE;
8379
8380
0
        rv = SECSuccess;
8381
100
    } else {
8382
        /* getClientAuthData returned SECSuccess or SECFailure immediately, handle accordingly */
8383
100
        ssl3_ClientAuthCallbackOutcome(ss, rv);
8384
100
        rv = SECSuccess;
8385
100
    }
8386
100
    return rv;
8387
100
}
8388
8389
/* Invoked by the application when client certificate selection is complete */
8390
SECStatus
8391
ssl3_ClientCertCallbackComplete(sslSocket *ss, SECStatus outcome, SECKEYPrivateKey *clientPrivateKey, CERTCertificate *clientCertificate)
8392
0
{
8393
0
    PORT_Assert(ss->ssl3.hs.clientCertificatePending);
8394
0
    ss->ssl3.hs.clientCertificatePending = PR_FALSE;
8395
8396
0
    ss->ssl3.clientCertificate = clientCertificate;
8397
0
    ss->ssl3.clientPrivateKey = clientPrivateKey;
8398
8399
0
    ssl3_ClientAuthCallbackOutcome(ss, outcome);
8400
8401
    /* Continue the handshake */
8402
0
    if (!ss->ssl3.hs.restartTarget) {
8403
        /* The client cert callback completed before the server Finished
8404
         * message was fully received.  This can happen on a non-blocking
8405
         * socket when EAGAIN interrupts the record-header read partway
8406
         * through (e.g. when the Finished record header straddles a TCP
8407
         * segment boundary).  The partial gather state is preserved in
8408
         * ss->gs and will be resumed by the next SSL_ForceHandshake /
8409
         * PR_Read call.  tls13_SendClientSecondRound will run after the
8410
         * Finished is processed and will find clientCertificatePending
8411
         * already cleared, so it will proceed without blocking. */
8412
0
        SSL_TRC(3, ("%d: SSL3[%p]: client certificate selection won the race"
8413
0
                    " with server Finished; will resume on next I/O",
8414
0
                    SSL_GETPID(), ss->fd));
8415
0
        PORT_Assert(ss->ssl3.hs.ws != idle_handshake);
8416
0
        return SECSuccess;
8417
0
    }
8418
0
    sslRestartTarget target = ss->ssl3.hs.restartTarget;
8419
0
    ss->ssl3.hs.restartTarget = NULL;
8420
0
    return target(ss);
8421
0
}
8422
8423
static SECStatus
8424
ssl3_CheckFalseStart(sslSocket *ss)
8425
3.82k
{
8426
3.82k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8427
3.82k
    PORT_Assert(!ss->ssl3.hs.authCertificatePending);
8428
3.82k
    PORT_Assert(!ss->ssl3.hs.canFalseStart);
8429
8430
3.82k
    if (!ss->canFalseStartCallback) {
8431
0
        SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start",
8432
0
                    SSL_GETPID(), ss->fd));
8433
3.82k
    } else {
8434
3.82k
        SECStatus rv;
8435
8436
3.82k
        rv = ssl_CheckServerRandom(ss);
8437
3.82k
        if (rv != SECSuccess) {
8438
0
            SSL_TRC(3, ("%d: SSL[%d]: no false start due to possible downgrade",
8439
0
                        SSL_GETPID(), ss->fd));
8440
0
            goto no_false_start;
8441
0
        }
8442
8443
        /* An attacker can control the selected ciphersuite so we only wish to
8444
         * do False Start in the case that the selected ciphersuite is
8445
         * sufficiently strong that the attack can gain no advantage.
8446
         * Therefore we always require an 80-bit cipher. */
8447
3.82k
        ssl_GetSpecReadLock(ss);
8448
3.82k
        PRBool weakCipher = ss->ssl3.cwSpec->cipherDef->secret_key_size < 10;
8449
3.82k
        ssl_ReleaseSpecReadLock(ss);
8450
3.82k
        if (weakCipher) {
8451
1.28k
            SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher",
8452
1.28k
                        SSL_GETPID(), ss->fd));
8453
1.28k
            goto no_false_start;
8454
1.28k
        }
8455
8456
2.53k
        if (ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn)) {
8457
189
            SSL_TRC(3, ("%d: SSL[%d]: no false start due to lower version after ECH",
8458
189
                        SSL_GETPID(), ss->fd));
8459
189
            goto no_false_start;
8460
189
        }
8461
8462
2.34k
        PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
8463
2.34k
                    ssl_preinfo_all);
8464
2.34k
        rv = (ss->canFalseStartCallback)(ss->fd,
8465
2.34k
                                         ss->canFalseStartCallbackData,
8466
2.34k
                                         &ss->ssl3.hs.canFalseStart);
8467
2.34k
        if (rv == SECSuccess) {
8468
2.34k
            SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s",
8469
2.34k
                        SSL_GETPID(), ss->fd,
8470
2.34k
                        ss->ssl3.hs.canFalseStart ? "TRUE"
8471
2.34k
                                                  : "FALSE"));
8472
2.34k
        } else {
8473
0
            SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)",
8474
0
                        SSL_GETPID(), ss->fd,
8475
0
                        PR_ErrorToName(PR_GetError())));
8476
0
        }
8477
2.34k
        return rv;
8478
2.53k
    }
8479
8480
1.47k
no_false_start:
8481
1.47k
    ss->ssl3.hs.canFalseStart = PR_FALSE;
8482
1.47k
    return SECSuccess;
8483
3.82k
}
8484
8485
PRBool
8486
ssl3_WaitingForServerSecondRound(sslSocket *ss)
8487
63.1k
{
8488
63.1k
    PRBool result;
8489
8490
63.1k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8491
8492
63.1k
    switch (ss->ssl3.hs.ws) {
8493
1.41k
        case wait_new_session_ticket:
8494
56.0k
        case wait_change_cipher:
8495
63.1k
        case wait_finished:
8496
63.1k
            result = PR_TRUE;
8497
63.1k
            break;
8498
0
        default:
8499
0
            result = PR_FALSE;
8500
0
            break;
8501
63.1k
    }
8502
8503
63.1k
    return result;
8504
63.1k
}
8505
8506
static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
8507
8508
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
8509
 * a complete ssl3 Server Hello Done message.
8510
 * Caller must hold Handshake and RecvBuf locks.
8511
 */
8512
static SECStatus
8513
ssl3_HandleServerHelloDone(sslSocket *ss)
8514
45.9k
{
8515
45.9k
    SECStatus rv;
8516
45.9k
    SSL3WaitState ws = ss->ssl3.hs.ws;
8517
8518
45.9k
    SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
8519
45.9k
                SSL_GETPID(), ss->fd));
8520
45.9k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
8521
45.9k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8522
8523
    /* Skipping CertificateRequest is always permitted. */
8524
45.9k
    if (ws != wait_hello_done &&
8525
45.8k
        ws != wait_cert_request) {
8526
39
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8527
39
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
8528
39
        return SECFailure;
8529
39
    }
8530
8531
45.8k
    rv = ssl3_SendClientSecondRound(ss);
8532
8533
45.8k
    return rv;
8534
45.9k
}
8535
8536
/* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
8537
 *
8538
 * Caller must hold Handshake and RecvBuf locks.
8539
 */
8540
static SECStatus
8541
ssl3_SendClientSecondRound(sslSocket *ss)
8542
45.8k
{
8543
45.8k
    SECStatus rv;
8544
45.8k
    PRBool sendClientCert;
8545
8546
45.8k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
8547
45.8k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8548
8549
45.8k
    sendClientCert = !ss->ssl3.sendEmptyCert &&
8550
45.8k
                     ss->ssl3.clientCertChain != NULL &&
8551
0
                     ss->ssl3.clientPrivateKey != NULL;
8552
8553
    /* We must wait for the server's certificate to be authenticated before
8554
     * sending the client certificate in order to disclosing the client
8555
     * certificate to an attacker that does not have a valid cert for the
8556
     * domain we are connecting to.
8557
     *
8558
     * During the initial handshake on a connection, we never send/receive
8559
     * application data until we have authenticated the server's certificate;
8560
     * i.e. we have fully authenticated the handshake before using the cipher
8561
     * specs agreed upon for that handshake. During a renegotiation, we may
8562
     * continue sending and receiving application data during the handshake
8563
     * interleaved with the handshake records. If we were to send the client's
8564
     * second round for a renegotiation before the server's certificate was
8565
     * authenticated, then the application data sent/received after this point
8566
     * would be using cipher spec that hadn't been authenticated. By waiting
8567
     * until the server's certificate has been authenticated during
8568
     * renegotiations, we ensure that renegotiations have the same property
8569
     * as initial handshakes; i.e. we have fully authenticated the handshake
8570
     * before using the cipher specs agreed upon for that handshake for
8571
     * application data.
8572
     */
8573
45.8k
    if (ss->ssl3.hs.restartTarget) {
8574
0
        PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
8575
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
8576
0
        return SECFailure;
8577
0
    }
8578
    /* Check whether waiting for client certificate selection OR
8579
       waiting on server certificate verification AND
8580
       going to send client cert */
8581
45.8k
    if ((ss->ssl3.hs.clientCertificatePending) ||
8582
45.8k
        (ss->ssl3.hs.authCertificatePending && (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone))) {
8583
0
        SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"
8584
0
                    " certificate authentication is still pending.",
8585
0
                    SSL_GETPID(), ss->fd));
8586
0
        ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
8587
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
8588
0
        return SECFailure;
8589
0
    }
8590
8591
45.8k
    ssl_GetXmitBufLock(ss); /*******************************/
8592
8593
45.8k
    if (ss->ssl3.sendEmptyCert) {
8594
57
        ss->ssl3.sendEmptyCert = PR_FALSE;
8595
57
        rv = ssl3_SendEmptyCertificate(ss);
8596
        /* Don't send verify */
8597
57
        if (rv != SECSuccess) {
8598
0
            goto loser; /* error code is set. */
8599
0
        }
8600
45.8k
    } else if (sendClientCert) {
8601
0
        rv = ssl3_SendCertificate(ss);
8602
0
        if (rv != SECSuccess) {
8603
0
            goto loser; /* error code is set. */
8604
0
        }
8605
0
    }
8606
8607
45.8k
    rv = ssl3_SendClientKeyExchange(ss);
8608
45.8k
    if (rv != SECSuccess) {
8609
568
        goto loser; /* err is set. */
8610
568
    }
8611
8612
45.3k
    if (sendClientCert) {
8613
0
        rv = ssl3_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
8614
0
        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
8615
0
        ss->ssl3.clientPrivateKey = NULL;
8616
0
        if (rv != SECSuccess) {
8617
0
            goto loser; /* err is set. */
8618
0
        }
8619
0
    }
8620
8621
45.3k
    rv = ssl3_SendChangeCipherSpecs(ss);
8622
45.3k
    if (rv != SECSuccess) {
8623
0
        goto loser; /* err code was set. */
8624
0
    }
8625
8626
    /* This must be done after we've set ss->ssl3.cwSpec in
8627
     * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information
8628
     * from cwSpec. This must be done before we call ssl3_CheckFalseStart
8629
     * because the false start callback (if any) may need the information from
8630
     * the functions that depend on this being set.
8631
     */
8632
45.3k
    ss->enoughFirstHsDone = PR_TRUE;
8633
8634
45.3k
    if (!ss->firstHsDone) {
8635
7.49k
        if (ss->opt.enableFalseStart) {
8636
3.82k
            if (!ss->ssl3.hs.authCertificatePending) {
8637
                /* When we fix bug 589047, we will need to know whether we are
8638
                 * false starting before we try to flush the client second
8639
                 * round to the network. With that in mind, we purposefully
8640
                 * call ssl3_CheckFalseStart before calling ssl3_SendFinished,
8641
                 * which includes a call to ssl3_FlushHandshake, so that
8642
                 * no application develops a reliance on such flushing being
8643
                 * done before its false start callback is called.
8644
                 */
8645
3.82k
                ssl_ReleaseXmitBufLock(ss);
8646
3.82k
                rv = ssl3_CheckFalseStart(ss);
8647
3.82k
                ssl_GetXmitBufLock(ss);
8648
3.82k
                if (rv != SECSuccess) {
8649
0
                    goto loser;
8650
0
                }
8651
3.82k
            } else {
8652
                /* The certificate authentication and the server's Finished
8653
                 * message are racing each other. If the certificate
8654
                 * authentication wins, then we will try to false start in
8655
                 * ssl3_AuthCertificateComplete.
8656
                 */
8657
0
                SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because"
8658
0
                            " certificate authentication is still pending.",
8659
0
                            SSL_GETPID(), ss->fd));
8660
0
            }
8661
3.82k
        }
8662
7.49k
    }
8663
8664
45.3k
    rv = ssl3_SendFinished(ss, 0);
8665
45.3k
    if (rv != SECSuccess) {
8666
0
        goto loser; /* err code was set. */
8667
0
    }
8668
8669
45.3k
    ssl_ReleaseXmitBufLock(ss); /*******************************/
8670
8671
45.3k
    if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
8672
133
        ss->ssl3.hs.ws = wait_new_session_ticket;
8673
45.1k
    else
8674
45.1k
        ss->ssl3.hs.ws = wait_change_cipher;
8675
8676
45.3k
    PORT_Assert(ssl3_WaitingForServerSecondRound(ss));
8677
8678
45.3k
    return SECSuccess;
8679
8680
568
loser:
8681
568
    ssl_ReleaseXmitBufLock(ss);
8682
568
    return rv;
8683
45.3k
}
8684
8685
/*
8686
 * Routines used by servers
8687
 */
8688
static SECStatus
8689
ssl3_SendHelloRequest(sslSocket *ss)
8690
0
{
8691
0
    SECStatus rv;
8692
8693
0
    SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
8694
0
                ss->fd));
8695
8696
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8697
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8698
8699
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_hello_request, 0);
8700
0
    if (rv != SECSuccess) {
8701
0
        return rv; /* err set by AppendHandshake */
8702
0
    }
8703
0
    rv = ssl3_FlushHandshake(ss, 0);
8704
0
    if (rv != SECSuccess) {
8705
0
        return rv; /* error code set by ssl3_FlushHandshake */
8706
0
    }
8707
0
    ss->ssl3.hs.ws = wait_client_hello;
8708
0
    return SECSuccess;
8709
0
}
8710
8711
/*
8712
 * Called from:
8713
 *  ssl3_HandleClientHello()
8714
 */
8715
static SECComparison
8716
ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
8717
0
{
8718
0
    if (!name1 != !name2) {
8719
0
        return SECLessThan;
8720
0
    }
8721
0
    if (!name1) {
8722
0
        return SECEqual;
8723
0
    }
8724
0
    if (name1->type != name2->type) {
8725
0
        return SECLessThan;
8726
0
    }
8727
0
    return SECITEM_CompareItem(name1, name2);
8728
0
}
8729
8730
/* Sets memory error when returning NULL.
8731
 * Called from:
8732
 *  ssl3_SendClientHello()
8733
 *  ssl3_HandleServerHello()
8734
 *  ssl3_HandleClientHello()
8735
 *  ssl3_HandleV2ClientHello()
8736
 */
8737
sslSessionID *
8738
ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
8739
246k
{
8740
246k
    sslSessionID *sid;
8741
8742
246k
    sid = PORT_ZNew(sslSessionID);
8743
246k
    if (sid == NULL)
8744
0
        return sid;
8745
8746
246k
    if (is_server) {
8747
79.2k
        const SECItem *srvName;
8748
79.2k
        SECStatus rv = SECSuccess;
8749
8750
79.2k
        ssl_GetSpecReadLock(ss); /********************************/
8751
79.2k
        srvName = &ss->ssl3.hs.srvVirtName;
8752
79.2k
        if (srvName->len && srvName->data) {
8753
0
            rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
8754
0
        }
8755
79.2k
        ssl_ReleaseSpecReadLock(ss); /************************************/
8756
79.2k
        if (rv != SECSuccess) {
8757
0
            PORT_Free(sid);
8758
0
            return NULL;
8759
0
        }
8760
79.2k
    }
8761
246k
    sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
8762
246k
    sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url);
8763
246k
    sid->addr = ss->sec.ci.peer;
8764
246k
    sid->port = ss->sec.ci.port;
8765
246k
    sid->references = 1;
8766
246k
    sid->cached = never_cached;
8767
246k
    sid->version = ss->version;
8768
246k
    sid->sigScheme = ssl_sig_none;
8769
8770
246k
    sid->u.ssl3.keys.resumable = PR_TRUE;
8771
246k
    sid->u.ssl3.policy = SSL_ALLOWED;
8772
246k
    sid->u.ssl3.keys.extendedMasterSecretUsed = PR_FALSE;
8773
8774
246k
    if (is_server) {
8775
79.2k
        SECStatus rv;
8776
79.2k
        int pid = SSL_GETPID();
8777
8778
79.2k
        sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
8779
79.2k
        sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff;
8780
79.2k
        sid->u.ssl3.sessionID[1] = pid & 0xff;
8781
79.2k
        rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
8782
79.2k
                                 SSL3_SESSIONID_BYTES - 2);
8783
79.2k
        if (rv != SECSuccess) {
8784
0
            ssl_FreeSID(sid);
8785
0
            ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
8786
0
            return NULL;
8787
0
        }
8788
79.2k
    }
8789
246k
    return sid;
8790
246k
}
8791
8792
/* Called from:  ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
8793
static SECStatus
8794
ssl3_SendServerHelloSequence(sslSocket *ss)
8795
75.6k
{
8796
75.6k
    const ssl3KEADef *kea_def;
8797
75.6k
    SECStatus rv;
8798
8799
75.6k
    SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
8800
75.6k
                SSL_GETPID(), ss->fd));
8801
8802
75.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8803
75.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8804
8805
75.6k
    rv = ssl3_SendServerHello(ss);
8806
75.6k
    if (rv != SECSuccess) {
8807
0
        return rv; /* err code is set. */
8808
0
    }
8809
75.6k
    rv = ssl3_SendCertificate(ss);
8810
75.6k
    if (rv != SECSuccess) {
8811
0
        return rv; /* error code is set. */
8812
0
    }
8813
75.6k
    rv = ssl3_SendCertificateStatus(ss);
8814
75.6k
    if (rv != SECSuccess) {
8815
0
        return rv; /* error code is set. */
8816
0
    }
8817
    /* We have to do this after the call to ssl3_SendServerHello,
8818
     * because kea_def is set up by ssl3_SendServerHello().
8819
     */
8820
75.6k
    kea_def = ss->ssl3.hs.kea_def;
8821
8822
75.6k
    if (kea_def->ephemeral) {
8823
28.2k
        rv = ssl3_SendServerKeyExchange(ss);
8824
28.2k
        if (rv != SECSuccess) {
8825
176
            return rv; /* err code was set. */
8826
176
        }
8827
28.2k
    }
8828
8829
75.4k
    if (ss->opt.requestCertificate) {
8830
25.6k
        rv = ssl3_SendCertificateRequest(ss);
8831
25.6k
        if (rv != SECSuccess) {
8832
0
            return rv; /* err code is set. */
8833
0
        }
8834
25.6k
    }
8835
75.4k
    rv = ssl3_SendServerHelloDone(ss);
8836
75.4k
    if (rv != SECSuccess) {
8837
7
        return rv; /* err code is set. */
8838
7
    }
8839
8840
75.4k
    ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
8841
75.4k
                                                  : wait_client_key;
8842
75.4k
    return SECSuccess;
8843
75.4k
}
8844
8845
/* An empty TLS Renegotiation Info (RI) extension */
8846
static const PRUint8 emptyRIext[5] = { 0xff, 0x01, 0x00, 0x01, 0x00 };
8847
8848
static PRBool
8849
ssl3_KEASupportsTickets(const ssl3KEADef *kea_def)
8850
6.16k
{
8851
6.16k
    if (kea_def->signKeyType == dsaKey) {
8852
        /* TODO: Fix session tickets for DSS. The server code rejects the
8853
         * session ticket received from the client. Bug 1174677 */
8854
0
        return PR_FALSE;
8855
0
    }
8856
6.16k
    return PR_TRUE;
8857
6.16k
}
8858
8859
static PRBool
8860
ssl3_PeerSupportsCipherSuite(const SECItem *peerSuites, uint16_t suite)
8861
1.90M
{
8862
5.48M
    for (unsigned int i = 0; i + 1 < peerSuites->len; i += 2) {
8863
3.65M
        PRUint16 suite_i = (peerSuites->data[i] << 8) | peerSuites->data[i + 1];
8864
3.65M
        if (suite_i == suite) {
8865
79.9k
            return PR_TRUE;
8866
79.9k
        }
8867
3.65M
    }
8868
1.82M
    return PR_FALSE;
8869
1.90M
}
8870
8871
SECStatus
8872
ssl3_NegotiateCipherSuiteInner(sslSocket *ss, const SECItem *suites,
8873
                               PRUint16 version, PRUint16 *suitep)
8874
80.3k
{
8875
80.3k
    unsigned int i;
8876
80.3k
    SSLVersionRange vrange = { version, version };
8877
8878
    /* If we negotiated an External PSK and that PSK has a ciphersuite
8879
     * configured, we need to constrain our choice. If the client does
8880
     * not support it, negotiate a certificate auth suite and fall back.
8881
     */
8882
80.3k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
8883
4.27k
        ss->xtnData.selectedPsk &&
8884
0
        ss->xtnData.selectedPsk->type == ssl_psk_external &&
8885
0
        ss->xtnData.selectedPsk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL) {
8886
0
        PRUint16 pskSuite = ss->xtnData.selectedPsk->zeroRttSuite;
8887
0
        ssl3CipherSuiteCfg *pskSuiteCfg = ssl_LookupCipherSuiteCfgMutable(pskSuite,
8888
0
                                                                          ss->cipherSuites);
8889
0
        if (ssl3_config_match(pskSuiteCfg, ss->ssl3.policy, &vrange, ss) &&
8890
0
            ssl3_PeerSupportsCipherSuite(suites, pskSuite)) {
8891
0
            *suitep = pskSuite;
8892
0
            return SECSuccess;
8893
0
        }
8894
0
    }
8895
8896
3.37M
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
8897
3.37M
        ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
8898
3.37M
        if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
8899
1.46M
            continue;
8900
1.46M
        }
8901
1.90M
        if (!ssl3_PeerSupportsCipherSuite(suites, suite->cipher_suite)) {
8902
1.82M
            continue;
8903
1.82M
        }
8904
79.9k
        *suitep = suite->cipher_suite;
8905
79.9k
        return SECSuccess;
8906
1.90M
    }
8907
459
    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8908
459
    return SECFailure;
8909
80.3k
}
8910
8911
/* Select a cipher suite.
8912
**
8913
** NOTE: This suite selection algorithm should be the same as the one in
8914
** ssl3_HandleV2ClientHello().
8915
**
8916
** If TLS 1.0 is enabled, we could handle the case where the client
8917
** offered TLS 1.1 but offered only export cipher suites by choosing TLS
8918
** 1.0 and selecting one of those export cipher suites. However, a secure
8919
** TLS 1.1 client should not have export cipher suites enabled at all,
8920
** and a TLS 1.1 client should definitely not be offering *only* export
8921
** cipher suites. Therefore, we refuse to negotiate export cipher suites
8922
** with any client that indicates support for TLS 1.1 or higher when we
8923
** (the server) have TLS 1.1 support enabled.
8924
*/
8925
SECStatus
8926
ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites,
8927
                          PRBool initHashes)
8928
80.3k
{
8929
80.3k
    PRUint16 selected;
8930
80.3k
    SECStatus rv;
8931
8932
    /* Ensure that only valid cipher suites are enabled. */
8933
80.3k
    if (ssl3_config_match_init(ss) == 0) {
8934
        /* No configured cipher is both supported by PK11 and allowed.
8935
         * This is a configuration error, so report handshake failure.*/
8936
0
        FATAL_ERROR(ss, PORT_GetError(), handshake_failure);
8937
0
        return SECFailure;
8938
0
    }
8939
8940
80.3k
    rv = ssl3_NegotiateCipherSuiteInner(ss, suites, ss->version, &selected);
8941
80.3k
    if (rv != SECSuccess) {
8942
459
        return SECFailure;
8943
459
    }
8944
8945
79.9k
    ss->ssl3.hs.cipher_suite = selected;
8946
79.9k
    return ssl3_SetupCipherSuite(ss, initHashes);
8947
80.3k
}
8948
8949
/*
8950
 * Call the SNI config hook.
8951
 *
8952
 * Called from:
8953
 *   ssl3_HandleClientHello
8954
 *   tls13_HandleClientHelloPart2
8955
 */
8956
SECStatus
8957
ssl3_ServerCallSNICallback(sslSocket *ss)
8958
79.6k
{
8959
79.6k
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8960
79.6k
    SSL3AlertDescription desc = illegal_parameter;
8961
79.6k
    int ret = 0;
8962
8963
#ifdef SSL_SNI_ALLOW_NAME_CHANGE_2HS
8964
#error ("No longer allowed to set SSL_SNI_ALLOW_NAME_CHANGE_2HS")
8965
#endif
8966
79.6k
    if (!ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
8967
79.6k
        if (ss->firstHsDone) {
8968
            /* Check that we don't have the name is current spec
8969
             * if this extension was not negotiated on the 2d hs. */
8970
55.7k
            PRBool passed = PR_TRUE;
8971
55.7k
            ssl_GetSpecReadLock(ss); /*******************************/
8972
55.7k
            if (ss->ssl3.hs.srvVirtName.data) {
8973
0
                passed = PR_FALSE;
8974
0
            }
8975
55.7k
            ssl_ReleaseSpecReadLock(ss); /***************************/
8976
55.7k
            if (!passed) {
8977
0
                errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8978
0
                desc = handshake_failure;
8979
0
                goto alert_loser;
8980
0
            }
8981
55.7k
        }
8982
79.6k
        return SECSuccess;
8983
79.6k
    }
8984
8985
0
    if (ss->sniSocketConfig)
8986
0
        do { /* not a loop */
8987
0
            PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
8988
0
                        ssl_preinfo_all);
8989
8990
0
            ret = SSL_SNI_SEND_ALERT;
8991
            /* If extension is negotiated, the len of names should > 0. */
8992
0
            if (ss->xtnData.sniNameArrSize) {
8993
                /* Calling client callback to reconfigure the socket. */
8994
0
                ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
8995
0
                                                        ss->xtnData.sniNameArr,
8996
0
                                                        ss->xtnData.sniNameArrSize,
8997
0
                                                        ss->sniSocketConfigArg);
8998
0
            }
8999
0
            if (ret <= SSL_SNI_SEND_ALERT) {
9000
                /* Application does not know the name or was not able to
9001
                 * properly reconfigure the socket. */
9002
0
                errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
9003
0
                desc = unrecognized_name;
9004
0
                break;
9005
0
            } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
9006
0
                SECStatus rv = SECSuccess;
9007
0
                SECItem pwsNameBuf = { 0, NULL, 0 };
9008
0
                SECItem *pwsName = &pwsNameBuf;
9009
0
                SECItem *cwsName;
9010
9011
0
                ssl_GetSpecWriteLock(ss); /*******************************/
9012
0
                cwsName = &ss->ssl3.hs.srvVirtName;
9013
                /* not allow name change on the 2d HS */
9014
0
                if (ss->firstHsDone) {
9015
0
                    if (ssl3_ServerNameCompare(pwsName, cwsName)) {
9016
0
                        ssl_ReleaseSpecWriteLock(ss); /******************/
9017
0
                        errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
9018
0
                        desc = handshake_failure;
9019
0
                        ret = SSL_SNI_SEND_ALERT;
9020
0
                        break;
9021
0
                    }
9022
0
                }
9023
0
                if (pwsName->data) {
9024
0
                    SECITEM_FreeItem(pwsName, PR_FALSE);
9025
0
                }
9026
0
                if (cwsName->data) {
9027
0
                    rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
9028
0
                }
9029
0
                ssl_ReleaseSpecWriteLock(ss); /**************************/
9030
0
                if (rv != SECSuccess) {
9031
0
                    errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
9032
0
                    desc = internal_error;
9033
0
                    ret = SSL_SNI_SEND_ALERT;
9034
0
                    break;
9035
0
                }
9036
0
            } else if ((unsigned int)ret < ss->xtnData.sniNameArrSize) {
9037
                /* Application has configured new socket info. Lets check it
9038
                 * and save the name. */
9039
0
                SECStatus rv;
9040
0
                SECItem *name = &ss->xtnData.sniNameArr[ret];
9041
0
                SECItem *pwsName;
9042
9043
                /* get rid of the old name and save the newly picked. */
9044
                /* This code is protected by ssl3HandshakeLock. */
9045
0
                ssl_GetSpecWriteLock(ss); /*******************************/
9046
                /* not allow name change on the 2d HS */
9047
0
                if (ss->firstHsDone) {
9048
0
                    SECItem *cwsName = &ss->ssl3.hs.srvVirtName;
9049
0
                    if (ssl3_ServerNameCompare(name, cwsName)) {
9050
0
                        ssl_ReleaseSpecWriteLock(ss); /******************/
9051
0
                        errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
9052
0
                        desc = handshake_failure;
9053
0
                        ret = SSL_SNI_SEND_ALERT;
9054
0
                        break;
9055
0
                    }
9056
0
                }
9057
0
                pwsName = &ss->ssl3.hs.srvVirtName;
9058
0
                if (pwsName->data) {
9059
0
                    SECITEM_FreeItem(pwsName, PR_FALSE);
9060
0
                }
9061
0
                rv = SECITEM_CopyItem(NULL, pwsName, name);
9062
0
                ssl_ReleaseSpecWriteLock(ss); /***************************/
9063
0
                if (rv != SECSuccess) {
9064
0
                    errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
9065
0
                    desc = internal_error;
9066
0
                    ret = SSL_SNI_SEND_ALERT;
9067
0
                    break;
9068
0
                }
9069
                /* Need to tell the client that application has picked
9070
                 * the name from the offered list and reconfigured the socket.
9071
                 */
9072
0
                ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_server_name_xtn,
9073
0
                                             ssl_SendEmptyExtension);
9074
0
            } else {
9075
                /* Callback returned index outside of the boundary. */
9076
0
                PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize);
9077
0
                errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
9078
0
                desc = internal_error;
9079
0
                ret = SSL_SNI_SEND_ALERT;
9080
0
                break;
9081
0
            }
9082
0
        } while (0);
9083
0
    ssl3_FreeSniNameArray(&ss->xtnData);
9084
0
    if (ret <= SSL_SNI_SEND_ALERT) {
9085
        /* desc and errCode should be set. */
9086
0
        goto alert_loser;
9087
0
    }
9088
9089
0
    return SECSuccess;
9090
9091
0
alert_loser:
9092
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
9093
0
    PORT_SetError(errCode);
9094
0
    return SECFailure;
9095
0
}
9096
9097
SECStatus
9098
ssl3_SelectServerCert(sslSocket *ss)
9099
75.7k
{
9100
75.7k
    const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
9101
75.7k
    PRCList *cursor;
9102
75.7k
    SECStatus rv;
9103
9104
    /* If the client didn't include the supported groups extension, assume just
9105
     * P-256 support and disable all the other ECDHE groups.  This also affects
9106
     * ECDHE group selection, but this function is called first. */
9107
75.7k
    if (!ssl3_ExtensionNegotiated(ss, ssl_supported_groups_xtn)) {
9108
66.1k
        unsigned int i;
9109
2.38M
        for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
9110
2.31M
            if (ss->namedGroupPreferences[i] &&
9111
639k
                ss->namedGroupPreferences[i]->keaType == ssl_kea_ecdh &&
9112
117k
                ss->namedGroupPreferences[i]->name != ssl_grp_ec_secp256r1) {
9113
51.9k
                ss->namedGroupPreferences[i] = NULL;
9114
51.9k
            }
9115
2.31M
        }
9116
66.1k
    }
9117
9118
    /* This picks the first certificate that has:
9119
     * a) the right authentication method, and
9120
     * b) the right named curve (EC only)
9121
     *
9122
     * We might want to do some sort of ranking here later.  For now, it's all
9123
     * based on what order they are configured in. */
9124
75.7k
    for (cursor = PR_NEXT_LINK(&ss->serverCerts);
9125
213k
         cursor != &ss->serverCerts;
9126
213k
         cursor = PR_NEXT_LINK(cursor)) {
9127
213k
        sslServerCert *cert = (sslServerCert *)cursor;
9128
213k
        if (kea_def->authKeyType == ssl_auth_rsa_sign) {
9129
            /* We consider PSS certificates here as well for TLS 1.2. */
9130
64.3k
            if (!SSL_CERT_IS(cert, ssl_auth_rsa_sign) &&
9131
42.8k
                (!SSL_CERT_IS(cert, ssl_auth_rsa_pss) ||
9132
42.8k
                 ss->version < SSL_LIBRARY_VERSION_TLS_1_2)) {
9133
42.8k
                continue;
9134
42.8k
            }
9135
149k
        } else {
9136
149k
            if (!SSL_CERT_IS(cert, kea_def->authKeyType)) {
9137
93.0k
                continue;
9138
93.0k
            }
9139
56.4k
            if (SSL_CERT_IS_EC(cert) &&
9140
9.89k
                !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
9141
2.11k
                continue;
9142
2.11k
            }
9143
56.4k
        }
9144
9145
        /* Found one. */
9146
75.7k
        ss->sec.serverCert = cert;
9147
75.7k
        ss->sec.authKeyBits = cert->serverKeyBits;
9148
9149
        /* Don't pick a signature scheme if we aren't going to use it. */
9150
75.7k
        if (kea_def->signKeyType == nullKey) {
9151
47.3k
            ss->sec.authType = kea_def->authKeyType;
9152
47.3k
            return SECSuccess;
9153
47.3k
        }
9154
9155
28.4k
        rv = ssl3_PickServerSignatureScheme(ss);
9156
28.4k
        if (rv != SECSuccess) {
9157
124
            return SECFailure;
9158
124
        }
9159
28.2k
        ss->sec.authType =
9160
28.2k
            ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme);
9161
28.2k
        return SECSuccess;
9162
28.4k
    }
9163
9164
8
    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
9165
8
    return SECFailure;
9166
75.7k
}
9167
9168
static SECStatus
9169
ssl_GenerateServerRandom(sslSocket *ss)
9170
78.3k
{
9171
78.3k
    SECStatus rv;
9172
78.3k
    PRUint8 *downgradeSentinel;
9173
9174
78.3k
    rv = ssl3_GetNewRandom(ss->ssl3.hs.server_random);
9175
78.3k
    if (rv != SECSuccess) {
9176
0
        return SECFailure;
9177
0
    }
9178
9179
78.3k
    if (ss->version == ss->vrange.max) {
9180
28.6k
        return SECSuccess;
9181
28.6k
    }
9182
9183
    /*
9184
     * [RFC 8446 Section 4.1.3].
9185
     *
9186
     * TLS 1.3 servers which negotiate TLS 1.2 or below in response to a
9187
     * ClientHello MUST set the last 8 bytes of their Random value specially in
9188
     * their ServerHello.
9189
     *
9190
     * If negotiating TLS 1.2, TLS 1.3 servers MUST set the last 8 bytes of
9191
     * their Random value to the bytes:
9192
     *
9193
     *   44 4F 57 4E 47 52 44 01
9194
     *
9195
     * If negotiating TLS 1.1 or below, TLS 1.3 servers MUST, and TLS 1.2
9196
     * servers SHOULD, set the last 8 bytes of their ServerHello.Random value to
9197
     * the bytes:
9198
     *
9199
     *   44 4F 57 4E 47 52 44 00
9200
     */
9201
49.7k
    downgradeSentinel =
9202
49.7k
        ss->ssl3.hs.server_random +
9203
49.7k
        SSL3_RANDOM_LENGTH - sizeof(tls12_downgrade_random);
9204
49.7k
    if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_2) {
9205
49.5k
        switch (ss->version) {
9206
49.3k
            case SSL_LIBRARY_VERSION_TLS_1_2:
9207
                /* vrange.max > 1.2, since we didn't early exit above. */
9208
49.3k
                PORT_Memcpy(downgradeSentinel,
9209
49.3k
                            tls12_downgrade_random, sizeof(tls12_downgrade_random));
9210
49.3k
                break;
9211
107
            case SSL_LIBRARY_VERSION_TLS_1_1:
9212
195
            case SSL_LIBRARY_VERSION_TLS_1_0:
9213
195
                PORT_Memcpy(downgradeSentinel,
9214
195
                            tls1_downgrade_random, sizeof(tls1_downgrade_random));
9215
195
                break;
9216
0
            default:
9217
                /* Do not change random. */
9218
0
                break;
9219
49.5k
        }
9220
49.5k
    }
9221
9222
49.7k
    return SECSuccess;
9223
49.7k
}
9224
9225
SECStatus
9226
ssl3_HandleClientHelloPreamble(sslSocket *ss, PRUint8 **b, PRUint32 *length, SECItem *sidBytes,
9227
                               SECItem *cookieBytes, SECItem *suites, SECItem *comps)
9228
83.1k
{
9229
83.1k
    SECStatus rv;
9230
83.1k
    PRUint32 tmp;
9231
83.1k
    rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
9232
83.1k
    if (rv != SECSuccess) {
9233
33
        return SECFailure; /* malformed, alert already sent */
9234
33
    }
9235
9236
    /* Translate the version. */
9237
83.0k
    if (IS_DTLS(ss)) {
9238
12.2k
        ss->clientHelloVersion = dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
9239
70.8k
    } else {
9240
70.8k
        ss->clientHelloVersion = (SSL3ProtocolVersion)tmp;
9241
70.8k
    }
9242
9243
    /* Grab the client random data. */
9244
83.0k
    rv = ssl3_ConsumeHandshake(
9245
83.0k
        ss, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, b, length);
9246
83.0k
    if (rv != SECSuccess) {
9247
101
        return SECFailure; /* malformed */
9248
101
    }
9249
9250
    /* Grab the client's SID, if present. */
9251
82.9k
    rv = ssl3_ConsumeHandshakeVariable(ss, sidBytes, 1, b, length);
9252
    /* Check that the SID has the format: opaque legacy_session_id<0..32>, as
9253
     * specified in RFC8446, Section 4.1.2. */
9254
82.9k
    if (rv != SECSuccess || sidBytes->len > SSL3_SESSIONID_BYTES) {
9255
74
        return SECFailure; /* malformed */
9256
74
    }
9257
9258
    /* Grab the client's cookie, if present. It is checked after version negotiation. */
9259
82.8k
    if (IS_DTLS(ss)) {
9260
12.1k
        rv = ssl3_ConsumeHandshakeVariable(ss, cookieBytes, 1, b, length);
9261
12.1k
        if (rv != SECSuccess) {
9262
17
            return SECFailure; /* malformed */
9263
17
        }
9264
12.1k
    }
9265
9266
    /* Grab the list of cipher suites. */
9267
82.8k
    rv = ssl3_ConsumeHandshakeVariable(ss, suites, 2, b, length);
9268
82.8k
    if (rv != SECSuccess) {
9269
86
        return SECFailure; /* malformed */
9270
86
    }
9271
9272
    /* Grab the list of compression methods. */
9273
82.7k
    rv = ssl3_ConsumeHandshakeVariable(ss, comps, 1, b, length);
9274
82.7k
    if (rv != SECSuccess) {
9275
12
        return SECFailure; /* malformed */
9276
12
    }
9277
82.7k
    return SECSuccess;
9278
82.7k
}
9279
9280
static SECStatus
9281
ssl3_ValidatePreambleWithVersion(sslSocket *ss, const SECItem *sidBytes, const SECItem *comps,
9282
                                 const SECItem *cookieBytes)
9283
82.3k
{
9284
82.3k
    SECStatus rv;
9285
82.3k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
9286
5.25k
        if (sidBytes->len > 0 && !IS_DTLS(ss)) {
9287
124
            SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
9288
124
            rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.fakeSid, sidBytes);
9289
124
            if (rv != SECSuccess) {
9290
0
                FATAL_ERROR(ss, PORT_GetError(), internal_error);
9291
0
                return SECFailure;
9292
0
            }
9293
124
        }
9294
9295
        /* TLS 1.3 requires that compression include only null. */
9296
5.25k
        if (comps->len != 1 || comps->data[0] != ssl_compression_null) {
9297
39
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
9298
39
            return SECFailure;
9299
39
        }
9300
9301
        /* receivedCcs is only valid if we sent an HRR. */
9302
5.21k
        if (ss->ssl3.hs.receivedCcs && !ss->ssl3.hs.helloRetry) {
9303
2
            FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message);
9304
2
            return SECFailure;
9305
2
        }
9306
9307
        /* A DTLS 1.3-only client MUST set the legacy_cookie field to zero length.
9308
         * If a DTLS 1.3 ClientHello is received with any other value in this field,
9309
         * the server MUST abort the handshake with an "illegal_parameter" alert. */
9310
5.21k
        if (IS_DTLS(ss) && cookieBytes->len != 0) {
9311
2
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
9312
2
            return SECFailure;
9313
2
        }
9314
77.1k
    } else {
9315
        /* ECH not possible here. */
9316
77.1k
        ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
9317
9318
        /* HRR and ECH are TLS1.3-only. We ignore the Cookie extension here. */
9319
77.1k
        if (ss->ssl3.hs.helloRetry) {
9320
0
            FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, protocol_version);
9321
0
            return SECFailure;
9322
0
        }
9323
9324
        /* receivedCcs is only valid if we sent an HRR. */
9325
77.1k
        if (ss->ssl3.hs.receivedCcs) {
9326
2
            FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message);
9327
2
            return SECFailure;
9328
2
        }
9329
9330
        /* TLS versions prior to 1.3 must include null somewhere. */
9331
77.1k
        if (comps->len < 1 ||
9332
77.0k
            !memchr(comps->data, ssl_compression_null, comps->len)) {
9333
31
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
9334
31
            return SECFailure;
9335
31
        }
9336
9337
        /* We never send cookies in DTLS 1.2. */
9338
77.0k
        if (IS_DTLS(ss) && cookieBytes->len != 0) {
9339
2
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
9340
2
            return SECFailure;
9341
2
        }
9342
77.0k
    }
9343
9344
82.2k
    return SECSuccess;
9345
82.3k
}
9346
9347
/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9348
 * ssl3 Client Hello message.
9349
 * Caller must hold Handshake and RecvBuf locks.
9350
 */
9351
static SECStatus
9352
ssl3_HandleClientHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
9353
83.1k
{
9354
83.1k
    sslSessionID *sid = NULL;
9355
83.1k
    unsigned int i;
9356
83.1k
    SECStatus rv;
9357
83.1k
    PRUint32 extensionLength;
9358
83.1k
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9359
83.1k
    SSL3AlertDescription desc = illegal_parameter;
9360
83.1k
    SSL3AlertLevel level = alert_fatal;
9361
83.1k
    TLSExtension *versionExtension;
9362
83.1k
    SECItem sidBytes = { siBuffer, NULL, 0 };
9363
83.1k
    SECItem cookieBytes = { siBuffer, NULL, 0 };
9364
83.1k
    SECItem suites = { siBuffer, NULL, 0 };
9365
83.1k
    SECItem comps = { siBuffer, NULL, 0 };
9366
83.1k
    SECItem *echInner = NULL;
9367
83.1k
    PRBool isTLS13;
9368
83.1k
    const PRUint8 *savedMsg = b;
9369
83.1k
    const PRUint32 savedLen = length;
9370
9371
83.1k
    SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
9372
83.1k
                SSL_GETPID(), ss->fd));
9373
9374
83.1k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
9375
83.1k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9376
83.1k
    ss->ssl3.hs.preliminaryInfo = 0;
9377
9378
83.1k
    if (!ss->sec.isServer ||
9379
83.1k
        (ss->ssl3.hs.ws != wait_client_hello &&
9380
55.9k
         ss->ssl3.hs.ws != idle_handshake)) {
9381
50
        desc = unexpected_message;
9382
50
        errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
9383
50
        goto alert_loser;
9384
50
    }
9385
83.1k
    if (ss->ssl3.hs.ws == idle_handshake) {
9386
        /* Refuse re-handshake when we have already negotiated TLS 1.3. */
9387
55.8k
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
9388
2
            desc = unexpected_message;
9389
2
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9390
2
            goto alert_loser;
9391
2
        }
9392
55.8k
        if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
9393
1
            desc = no_renegotiation;
9394
1
            level = alert_warning;
9395
1
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9396
1
            goto alert_loser;
9397
1
        }
9398
55.8k
    }
9399
9400
    /* We should always be in a fresh state. */
9401
83.1k
    SSL_ASSERT_HASHES_EMPTY(ss);
9402
9403
    /* Get peer name of client */
9404
83.1k
    rv = ssl_GetPeerInfo(ss);
9405
83.1k
    if (rv != SECSuccess) {
9406
0
        return rv; /* error code is set. */
9407
0
    }
9408
9409
    /* We might be starting session renegotiation in which case we should
9410
     * clear previous state.
9411
     */
9412
83.1k
    ssl3_ResetExtensionData(&ss->xtnData, ss);
9413
83.1k
    ss->statelessResume = PR_FALSE;
9414
9415
83.1k
    if (IS_DTLS(ss)) {
9416
12.2k
        dtls_RehandshakeCleanup(ss);
9417
12.2k
    }
9418
9419
83.1k
    rv = ssl3_HandleClientHelloPreamble(ss, &b, &length, &sidBytes,
9420
83.1k
                                        &cookieBytes, &suites, &comps);
9421
83.1k
    if (rv != SECSuccess) {
9422
323
        goto loser; /* malformed */
9423
323
    }
9424
9425
    /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
9426
     * we are restarting a previous session until extensions have been
9427
     * parsed, since we might have received a SessionTicket extension.
9428
     * Note: we allow extensions even when negotiating SSL3 for the sake
9429
     * of interoperability (and backwards compatibility).
9430
     */
9431
82.7k
    if (length) {
9432
        /* Get length of hello extensions */
9433
24.4k
        rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
9434
24.4k
        if (rv != SECSuccess) {
9435
7
            goto loser; /* alert already sent */
9436
7
        }
9437
24.4k
        if (extensionLength != length) {
9438
82
            errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9439
82
            desc = decode_error;
9440
82
            goto alert_loser;
9441
82
        }
9442
9443
24.3k
        rv = ssl3_ParseExtensions(ss, &b, &length);
9444
24.3k
        if (rv != SECSuccess) {
9445
55
            goto loser; /* malformed */
9446
55
        }
9447
24.3k
    }
9448
9449
82.6k
    versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
9450
82.6k
    if (versionExtension) {
9451
6.18k
        rv = tls13_NegotiateVersion(ss, versionExtension);
9452
6.18k
        if (rv != SECSuccess) {
9453
83
            errCode = PORT_GetError();
9454
83
            desc = (errCode == SSL_ERROR_UNSUPPORTED_VERSION) ? protocol_version : illegal_parameter;
9455
83
            goto alert_loser;
9456
83
        }
9457
76.4k
    } else {
9458
        /* The PR_MIN here ensures that we never negotiate 1.3 if the
9459
         * peer didn't offer "supported_versions". */
9460
76.4k
        rv = ssl3_NegotiateVersion(ss,
9461
76.4k
                                   PR_MIN(ss->clientHelloVersion,
9462
76.4k
                                          SSL_LIBRARY_VERSION_TLS_1_2),
9463
76.4k
                                   PR_TRUE);
9464
        /* Send protocol version alert if the ClientHello.legacy_version is not
9465
         * supported by the server.
9466
         *
9467
         * If the "supported_versions" extension is absent and the server only
9468
         * supports versions greater than ClientHello.legacy_version, the
9469
         * server MUST abort the handshake with a "protocol_version" alert
9470
         * [RFC8446, Appendix D.2]. */
9471
76.4k
        if (rv != SECSuccess) {
9472
49
            desc = protocol_version;
9473
49
            errCode = SSL_ERROR_UNSUPPORTED_VERSION;
9474
49
            goto alert_loser;
9475
49
        }
9476
76.4k
    }
9477
82.5k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
9478
9479
    /* Update the write spec to match the selected version. */
9480
82.5k
    if (!ss->firstHsDone) {
9481
26.6k
        ssl_GetSpecWriteLock(ss);
9482
26.6k
        ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
9483
26.6k
        ssl_ReleaseSpecWriteLock(ss);
9484
26.6k
    }
9485
9486
82.5k
    isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
9487
82.5k
    if (isTLS13) {
9488
5.38k
        if (ss->firstHsDone) {
9489
1
            desc = unexpected_message;
9490
1
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9491
1
            goto alert_loser;
9492
1
        }
9493
9494
        /* If there is a cookie, then this is a second ClientHello (TLS 1.3). */
9495
5.38k
        if (ssl3_FindExtension(ss, ssl_tls13_cookie_xtn)) {
9496
265
            ss->ssl3.hs.helloRetry = PR_TRUE;
9497
265
        }
9498
9499
5.38k
        rv = tls13_MaybeHandleEch(ss, savedMsg, savedLen, &sidBytes,
9500
5.38k
                                  &comps, &cookieBytes, &suites, &echInner);
9501
5.38k
        if (rv != SECSuccess) {
9502
123
            errCode = PORT_GetError();
9503
123
            goto loser; /* code set, alert sent. */
9504
123
        }
9505
5.38k
    }
9506
9507
82.3k
    rv = ssl3_ValidatePreambleWithVersion(ss, &sidBytes, &comps, &cookieBytes);
9508
82.3k
    if (rv != SECSuccess) {
9509
78
        errCode = PORT_GetError();
9510
78
        goto loser; /* code set, alert sent. */
9511
78
    }
9512
9513
    /* Now parse the rest of the extensions. */
9514
82.2k
    rv = ssl3_HandleParsedExtensions(ss, ssl_hs_client_hello);
9515
82.2k
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
9516
82.2k
    if (rv != SECSuccess) {
9517
1.59k
        if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
9518
236
            errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
9519
236
        }
9520
1.59k
        goto loser; /* malformed */
9521
1.59k
    }
9522
9523
    /* If the ClientHello version is less than our maximum version, check for a
9524
     * TLS_FALLBACK_SCSV and reject the connection if found. */
9525
80.7k
    if (ss->vrange.max > ss->version) {
9526
315k
        for (i = 0; i + 1 < suites.len; i += 2) {
9527
265k
            PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
9528
265k
            if (suite_i != TLS_FALLBACK_SCSV)
9529
265k
                continue;
9530
5
            desc = inappropriate_fallback;
9531
5
            errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
9532
5
            goto alert_loser;
9533
265k
        }
9534
50.0k
    }
9535
9536
80.6k
    if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9537
        /* If we didn't receive an RI extension, look for the SCSV,
9538
         * and if found, treat it just like an empty RI extension
9539
         * by processing a local copy of an empty RI extension.
9540
         */
9541
302k
        for (i = 0; i + 1 < suites.len; i += 2) {
9542
230k
            PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
9543
230k
            if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
9544
7.08k
                PRUint8 *b2 = (PRUint8 *)emptyRIext;
9545
7.08k
                PRUint32 L2 = sizeof emptyRIext;
9546
7.08k
                (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
9547
7.08k
                break;
9548
7.08k
            }
9549
230k
        }
9550
78.9k
    }
9551
9552
    /* The check for renegotiation in TLS 1.3 is earlier. */
9553
80.6k
    if (!isTLS13) {
9554
76.3k
        if (ss->firstHsDone &&
9555
55.7k
            (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
9556
55.7k
             ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) &&
9557
0
            !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9558
0
            desc = no_renegotiation;
9559
0
            level = alert_warning;
9560
0
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9561
0
            goto alert_loser;
9562
0
        }
9563
76.3k
        if ((ss->opt.requireSafeNegotiation ||
9564
71.7k
             (ss->firstHsDone && ss->peerRequestedProtection)) &&
9565
4.64k
            !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9566
274
            desc = handshake_failure;
9567
274
            errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
9568
274
            goto alert_loser;
9569
274
        }
9570
76.3k
    }
9571
9572
    /* We do stateful resumes only if we are in TLS < 1.3 and
9573
     * either of the following conditions are satisfied:
9574
     * (1) the client does not support the session ticket extension, or
9575
     * (2) the client support the session ticket extension, but sent an
9576
     * empty ticket.
9577
     */
9578
80.4k
    if (!isTLS13 &&
9579
76.1k
        (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
9580
75.3k
         ss->xtnData.emptySessionTicket)) {
9581
75.3k
        if (sidBytes.len > 0 && !ss->opt.noCache) {
9582
4.46k
            SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
9583
4.46k
                        SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
9584
4.46k
                        ss->sec.ci.peer.pr_s6_addr32[1],
9585
4.46k
                        ss->sec.ci.peer.pr_s6_addr32[2],
9586
4.46k
                        ss->sec.ci.peer.pr_s6_addr32[3]));
9587
4.46k
            if (ssl_sid_lookup) {
9588
4.46k
                sid = (*ssl_sid_lookup)(ssl_Time(ss), &ss->sec.ci.peer,
9589
4.46k
                                        sidBytes.data, sidBytes.len, ss->dbHandle);
9590
4.46k
            } else {
9591
0
                errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
9592
0
                goto loser;
9593
0
            }
9594
4.46k
        }
9595
75.3k
    } else if (ss->statelessResume) {
9596
        /* Fill in the client's session ID if doing a stateless resume.
9597
         * (When doing stateless resumes, server echos client's SessionID.)
9598
         * This branch also handles TLS 1.3 resumption-PSK.
9599
         */
9600
        /* Take ownership of the session from the socket. */
9601
873
        sid = ssl_TakeSocketSID(ss);
9602
873
        PORT_Assert(sid != NULL); /* Should have already been filled in.*/
9603
9604
873
        if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
9605
9
            sid->u.ssl3.sessionIDLength = sidBytes.len;
9606
9
            PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
9607
9
                        sidBytes.len);
9608
9
            sid->u.ssl3.sessionIDLength = sidBytes.len;
9609
864
        } else {
9610
864
            sid->u.ssl3.sessionIDLength = 0;
9611
864
        }
9612
873
    }
9613
9614
    /* Free a potentially leftover session ID from a previous handshake. */
9615
80.4k
    if (ss->sec.ci.sid) {
9616
55.1k
        ssl_SetSocketSID(ss, NULL);
9617
55.1k
    }
9618
9619
80.4k
    if (sid != NULL) {
9620
        /* We've found a session cache entry for this client.
9621
         * Now, if we're going to require a client-auth cert,
9622
         * and we don't already have this client's cert in the session cache,
9623
         * and this is the first handshake on this connection (not a redo),
9624
         * then drop this old cache entry and start a new session.
9625
         */
9626
873
        if ((sid->peerCertDER.data == NULL) && ss->opt.requestCertificate &&
9627
146
            ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
9628
102
             (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
9629
102
             ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) &&
9630
44
              !ss->firstHsDone))) {
9631
9632
44
            SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
9633
44
            ssl_FreeSID(sid);
9634
44
            sid = NULL;
9635
44
            ss->statelessResume = PR_FALSE;
9636
44
        }
9637
873
    }
9638
9639
80.4k
    if (IS_DTLS(ss)) {
9640
11.1k
        ssl3_DisableNonDTLSSuites(ss);
9641
11.1k
        dtls_ReceivedFirstMessageInFlight(ss);
9642
11.1k
    }
9643
9644
80.4k
    if (isTLS13) {
9645
4.31k
        rv = tls13_HandleClientHelloPart2(ss, &suites, sid,
9646
4.31k
                                          ss->ssl3.hs.echAccepted ? echInner->data : savedMsg,
9647
4.31k
                                          ss->ssl3.hs.echAccepted ? echInner->len : savedLen);
9648
4.31k
        SECITEM_FreeItem(echInner, PR_TRUE);
9649
4.31k
        echInner = NULL;
9650
76.1k
    } else {
9651
76.1k
        rv = ssl3_HandleClientHelloPart2(ss, &suites, sid,
9652
76.1k
                                         savedMsg, savedLen);
9653
76.1k
    }
9654
80.4k
    if (rv != SECSuccess) {
9655
1.33k
        errCode = PORT_GetError();
9656
1.33k
        goto loser;
9657
1.33k
    }
9658
79.0k
    return SECSuccess;
9659
9660
547
alert_loser:
9661
547
    (void)SSL3_SendAlert(ss, level, desc);
9662
/* FALLTHRU */
9663
4.06k
loser:
9664
4.06k
    SECITEM_FreeItem(echInner, PR_TRUE);
9665
4.06k
    PORT_SetError(errCode);
9666
4.06k
    return SECFailure;
9667
547
}
9668
9669
/* unwrap helper function to handle the case where the wrapKey doesn't wind
9670
 * up in the correct token for the master secret */
9671
PK11SymKey *
9672
ssl_unwrapSymKey(PK11SymKey *wrapKey,
9673
                 CK_MECHANISM_TYPE wrapType, SECItem *param,
9674
                 SECItem *wrappedKey,
9675
                 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
9676
                 int keySize, CK_FLAGS keyFlags, void *pinArg)
9677
0
{
9678
0
    PK11SymKey *unwrappedKey;
9679
9680
    /* unwrap the master secret. */
9681
0
    unwrappedKey = PK11_UnwrapSymKeyWithFlags(wrapKey, wrapType, param,
9682
0
                                              wrappedKey, target, operation, keySize,
9683
0
                                              keyFlags);
9684
0
    if (!unwrappedKey) {
9685
0
        PK11SlotInfo *targetSlot = PK11_GetBestSlot(target, pinArg);
9686
0
        PK11SymKey *newWrapKey;
9687
9688
        /* it's possible that we failed to unwrap because the wrapKey is in
9689
         * a slot that can't handle target. Move the wrapKey to a slot that
9690
         * can handle this mechanism and retry the operation */
9691
0
        if (targetSlot == NULL) {
9692
0
            return NULL;
9693
0
        }
9694
0
        newWrapKey = PK11_MoveSymKey(targetSlot, CKA_UNWRAP, 0,
9695
0
                                     PR_FALSE, wrapKey);
9696
0
        PK11_FreeSlot(targetSlot);
9697
0
        if (newWrapKey == NULL) {
9698
0
            return NULL;
9699
0
        }
9700
0
        unwrappedKey = PK11_UnwrapSymKeyWithFlags(newWrapKey, wrapType, param,
9701
0
                                                  wrappedKey, target, operation, keySize,
9702
0
                                                  keyFlags);
9703
0
        PK11_FreeSymKey(newWrapKey);
9704
0
    }
9705
0
    return unwrappedKey;
9706
0
}
9707
9708
static SECStatus
9709
ssl3_UnwrapMasterSecretServer(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
9710
0
{
9711
0
    PK11SymKey *wrapKey;
9712
0
    CK_FLAGS keyFlags = 0;
9713
0
    SECItem wrappedMS = {
9714
0
        siBuffer,
9715
0
        sid->u.ssl3.keys.wrapped_master_secret,
9716
0
        sid->u.ssl3.keys.wrapped_master_secret_len
9717
0
    };
9718
9719
0
    wrapKey = ssl3_GetWrappingKey(ss, NULL, sid->u.ssl3.masterWrapMech,
9720
0
                                  ss->pkcs11PinArg);
9721
0
    if (!wrapKey) {
9722
0
        return SECFailure;
9723
0
    }
9724
9725
0
    if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
9726
0
        keyFlags = CKF_SIGN | CKF_VERIFY;
9727
0
    }
9728
9729
0
    *ms = ssl_unwrapSymKey(wrapKey, sid->u.ssl3.masterWrapMech, NULL,
9730
0
                           &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
9731
0
                           CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH,
9732
0
                           keyFlags, ss->pkcs11PinArg);
9733
0
    PK11_FreeSymKey(wrapKey);
9734
0
    if (!*ms) {
9735
0
        SSL_TRC(10, ("%d: SSL3[%d]: server wrapping key found, but couldn't unwrap MasterSecret. wrapMech=0x%0lx",
9736
0
                     SSL_GETPID(), ss->fd, sid->u.ssl3.masterWrapMech));
9737
0
        return SECFailure;
9738
0
    }
9739
0
    return SECSuccess;
9740
0
}
9741
9742
static SECStatus
9743
ssl3_HandleClientHelloPart2(sslSocket *ss,
9744
                            SECItem *suites,
9745
                            sslSessionID *sid,
9746
                            const PRUint8 *msg,
9747
                            unsigned int len)
9748
76.1k
{
9749
76.1k
    PRBool haveXmitBufLock = PR_FALSE;
9750
76.1k
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9751
76.1k
    SSL3AlertDescription desc = illegal_parameter;
9752
76.1k
    SECStatus rv;
9753
76.1k
    unsigned int i;
9754
76.1k
    unsigned int j;
9755
9756
76.1k
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_client_hello, msg, len);
9757
76.1k
    if (rv != SECSuccess) {
9758
0
        errCode = SEC_ERROR_LIBRARY_FAILURE;
9759
0
        desc = internal_error;
9760
0
        goto alert_loser;
9761
0
    }
9762
9763
    /* If we already have a session for this client, be sure to pick the same
9764
    ** cipher suite we picked before.  This is not a loop, despite appearances.
9765
    */
9766
76.1k
    if (sid)
9767
764
        do {
9768
764
            ssl3CipherSuiteCfg *suite;
9769
764
            SSLVersionRange vrange = { ss->version, ss->version };
9770
9771
764
            suite = ss->cipherSuites;
9772
            /* Find the entry for the cipher suite used in the cached session. */
9773
55.0k
            for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
9774
54.2k
                if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
9775
0
                    break;
9776
54.2k
            }
9777
9778
764
            if (j == 0)
9779
764
                break;
9780
9781
            /* Double check that the cached cipher suite is still enabled,
9782
             * implemented, and allowed by policy.  Might have been disabled.
9783
             */
9784
0
            if (ssl3_config_match_init(ss) == 0) {
9785
0
                desc = handshake_failure;
9786
0
                errCode = PORT_GetError();
9787
0
                goto alert_loser;
9788
0
            }
9789
0
            if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss))
9790
0
                break;
9791
9792
            /* Double check that the cached cipher suite is in the client's
9793
             * list.  If it isn't, fall through and start a new session. */
9794
0
            for (i = 0; i + 1 < suites->len; i += 2) {
9795
0
                PRUint16 suite_i = (suites->data[i] << 8) | suites->data[i + 1];
9796
0
                if (suite_i == suite->cipher_suite) {
9797
0
                    ss->ssl3.hs.cipher_suite = suite_i;
9798
0
                    rv = ssl3_SetupCipherSuite(ss, PR_TRUE);
9799
0
                    if (rv != SECSuccess) {
9800
0
                        desc = internal_error;
9801
0
                        errCode = PORT_GetError();
9802
0
                        goto alert_loser;
9803
0
                    }
9804
9805
0
                    goto cipher_found;
9806
0
                }
9807
0
            }
9808
0
        } while (0);
9809
    /* START A NEW SESSION */
9810
9811
76.1k
    rv = ssl3_NegotiateCipherSuite(ss, suites, PR_TRUE);
9812
76.1k
    if (rv != SECSuccess) {
9813
351
        desc = handshake_failure;
9814
351
        errCode = PORT_GetError();
9815
351
        goto alert_loser;
9816
351
    }
9817
9818
75.7k
cipher_found:
9819
75.7k
    suites->data = NULL;
9820
9821
    /* If there are any failures while processing the old sid,
9822
     * we don't consider them to be errors.  Instead, We just behave
9823
     * as if the client had sent us no sid to begin with, and make a new one.
9824
     * The exception here is attempts to resume extended_master_secret
9825
     * sessions without the extension, which causes an alert.
9826
     */
9827
75.7k
    if (sid != NULL)
9828
753
        do {
9829
753
            PK11SymKey *masterSecret;
9830
9831
753
            if (sid->version != ss->version ||
9832
753
                sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
9833
753
                break; /* not an error */
9834
753
            }
9835
9836
            /* server sids don't remember the server cert we previously sent,
9837
            ** but they do remember the slot we originally used, so we
9838
            ** can locate it again, provided that the current ssl socket
9839
            ** has had its server certs configured the same as the previous one.
9840
            */
9841
0
            ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType, sid->namedCurve);
9842
0
            if (!ss->sec.serverCert || !ss->sec.serverCert->serverCert) {
9843
                /* A compatible certificate must not have been configured.  It
9844
                 * might not be the same certificate, but we only find that out
9845
                 * when the ticket fails to decrypt. */
9846
0
                break;
9847
0
            }
9848
9849
            /* [draft-ietf-tls-session-hash-06; Section 5.3]
9850
             * o  If the original session did not use the "extended_master_secret"
9851
             *    extension but the new ClientHello contains the extension, then the
9852
             *    server MUST NOT perform the abbreviated handshake.  Instead, it
9853
             *    SHOULD continue with a full handshake (as described in
9854
             *    Section 5.2) to negotiate a new session.
9855
             *
9856
             * o  If the original session used the "extended_master_secret"
9857
             *    extension but the new ClientHello does not contain the extension,
9858
             *    the server MUST abort the abbreviated handshake.
9859
             */
9860
0
            if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
9861
0
                if (!sid->u.ssl3.keys.extendedMasterSecretUsed) {
9862
0
                    break; /* not an error */
9863
0
                }
9864
0
            } else {
9865
0
                if (sid->u.ssl3.keys.extendedMasterSecretUsed) {
9866
                    /* Note: we do not destroy the session */
9867
0
                    desc = handshake_failure;
9868
0
                    errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
9869
0
                    goto alert_loser;
9870
0
                }
9871
0
            }
9872
9873
0
            if (ss->sec.ci.sid) {
9874
0
                ssl_UncacheSessionID(ss);
9875
0
                PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */
9876
0
                if (ss->sec.ci.sid == sid) {
9877
                    /* Ownership transfers to |sid|. */
9878
0
                    (void)ssl_TakeSocketSID(ss);
9879
0
                } else {
9880
0
                    ssl_SetSocketSID(ss, NULL);
9881
0
                }
9882
0
            }
9883
9884
            /* we need to resurrect the master secret.... */
9885
0
            rv = ssl3_UnwrapMasterSecretServer(ss, sid, &masterSecret);
9886
0
            if (rv != SECSuccess) {
9887
0
                break; /* not an error */
9888
0
            }
9889
9890
0
            ssl_SetSocketSID(ss, sid);
9891
            /* On a renegotiation |ss->sec| can hold a client certificate while
9892
             * |sid| has none; keep it rather than clearing unconditionally.
9893
             * ssl_SetPeerCertificate() already replaces any previous one. */
9894
0
            if (sid->peerCertDER.data != NULL) {
9895
0
                rv = ssl_SetPeerCertificate(&ss->sec, &sid->peerCertDER);
9896
0
                if (rv != SECSuccess) {
9897
0
                    errCode = PORT_GetError();
9898
0
                    goto loser;
9899
0
                }
9900
0
            }
9901
9902
            /*
9903
             * Old SID passed all tests, so resume this old session.
9904
             */
9905
0
            SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_hits);
9906
0
            if (ss->statelessResume)
9907
0
                SSL_AtomicIncrementLong(&ssl3stats.hch_sid_stateless_resumes);
9908
0
            ss->ssl3.hs.isResuming = PR_TRUE;
9909
9910
0
            ss->sec.authType = sid->authType;
9911
0
            ss->sec.authKeyBits = sid->authKeyBits;
9912
0
            ss->sec.keaType = sid->keaType;
9913
0
            ss->sec.keaKeyBits = sid->keaKeyBits;
9914
0
            ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
9915
0
            ss->sec.signatureScheme = sid->sigScheme;
9916
9917
0
            ss->sec.localCert =
9918
0
                CERT_DupCertificate(ss->sec.serverCert->serverCert);
9919
9920
            /* Copy cached name in to pending spec */
9921
0
            if (sid != NULL &&
9922
0
                sid->version > SSL_LIBRARY_VERSION_3_0 &&
9923
0
                sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
9924
                /* Set server name from sid */
9925
0
                SECItem *sidName = &sid->u.ssl3.srvName;
9926
0
                SECItem *pwsName = &ss->ssl3.hs.srvVirtName;
9927
0
                if (pwsName->data) {
9928
0
                    SECITEM_FreeItem(pwsName, PR_FALSE);
9929
0
                }
9930
0
                rv = SECITEM_CopyItem(NULL, pwsName, sidName);
9931
0
                if (rv != SECSuccess) {
9932
0
                    errCode = PORT_GetError();
9933
0
                    desc = internal_error;
9934
0
                    goto alert_loser;
9935
0
                }
9936
0
            }
9937
9938
            /* Clean up sni name array */
9939
0
            ssl3_FreeSniNameArray(&ss->xtnData);
9940
9941
0
            ssl_GetXmitBufLock(ss);
9942
0
            haveXmitBufLock = PR_TRUE;
9943
9944
0
            rv = ssl3_SendServerHello(ss);
9945
0
            if (rv != SECSuccess) {
9946
0
                errCode = PORT_GetError();
9947
0
                goto loser;
9948
0
            }
9949
9950
            /* We are re-using the old MS, so no need to derive again. */
9951
0
            rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE);
9952
0
            if (rv != SECSuccess) {
9953
0
                errCode = PORT_GetError();
9954
0
                goto loser;
9955
0
            }
9956
9957
0
            rv = ssl3_SendChangeCipherSpecs(ss);
9958
0
            if (rv != SECSuccess) {
9959
0
                errCode = PORT_GetError();
9960
0
                goto loser;
9961
0
            }
9962
0
            rv = ssl3_SendFinished(ss, 0);
9963
0
            ss->ssl3.hs.ws = wait_change_cipher;
9964
0
            if (rv != SECSuccess) {
9965
0
                errCode = PORT_GetError();
9966
0
                goto loser;
9967
0
            }
9968
9969
0
            ssl_ReleaseXmitBufLock(ss);
9970
9971
0
            return SECSuccess;
9972
0
        } while (0);
9973
9974
75.7k
    if (sid) { /* we had a sid, but it's no longer valid, free it */
9975
753
        ss->statelessResume = PR_FALSE;
9976
753
        SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
9977
753
        ssl_UncacheSessionID(ss);
9978
753
        ssl_FreeSID(sid);
9979
753
        sid = NULL;
9980
753
    }
9981
75.7k
    SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
9982
9983
    /* We only send a session ticket extension if the client supports
9984
     * the extension and we are unable to resume.
9985
     *
9986
     * TODO: send a session ticket if performing a stateful
9987
     * resumption.  (As per RFC4507, a server may issue a session
9988
     * ticket while doing a (stateless or stateful) session resume,
9989
     * but OpenSSL-0.9.8g does not accept session tickets while
9990
     * resuming.)
9991
     */
9992
75.7k
    if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
9993
3.24k
        ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
9994
3.24k
        ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_session_ticket_xtn,
9995
3.24k
                                     ssl_SendEmptyExtension);
9996
3.24k
    }
9997
9998
75.7k
    rv = ssl3_ServerCallSNICallback(ss);
9999
75.7k
    if (rv != SECSuccess) {
10000
        /* The alert has already been sent. */
10001
0
        errCode = PORT_GetError();
10002
0
        goto loser;
10003
0
    }
10004
10005
75.7k
    rv = ssl3_SelectServerCert(ss);
10006
75.7k
    if (rv != SECSuccess) {
10007
132
        errCode = PORT_GetError();
10008
132
        desc = handshake_failure;
10009
132
        goto alert_loser;
10010
132
    }
10011
10012
75.6k
    sid = ssl3_NewSessionID(ss, PR_TRUE);
10013
75.6k
    if (sid == NULL) {
10014
0
        errCode = PORT_GetError();
10015
0
        goto loser; /* memory error is set. */
10016
0
    }
10017
75.6k
    ssl_SetSocketSID(ss, sid);
10018
10019
75.6k
    sid->u.ssl3.keys.extendedMasterSecretUsed =
10020
75.6k
        ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
10021
75.6k
    ss->ssl3.hs.isResuming = PR_FALSE;
10022
10023
75.6k
    ssl_GetXmitBufLock(ss);
10024
75.6k
    rv = ssl3_SendServerHelloSequence(ss);
10025
75.6k
    ssl_ReleaseXmitBufLock(ss);
10026
75.6k
    if (rv != SECSuccess) {
10027
183
        errCode = PORT_GetError();
10028
183
        desc = handshake_failure;
10029
183
        goto alert_loser;
10030
183
    }
10031
10032
75.4k
    return SECSuccess;
10033
10034
666
alert_loser:
10035
666
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
10036
/* FALLTHRU */
10037
666
loser:
10038
666
    if (sid && sid != ss->sec.ci.sid) {
10039
11
        ssl_UncacheSessionID(ss);
10040
11
        ssl_FreeSID(sid);
10041
11
    }
10042
10043
666
    if (haveXmitBufLock) {
10044
0
        ssl_ReleaseXmitBufLock(ss);
10045
0
    }
10046
10047
666
    PORT_SetError(errCode);
10048
666
    return SECFailure;
10049
666
}
10050
10051
/*
10052
 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
10053
 * in asking to use the V3 handshake.
10054
 */
10055
SECStatus
10056
ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, unsigned int length,
10057
                         PRUint8 padding)
10058
0
{
10059
0
    sslSessionID *sid = NULL;
10060
0
    unsigned char *suites;
10061
0
    unsigned char *random;
10062
0
    SSL3ProtocolVersion version;
10063
0
    SECStatus rv;
10064
0
    unsigned int i;
10065
0
    unsigned int j;
10066
0
    unsigned int sid_length;
10067
0
    unsigned int suite_length;
10068
0
    unsigned int rand_length;
10069
0
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
10070
0
    SSL3AlertDescription desc = handshake_failure;
10071
0
    unsigned int total = SSL_HL_CLIENT_HELLO_HBYTES;
10072
10073
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
10074
10075
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10076
10077
0
    ssl_GetSSL3HandshakeLock(ss);
10078
10079
0
    version = (buffer[1] << 8) | buffer[2];
10080
0
    if (version < SSL_LIBRARY_VERSION_3_0) {
10081
0
        goto loser;
10082
0
    }
10083
10084
0
    ssl3_RestartHandshakeHashes(ss);
10085
10086
0
    if (ss->ssl3.hs.ws != wait_client_hello) {
10087
0
        desc = unexpected_message;
10088
0
        errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
10089
0
        goto alert_loser;
10090
0
    }
10091
10092
0
    total += suite_length = (buffer[3] << 8) | buffer[4];
10093
0
    total += sid_length = (buffer[5] << 8) | buffer[6];
10094
0
    total += rand_length = (buffer[7] << 8) | buffer[8];
10095
0
    total += padding;
10096
0
    ss->clientHelloVersion = version;
10097
10098
0
    if (version >= SSL_LIBRARY_VERSION_TLS_1_3) {
10099
        /* [draft-ietf-tls-tls-11; C.3] forbids sending a TLS 1.3
10100
         * ClientHello using the backwards-compatible format. */
10101
0
        desc = illegal_parameter;
10102
0
        errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
10103
0
        goto alert_loser;
10104
0
    }
10105
10106
0
    rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
10107
0
    if (rv != SECSuccess) {
10108
        /* send back which ever alert client will understand. */
10109
0
        desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
10110
0
                                                   : handshake_failure;
10111
0
        errCode = SSL_ERROR_UNSUPPORTED_VERSION;
10112
0
        goto alert_loser;
10113
0
    }
10114
    /* ECH not possible here. */
10115
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
10116
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
10117
0
    if (!ss->firstHsDone) {
10118
0
        ssl_GetSpecWriteLock(ss);
10119
0
        ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
10120
0
        ssl_ReleaseSpecWriteLock(ss);
10121
0
    }
10122
10123
    /* if we get a non-zero SID, just ignore it. */
10124
0
    if (length != total) {
10125
0
        SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
10126
0
                 SSL_GETPID(), ss->fd, length, total));
10127
0
        desc = illegal_parameter;
10128
0
        errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
10129
0
        goto alert_loser;
10130
0
    }
10131
10132
0
    suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
10133
0
    random = suites + suite_length + sid_length;
10134
10135
0
    if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
10136
0
        rand_length > SSL_MAX_CHALLENGE_BYTES) {
10137
0
        desc = illegal_parameter;
10138
0
        errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
10139
0
        goto alert_loser;
10140
0
    }
10141
10142
0
    PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
10143
10144
0
    PORT_Memset(ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
10145
0
    PORT_Memcpy(&ss->ssl3.hs.client_random[SSL3_RANDOM_LENGTH - rand_length],
10146
0
                random, rand_length);
10147
10148
0
    PRINT_BUF(60, (ss, "client random:", ss->ssl3.hs.client_random,
10149
0
                   SSL3_RANDOM_LENGTH));
10150
10151
0
    if (ssl3_config_match_init(ss) == 0) {
10152
0
        errCode = PORT_GetError(); /* error code is already set. */
10153
0
        goto alert_loser;
10154
0
    }
10155
10156
    /* Select a cipher suite.
10157
    **
10158
    ** NOTE: This suite selection algorithm should be the same as the one in
10159
    ** ssl3_HandleClientHello().
10160
    */
10161
0
    for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
10162
0
        ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
10163
0
        SSLVersionRange vrange = { ss->version, ss->version };
10164
0
        if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
10165
0
            continue;
10166
0
        }
10167
0
        for (i = 0; i + 2 < suite_length; i += 3) {
10168
0
            PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
10169
0
            if (suite_i == suite->cipher_suite) {
10170
0
                ss->ssl3.hs.cipher_suite = suite_i;
10171
0
                rv = ssl3_SetupCipherSuite(ss, PR_TRUE);
10172
0
                if (rv != SECSuccess) {
10173
0
                    desc = internal_error;
10174
0
                    errCode = PORT_GetError();
10175
0
                    goto alert_loser;
10176
0
                }
10177
0
                goto suite_found;
10178
0
            }
10179
0
        }
10180
0
    }
10181
0
    errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
10182
0
    goto alert_loser;
10183
10184
0
suite_found:
10185
10186
    /* If the ClientHello version is less than our maximum version, check for a
10187
     * TLS_FALLBACK_SCSV and reject the connection if found. */
10188
0
    if (ss->vrange.max > ss->clientHelloVersion) {
10189
0
        for (i = 0; i + 2 < suite_length; i += 3) {
10190
0
            PRUint16 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
10191
0
            if (suite_i == TLS_FALLBACK_SCSV) {
10192
0
                desc = inappropriate_fallback;
10193
0
                errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
10194
0
                goto alert_loser;
10195
0
            }
10196
0
        }
10197
0
    }
10198
10199
    /* Look for the SCSV, and if found, treat it just like an empty RI
10200
     * extension by processing a local copy of an empty RI extension.
10201
     */
10202
0
    for (i = 0; i + 2 < suite_length; i += 3) {
10203
0
        PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
10204
0
        if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
10205
0
            PRUint8 *b2 = (PRUint8 *)emptyRIext;
10206
0
            PRUint32 L2 = sizeof emptyRIext;
10207
0
            (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
10208
0
            break;
10209
0
        }
10210
0
    }
10211
10212
0
    if (ss->opt.requireSafeNegotiation &&
10213
0
        !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
10214
0
        desc = handshake_failure;
10215
0
        errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
10216
0
        goto alert_loser;
10217
0
    }
10218
10219
0
    rv = ssl3_SelectServerCert(ss);
10220
0
    if (rv != SECSuccess) {
10221
0
        errCode = PORT_GetError();
10222
0
        desc = handshake_failure;
10223
0
        goto alert_loser;
10224
0
    }
10225
10226
    /* we don't even search for a cache hit here.  It's just a miss. */
10227
0
    SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
10228
0
    sid = ssl3_NewSessionID(ss, PR_TRUE);
10229
0
    if (sid == NULL) {
10230
0
        errCode = PORT_GetError();
10231
0
        goto loser; /* memory error is set. */
10232
0
    }
10233
0
    ssl_SetSocketSID(ss, sid);
10234
    /* do not worry about memory leak of sid since it now belongs to ci */
10235
10236
    /* We have to update the handshake hashes before we can send stuff */
10237
0
    rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
10238
0
    if (rv != SECSuccess) {
10239
0
        errCode = PORT_GetError();
10240
0
        goto loser;
10241
0
    }
10242
10243
0
    ssl_GetXmitBufLock(ss);
10244
0
    rv = ssl3_SendServerHelloSequence(ss);
10245
0
    ssl_ReleaseXmitBufLock(ss);
10246
0
    if (rv != SECSuccess) {
10247
0
        errCode = PORT_GetError();
10248
0
        goto loser;
10249
0
    }
10250
10251
0
    ssl_ReleaseSSL3HandshakeLock(ss);
10252
0
    return SECSuccess;
10253
10254
0
alert_loser:
10255
0
    SSL3_SendAlert(ss, alert_fatal, desc);
10256
0
loser:
10257
0
    ssl_ReleaseSSL3HandshakeLock(ss);
10258
0
    PORT_SetError(errCode);
10259
0
    return SECFailure;
10260
0
}
10261
10262
SECStatus
10263
ssl_ConstructServerHello(sslSocket *ss, PRBool helloRetry,
10264
                         const sslBuffer *extensionBuf, sslBuffer *messageBuf)
10265
79.2k
{
10266
79.2k
    SECStatus rv;
10267
79.2k
    SSL3ProtocolVersion version;
10268
79.2k
    sslSessionID *sid = ss->sec.ci.sid;
10269
79.2k
    const PRUint8 *random;
10270
10271
79.2k
    version = PR_MIN(ss->version, SSL_LIBRARY_VERSION_TLS_1_2);
10272
79.2k
    if (IS_DTLS(ss)) {
10273
10.6k
        version = dtls_TLSVersionToDTLSVersion(version);
10274
10.6k
    }
10275
79.2k
    rv = sslBuffer_AppendNumber(messageBuf, version, 2);
10276
79.2k
    if (rv != SECSuccess) {
10277
0
        return SECFailure;
10278
0
    }
10279
10280
79.2k
    if (helloRetry) {
10281
931
        random = ssl_hello_retry_random;
10282
78.3k
    } else {
10283
78.3k
        rv = ssl_GenerateServerRandom(ss);
10284
78.3k
        if (rv != SECSuccess) {
10285
0
            return SECFailure;
10286
0
        }
10287
78.3k
        random = ss->ssl3.hs.server_random;
10288
78.3k
    }
10289
79.2k
    rv = sslBuffer_Append(messageBuf, random, SSL3_RANDOM_LENGTH);
10290
79.2k
    if (rv != SECSuccess) {
10291
0
        return SECFailure;
10292
0
    }
10293
10294
79.2k
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
10295
75.6k
        if (sid) {
10296
75.6k
            rv = sslBuffer_AppendVariable(messageBuf, sid->u.ssl3.sessionID,
10297
75.6k
                                          sid->u.ssl3.sessionIDLength, 1);
10298
75.6k
        } else {
10299
0
            rv = sslBuffer_AppendNumber(messageBuf, 0, 1);
10300
0
        }
10301
75.6k
    } else {
10302
3.64k
        rv = sslBuffer_AppendVariable(messageBuf, ss->ssl3.hs.fakeSid.data,
10303
3.64k
                                      ss->ssl3.hs.fakeSid.len, 1);
10304
3.64k
    }
10305
79.2k
    if (rv != SECSuccess) {
10306
0
        return SECFailure;
10307
0
    }
10308
10309
79.2k
    rv = sslBuffer_AppendNumber(messageBuf, ss->ssl3.hs.cipher_suite, 2);
10310
79.2k
    if (rv != SECSuccess) {
10311
0
        return SECFailure;
10312
0
    }
10313
79.2k
    rv = sslBuffer_AppendNumber(messageBuf, ssl_compression_null, 1);
10314
79.2k
    if (rv != SECSuccess) {
10315
0
        return SECFailure;
10316
0
    }
10317
79.2k
    if (SSL_BUFFER_LEN(extensionBuf)) {
10318
        /* Directly copy the extensions */
10319
21.3k
        rv = sslBuffer_AppendBufferVariable(messageBuf, extensionBuf, 2);
10320
21.3k
        if (rv != SECSuccess) {
10321
0
            return SECFailure;
10322
0
        }
10323
21.3k
    }
10324
10325
79.2k
    if (ss->xtnData.ech && ss->xtnData.ech->receivedInnerXtn) {
10326
        /* Signal ECH acceptance if we handled handled both CHOuter/CHInner (i.e.
10327
         * in shared mode), or if we received a CHInner in split/backend mode. */
10328
41
        if (ss->ssl3.hs.echAccepted || ss->opt.enableTls13BackendEch) {
10329
41
            if (helloRetry) {
10330
22
                return tls13_WriteServerEchHrrSignal(ss, SSL_BUFFER_BASE(messageBuf),
10331
22
                                                     SSL_BUFFER_LEN(messageBuf));
10332
22
            } else {
10333
19
                return tls13_WriteServerEchSignal(ss, SSL_BUFFER_BASE(messageBuf),
10334
19
                                                  SSL_BUFFER_LEN(messageBuf));
10335
19
            }
10336
41
        }
10337
41
    }
10338
79.2k
    return SECSuccess;
10339
79.2k
}
10340
10341
/* The negotiated version number has been already placed in ss->version.
10342
**
10343
** Called from:  ssl3_HandleClientHello                     (resuming session),
10344
**  ssl3_SendServerHelloSequence <- ssl3_HandleClientHello   (new session),
10345
**  ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
10346
*/
10347
SECStatus
10348
ssl3_SendServerHello(sslSocket *ss)
10349
78.3k
{
10350
78.3k
    SECStatus rv;
10351
78.3k
    sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
10352
78.3k
    sslBuffer messageBuf = SSL_BUFFER_EMPTY;
10353
10354
78.3k
    SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
10355
78.3k
                ss->fd));
10356
10357
78.3k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10358
78.3k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10359
10360
78.3k
    PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
10361
78.3k
    if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
10362
0
        PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
10363
0
        return SECFailure;
10364
0
    }
10365
10366
78.3k
    rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_server_hello);
10367
78.3k
    if (rv != SECSuccess) {
10368
0
        goto loser;
10369
0
    }
10370
10371
78.3k
    rv = ssl_ConstructServerHello(ss, PR_FALSE, &extensionBuf, &messageBuf);
10372
78.3k
    if (rv != SECSuccess) {
10373
0
        goto loser;
10374
0
    }
10375
10376
78.3k
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello,
10377
78.3k
                                    SSL_BUFFER_LEN(&messageBuf));
10378
78.3k
    if (rv != SECSuccess) {
10379
0
        goto loser; /* err set by AppendHandshake. */
10380
0
    }
10381
10382
78.3k
    rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&messageBuf),
10383
78.3k
                              SSL_BUFFER_LEN(&messageBuf));
10384
78.3k
    if (rv != SECSuccess) {
10385
0
        goto loser; /* err set by AppendHandshake. */
10386
0
    }
10387
10388
78.3k
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
10389
75.6k
        rv = ssl3_SetupBothPendingCipherSpecs(ss);
10390
75.6k
        if (rv != SECSuccess) {
10391
0
            goto loser; /* err set */
10392
0
        }
10393
75.6k
    }
10394
10395
78.3k
    sslBuffer_Clear(&extensionBuf);
10396
78.3k
    sslBuffer_Clear(&messageBuf);
10397
78.3k
    return SECSuccess;
10398
10399
0
loser:
10400
0
    sslBuffer_Clear(&extensionBuf);
10401
0
    sslBuffer_Clear(&messageBuf);
10402
0
    return SECFailure;
10403
78.3k
}
10404
10405
SECStatus
10406
ssl_CreateDHEKeyPair(const sslNamedGroupDef *groupDef,
10407
                     const ssl3DHParams *params,
10408
                     sslEphemeralKeyPair **keyPair)
10409
6.67k
{
10410
6.67k
    SECKEYDHParams dhParam;
10411
6.67k
    SECKEYPublicKey *pubKey = NULL;   /* Ephemeral DH key */
10412
6.67k
    SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */
10413
6.67k
    sslEphemeralKeyPair *pair;
10414
10415
6.67k
    dhParam.prime.data = params->prime.data;
10416
6.67k
    dhParam.prime.len = params->prime.len;
10417
6.67k
    dhParam.base.data = params->base.data;
10418
6.67k
    dhParam.base.len = params->base.len;
10419
10420
6.67k
    PRINT_BUF(60, (NULL, "Server DH p", dhParam.prime.data,
10421
6.67k
                   dhParam.prime.len));
10422
6.67k
    PRINT_BUF(60, (NULL, "Server DH g", dhParam.base.data,
10423
6.67k
                   dhParam.base.len));
10424
10425
    /* Generate ephemeral DH keypair */
10426
6.67k
    privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
10427
6.67k
    if (!privKey || !pubKey) {
10428
208
        ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
10429
208
        return SECFailure;
10430
208
    }
10431
10432
6.46k
    pair = ssl_NewEphemeralKeyPair(groupDef, privKey, pubKey);
10433
6.46k
    if (!pair) {
10434
0
        SECKEY_DestroyPrivateKey(privKey);
10435
0
        SECKEY_DestroyPublicKey(pubKey);
10436
10437
0
        return SECFailure;
10438
0
    }
10439
10440
6.46k
    *keyPair = pair;
10441
6.46k
    return SECSuccess;
10442
6.46k
}
10443
10444
static SECStatus
10445
ssl3_SendDHServerKeyExchange(sslSocket *ss)
10446
3.99k
{
10447
3.99k
    const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
10448
3.99k
    SECStatus rv = SECFailure;
10449
3.99k
    int length;
10450
3.99k
    SECItem signed_hash = { siBuffer, NULL, 0 };
10451
3.99k
    SSL3Hashes hashes;
10452
3.99k
    SSLHashType hashAlg;
10453
10454
3.99k
    const ssl3DHParams *params;
10455
3.99k
    sslEphemeralKeyPair *keyPair;
10456
3.99k
    SECKEYPublicKey *pubKey;
10457
3.99k
    SECKEYPrivateKey *certPrivateKey;
10458
3.99k
    const sslNamedGroupDef *groupDef;
10459
    /* Do this on the heap, this could be over 2k long. */
10460
3.99k
    sslBuffer dhBuf = SSL_BUFFER_EMPTY;
10461
10462
3.99k
    if (kea_def->kea != kea_dhe_dss && kea_def->kea != kea_dhe_rsa) {
10463
        /* TODO: Support DH_anon. It might be sufficient to drop the signature.
10464
                 See bug 1170510. */
10465
0
        PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
10466
0
        return SECFailure;
10467
0
    }
10468
10469
3.99k
    rv = ssl_SelectDHEGroup(ss, &groupDef);
10470
3.99k
    if (rv == SECFailure) {
10471
0
        PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
10472
0
        return SECFailure;
10473
0
    }
10474
3.99k
    ss->sec.keaGroup = groupDef;
10475
10476
3.99k
    params = ssl_GetDHEParams(groupDef);
10477
3.99k
    rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
10478
3.99k
    if (rv == SECFailure) {
10479
138
        ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
10480
138
        return SECFailure;
10481
138
    }
10482
3.85k
    PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs);
10483
10484
3.85k
    if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
10485
3.49k
        hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
10486
3.49k
    } else {
10487
        /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
10488
360
        hashAlg = ssl_hash_none;
10489
360
    }
10490
10491
3.85k
    pubKey = keyPair->keys->pubKey;
10492
3.85k
    PRINT_BUF(50, (ss, "DH public value:",
10493
3.85k
                   pubKey->u.dh.publicValue.data,
10494
3.85k
                   pubKey->u.dh.publicValue.len));
10495
3.85k
    rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
10496
3.85k
                               pubKey->u.dh.prime,
10497
3.85k
                               pubKey->u.dh.base,
10498
3.85k
                               pubKey->u.dh.publicValue,
10499
3.85k
                               PR_TRUE /* padY */);
10500
3.85k
    if (rv != SECSuccess) {
10501
0
        ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
10502
0
        goto loser;
10503
0
    }
10504
10505
3.85k
    certPrivateKey = ss->sec.serverCert->serverKeyPair->privKey;
10506
3.85k
    rv = ssl3_SignHashes(ss, &hashes, certPrivateKey, &signed_hash);
10507
3.85k
    if (rv != SECSuccess) {
10508
0
        goto loser; /* ssl3_SignHashes has set err. */
10509
0
    }
10510
10511
3.85k
    length = 2 + pubKey->u.dh.prime.len +
10512
3.85k
             2 + pubKey->u.dh.base.len +
10513
3.85k
             2 + pubKey->u.dh.prime.len +
10514
3.85k
             2 + signed_hash.len;
10515
10516
3.85k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
10517
3.49k
        length += 2;
10518
3.49k
    }
10519
10520
3.85k
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_key_exchange, length);
10521
3.85k
    if (rv != SECSuccess) {
10522
0
        goto loser; /* err set by AppendHandshake. */
10523
0
    }
10524
10525
3.85k
    rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.prime.data,
10526
3.85k
                                      pubKey->u.dh.prime.len, 2);
10527
3.85k
    if (rv != SECSuccess) {
10528
0
        goto loser; /* err set by AppendHandshake. */
10529
0
    }
10530
10531
3.85k
    rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.base.data,
10532
3.85k
                                      pubKey->u.dh.base.len, 2);
10533
3.85k
    if (rv != SECSuccess) {
10534
0
        goto loser; /* err set by AppendHandshake. */
10535
0
    }
10536
10537
3.85k
    rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE);
10538
3.85k
    if (rv != SECSuccess) {
10539
0
        goto loser; /* err set by AppendPaddedDHKeyShare. */
10540
0
    }
10541
3.85k
    rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
10542
3.85k
    if (rv != SECSuccess) {
10543
0
        goto loser; /* err set by AppendHandshake. */
10544
0
    }
10545
10546
3.85k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
10547
3.49k
        rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
10548
3.49k
        if (rv != SECSuccess) {
10549
0
            goto loser; /* err set by AppendHandshake. */
10550
0
        }
10551
3.49k
    }
10552
10553
3.85k
    rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
10554
3.85k
                                      signed_hash.len, 2);
10555
3.85k
    if (rv != SECSuccess) {
10556
0
        goto loser; /* err set by AppendHandshake. */
10557
0
    }
10558
10559
3.85k
    sslBuffer_Clear(&dhBuf);
10560
3.85k
    PORT_Free(signed_hash.data);
10561
3.85k
    return SECSuccess;
10562
10563
0
loser:
10564
0
    if (signed_hash.data)
10565
0
        PORT_Free(signed_hash.data);
10566
0
    sslBuffer_Clear(&dhBuf);
10567
0
    return SECFailure;
10568
3.85k
}
10569
10570
static SECStatus
10571
ssl3_SendServerKeyExchange(sslSocket *ss)
10572
28.2k
{
10573
28.2k
    const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
10574
10575
28.2k
    SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
10576
28.2k
                SSL_GETPID(), ss->fd));
10577
10578
28.2k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10579
28.2k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10580
10581
28.2k
    switch (kea_def->exchKeyType) {
10582
3.99k
        case ssl_kea_dh: {
10583
3.99k
            return ssl3_SendDHServerKeyExchange(ss);
10584
0
        }
10585
10586
24.2k
        case ssl_kea_ecdh: {
10587
24.2k
            return ssl3_SendECDHServerKeyExchange(ss);
10588
0
        }
10589
10590
0
        case ssl_kea_rsa:
10591
0
        case ssl_kea_null:
10592
0
        default:
10593
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10594
0
            break;
10595
28.2k
    }
10596
10597
0
    return SECFailure;
10598
28.2k
}
10599
10600
SECStatus
10601
ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint16 maxVersion, PRUint16 minVersion,
10602
                   PRBool forCert, PRBool grease, sslBuffer *buf)
10603
79.0k
{
10604
79.0k
    SSLSignatureScheme filtered[MAX_SIGNATURE_SCHEMES] = { 0 };
10605
79.0k
    unsigned int filteredCount = 0;
10606
10607
79.0k
    SECStatus rv = ssl3_FilterSigAlgs(ss, maxVersion, minVersion,
10608
79.0k
                                      PR_FALSE, forCert,
10609
79.0k
                                      PR_ARRAY_SIZE(filtered),
10610
79.0k
                                      filtered, &filteredCount);
10611
79.0k
    if (rv != SECSuccess) {
10612
0
        return SECFailure;
10613
0
    }
10614
79.0k
    return ssl3_EncodeFilteredSigAlgs(ss, filtered, filteredCount, grease, buf);
10615
79.0k
}
10616
10617
SECStatus
10618
ssl3_EncodeFilteredSigAlgs(const sslSocket *ss, const SSLSignatureScheme *schemes,
10619
                           PRUint32 numSchemes, PRBool grease, sslBuffer *buf)
10620
87.4k
{
10621
87.4k
    if (!numSchemes) {
10622
0
        PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
10623
0
        return SECFailure;
10624
0
    }
10625
10626
87.4k
    unsigned int lengthOffset;
10627
87.4k
    SECStatus rv;
10628
10629
87.4k
    rv = sslBuffer_Skip(buf, 2, &lengthOffset);
10630
87.4k
    if (rv != SECSuccess) {
10631
0
        return SECFailure;
10632
0
    }
10633
10634
1.37M
    for (unsigned int i = 0; i < numSchemes; ++i) {
10635
1.28M
        rv = sslBuffer_AppendNumber(buf, schemes[i], 2);
10636
1.28M
        if (rv != SECSuccess) {
10637
0
            return SECFailure;
10638
0
        }
10639
1.28M
    }
10640
10641
    /* GREASE SignatureAlgorithms:
10642
     * A client MAY select one or more GREASE signature algorithm values and
10643
     * advertise them in the "signature_algorithms" or
10644
     * "signature_algorithms_cert" extensions, if sent [RFC8701, Section 3.1].
10645
     *
10646
     * When sending a CertificateRequest in TLS 1.3, a server MAY behave as
10647
     * follows: [...] A server MAY select one or more GREASE signature
10648
     * algorithm values and advertise them in the "signature_algorithms" or
10649
     * "signature_algorithms_cert" extensions, if present
10650
     * [RFC8701, Section 4.1]. */
10651
87.4k
    if (grease &&
10652
27.6k
        ((!ss->sec.isServer && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) ||
10653
19.1k
         (ss->sec.isServer && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3))) {
10654
9.09k
        PRUint16 value;
10655
9.09k
        if (ss->sec.isServer) {
10656
651
            rv = tls13_RandomGreaseValue(&value);
10657
651
            if (rv != SECSuccess) {
10658
0
                return SECFailure;
10659
0
            }
10660
8.44k
        } else {
10661
8.44k
            value = ss->ssl3.hs.grease->idx[grease_sigalg];
10662
8.44k
        }
10663
9.09k
        rv = sslBuffer_AppendNumber(buf, value, 2);
10664
9.09k
        if (rv != SECSuccess) {
10665
0
            return SECFailure;
10666
0
        }
10667
9.09k
    }
10668
10669
87.4k
    return sslBuffer_InsertLength(buf, lengthOffset, 2);
10670
87.4k
}
10671
10672
/*
10673
 * In TLS 1.3 we are permitted to advertise support for PKCS#1
10674
 * schemes. This doesn't affect the signatures in TLS itself, just
10675
 * those on certificates. Not advertising PKCS#1 signatures creates a
10676
 * serious compatibility risk as it excludes many certificate chains
10677
 * that include PKCS#1. Hence, forCert is used to enable advertising
10678
 * PKCS#1 support. Note that we include these in signature_algorithms
10679
 * because we don't yet support signature_algorithms_cert. TLS 1.3
10680
 * requires that PKCS#1 schemes are placed last in the list if they
10681
 * are present. This sorting can be removed once we support
10682
 * signature_algorithms_cert.
10683
 */
10684
SECStatus
10685
ssl3_FilterSigAlgs(const sslSocket *ss, PRUint16 maxVersion, PRUint16 minVersion,
10686
                   PRBool disableRsae, PRBool forCert,
10687
                   unsigned int maxSchemes, SSLSignatureScheme *filteredSchemes,
10688
                   unsigned int *numFilteredSchemes)
10689
87.4k
{
10690
87.4k
    PORT_Assert(filteredSchemes);
10691
87.4k
    PORT_Assert(numFilteredSchemes);
10692
87.4k
    PORT_Assert(maxSchemes >= ss->ssl3.signatureSchemeCount);
10693
87.4k
    if (maxSchemes < ss->ssl3.signatureSchemeCount) {
10694
0
        return SECFailure;
10695
0
    }
10696
10697
87.4k
    *numFilteredSchemes = 0;
10698
87.4k
    PRBool allowUnsortedPkcs1 = forCert && minVersion < SSL_LIBRARY_VERSION_TLS_1_3;
10699
1.66M
    for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
10700
1.57M
        if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
10701
24.9k
            continue;
10702
24.9k
        }
10703
1.54M
        if (ssl_SignatureSchemeAccepted(maxVersion, minVersion,
10704
1.54M
                                        ss->ssl3.signatureSchemes[i],
10705
1.54M
                                        allowUnsortedPkcs1)) {
10706
1.27M
            filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
10707
1.27M
        }
10708
1.54M
    }
10709
87.4k
    if (forCert && !allowUnsortedPkcs1) {
10710
63.5k
        for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
10711
60.1k
            if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
10712
0
                continue;
10713
0
            }
10714
60.1k
            if (!ssl_SignatureSchemeAccepted(maxVersion, minVersion,
10715
60.1k
                                             ss->ssl3.signatureSchemes[i],
10716
60.1k
                                             PR_FALSE) &&
10717
26.7k
                ssl_SignatureSchemeAccepted(maxVersion, minVersion,
10718
26.7k
                                            ss->ssl3.signatureSchemes[i],
10719
26.7k
                                            PR_TRUE)) {
10720
13.3k
                filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
10721
13.3k
            }
10722
60.1k
        }
10723
3.34k
    }
10724
87.4k
    return SECSuccess;
10725
87.4k
}
10726
10727
static SECStatus
10728
ssl3_SendCertificateRequest(sslSocket *ss)
10729
25.6k
{
10730
25.6k
    PRBool isTLS12;
10731
25.6k
    const PRUint8 *certTypes;
10732
25.6k
    SECStatus rv;
10733
25.6k
    PRUint32 length;
10734
25.6k
    const SECItem *names;
10735
25.6k
    unsigned int calen;
10736
25.6k
    unsigned int nnames;
10737
25.6k
    const SECItem *name;
10738
25.6k
    unsigned int i;
10739
25.6k
    int certTypesLength;
10740
25.6k
    PRUint8 sigAlgs[2 + MAX_SIGNATURE_SCHEMES * 2];
10741
25.6k
    sslBuffer sigAlgsBuf = SSL_BUFFER(sigAlgs);
10742
10743
25.6k
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
10744
25.6k
                SSL_GETPID(), ss->fd));
10745
10746
25.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10747
25.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10748
10749
25.6k
    isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
10750
10751
25.6k
    rv = ssl_GetCertificateRequestCAs(ss, &calen, &names, &nnames);
10752
25.6k
    if (rv != SECSuccess) {
10753
0
        return rv;
10754
0
    }
10755
25.6k
    certTypes = certificate_types;
10756
25.6k
    certTypesLength = sizeof certificate_types;
10757
10758
25.6k
    length = 1 + certTypesLength + 2 + calen;
10759
25.6k
    if (isTLS12) {
10760
24.4k
        rv = ssl3_EncodeSigAlgs(ss, ss->version, ss->version, PR_TRUE /* forCert */,
10761
24.4k
                                PR_FALSE /* GREASE */, &sigAlgsBuf);
10762
24.4k
        if (rv != SECSuccess) {
10763
0
            return rv;
10764
0
        }
10765
24.4k
        length += SSL_BUFFER_LEN(&sigAlgsBuf);
10766
24.4k
    }
10767
10768
25.6k
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request, length);
10769
25.6k
    if (rv != SECSuccess) {
10770
0
        return rv; /* err set by AppendHandshake. */
10771
0
    }
10772
25.6k
    rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
10773
25.6k
    if (rv != SECSuccess) {
10774
0
        return rv; /* err set by AppendHandshake. */
10775
0
    }
10776
25.6k
    if (isTLS12) {
10777
24.4k
        rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&sigAlgsBuf),
10778
24.4k
                                  SSL_BUFFER_LEN(&sigAlgsBuf));
10779
24.4k
        if (rv != SECSuccess) {
10780
0
            return rv; /* err set by AppendHandshake. */
10781
0
        }
10782
24.4k
    }
10783
25.6k
    rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
10784
25.6k
    if (rv != SECSuccess) {
10785
0
        return rv; /* err set by AppendHandshake. */
10786
0
    }
10787
25.6k
    for (i = 0, name = names; i < nnames; i++, name++) {
10788
0
        rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
10789
0
        if (rv != SECSuccess) {
10790
0
            return rv; /* err set by AppendHandshake. */
10791
0
        }
10792
0
    }
10793
10794
25.6k
    return SECSuccess;
10795
25.6k
}
10796
10797
static SECStatus
10798
ssl3_SendServerHelloDone(sslSocket *ss)
10799
75.4k
{
10800
75.4k
    SECStatus rv;
10801
10802
75.4k
    SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
10803
75.4k
                SSL_GETPID(), ss->fd));
10804
10805
75.4k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10806
75.4k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10807
10808
75.4k
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello_done, 0);
10809
75.4k
    if (rv != SECSuccess) {
10810
0
        return rv; /* err set by AppendHandshake. */
10811
0
    }
10812
75.4k
    rv = ssl3_FlushHandshake(ss, 0);
10813
75.4k
    if (rv != SECSuccess) {
10814
7
        return rv; /* error code set by ssl3_FlushHandshake */
10815
7
    }
10816
75.4k
    return SECSuccess;
10817
75.4k
}
10818
10819
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10820
 * a complete ssl3 Certificate Verify message
10821
 * Caller must hold Handshake and RecvBuf locks.
10822
 */
10823
static SECStatus
10824
ssl3_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
10825
18.5k
{
10826
18.5k
    SECItem signed_hash = { siBuffer, NULL, 0 };
10827
18.5k
    SECStatus rv;
10828
18.5k
    int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
10829
18.5k
    SSL3AlertDescription desc = handshake_failure;
10830
18.5k
    PRBool isTLS;
10831
18.5k
    SSLSignatureScheme sigScheme;
10832
18.5k
    SSL3Hashes hashes;
10833
18.5k
    const PRUint8 *savedMsg = b;
10834
18.5k
    const PRUint32 savedLen = length;
10835
10836
18.5k
    SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
10837
18.5k
                SSL_GETPID(), ss->fd));
10838
18.5k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10839
18.5k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10840
10841
18.5k
    if (ss->ssl3.hs.ws != wait_cert_verify) {
10842
21
        desc = unexpected_message;
10843
21
        errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
10844
21
        goto alert_loser;
10845
21
    }
10846
10847
    /* TLS 1.3 is handled by tls13_HandleCertificateVerify */
10848
18.5k
    PORT_Assert(ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2);
10849
10850
18.5k
    if (ss->ssl3.prSpec->version == SSL_LIBRARY_VERSION_TLS_1_2) {
10851
18.1k
        PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_record);
10852
18.1k
        rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
10853
18.1k
        if (rv != SECSuccess) {
10854
10
            if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
10855
4
                errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
10856
4
            }
10857
10
            goto loser; /* alert already sent */
10858
10
        }
10859
18.1k
        rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme,
10860
18.1k
                                                 ss->sec.peerCertSPKI);
10861
18.1k
        if (rv != SECSuccess) {
10862
40
            errCode = PORT_GetError();
10863
40
            desc = illegal_parameter;
10864
40
            goto alert_loser;
10865
40
        }
10866
10867
18.1k
        rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
10868
18.1k
                                       ss->ssl3.hs.messages.len,
10869
18.1k
                                       ssl_SignatureSchemeToHashType(sigScheme),
10870
18.1k
                                       &hashes);
10871
18.1k
    } else {
10872
397
        PORT_Assert(ss->ssl3.hs.hashType != handshake_hash_record);
10873
397
        sigScheme = ssl_sig_none;
10874
397
        rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.prSpec, &hashes, 0);
10875
397
    }
10876
10877
18.5k
    if (rv != SECSuccess) {
10878
0
        errCode = SSL_ERROR_DIGEST_FAILURE;
10879
0
        desc = decrypt_error;
10880
0
        goto alert_loser;
10881
0
    }
10882
10883
18.5k
    rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
10884
18.5k
    if (rv != SECSuccess) {
10885
62
        goto loser; /* malformed. */
10886
62
    }
10887
10888
18.4k
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
10889
10890
    /* XXX verify that the key & kea match */
10891
18.4k
    rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signed_hash);
10892
18.4k
    if (rv != SECSuccess) {
10893
2.98k
        errCode = PORT_GetError();
10894
2.98k
        desc = isTLS ? decrypt_error : handshake_failure;
10895
2.98k
        goto alert_loser;
10896
2.98k
    }
10897
10898
15.4k
    signed_hash.data = NULL;
10899
10900
15.4k
    if (length != 0) {
10901
208
        desc = isTLS ? decode_error : illegal_parameter;
10902
208
        goto alert_loser; /* malformed */
10903
208
    }
10904
10905
15.2k
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify,
10906
15.2k
                                  savedMsg, savedLen);
10907
15.2k
    if (rv != SECSuccess) {
10908
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10909
0
        return rv;
10910
0
    }
10911
10912
15.2k
    ss->ssl3.hs.ws = wait_change_cipher;
10913
15.2k
    return SECSuccess;
10914
10915
3.25k
alert_loser:
10916
3.25k
    SSL3_SendAlert(ss, alert_fatal, desc);
10917
3.32k
loser:
10918
3.32k
    PORT_SetError(errCode);
10919
3.32k
    return SECFailure;
10920
3.25k
}
10921
10922
/* find a slot that is able to generate a PMS and wrap it with RSA.
10923
 * Then generate and return the PMS.
10924
 * If the serverKeySlot parameter is non-null, this function will use
10925
 * that slot to do the job, otherwise it will find a slot.
10926
 *
10927
 * Called from  ssl3_DeriveConnectionKeys()  (above)
10928
 *      ssl3_SendRSAClientKeyExchange()     (above)
10929
 *      ssl3_HandleRSAClientKeyExchange()  (below)
10930
 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
10931
 */
10932
static PK11SymKey *
10933
ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
10934
                    PK11SlotInfo *serverKeySlot)
10935
59.0k
{
10936
59.0k
    PK11SymKey *pms = NULL;
10937
59.0k
    PK11SlotInfo *slot = serverKeySlot;
10938
59.0k
    void *pwArg = ss->pkcs11PinArg;
10939
59.0k
    SECItem param;
10940
59.0k
    CK_VERSION version;
10941
59.0k
    CK_MECHANISM_TYPE mechanism_array[3];
10942
10943
59.0k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10944
10945
59.0k
    if (slot == NULL) {
10946
15.1k
        SSLCipherAlgorithm calg;
10947
        /* The specReadLock would suffice here, but we cannot assert on
10948
        ** read locks.  Also, all the callers who call with a non-null
10949
        ** slot already hold the SpecWriteLock.
10950
        */
10951
15.1k
        PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
10952
15.1k
        PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
10953
10954
15.1k
        calg = spec->cipherDef->calg;
10955
10956
        /* First get an appropriate slot.  */
10957
15.1k
        mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
10958
15.1k
        mechanism_array[1] = CKM_RSA_PKCS;
10959
15.1k
        mechanism_array[2] = ssl3_Alg2Mech(calg);
10960
10961
15.1k
        slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
10962
15.1k
        if (slot == NULL) {
10963
            /* can't find a slot with all three, find a slot with the minimum */
10964
2.77k
            slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
10965
2.77k
            if (slot == NULL) {
10966
0
                PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
10967
0
                return pms; /* which is NULL */
10968
0
            }
10969
2.77k
        }
10970
15.1k
    }
10971
10972
    /* Generate the pre-master secret ...  */
10973
59.0k
    if (IS_DTLS(ss)) {
10974
5.94k
        SSL3ProtocolVersion temp;
10975
10976
5.94k
        temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
10977
5.94k
        version.major = MSB(temp);
10978
5.94k
        version.minor = LSB(temp);
10979
53.1k
    } else {
10980
53.1k
        version.major = MSB(ss->clientHelloVersion);
10981
53.1k
        version.minor = LSB(ss->clientHelloVersion);
10982
53.1k
    }
10983
10984
59.0k
    param.data = (unsigned char *)&version;
10985
59.0k
    param.len = sizeof version;
10986
10987
59.0k
    pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
10988
59.0k
    if (!serverKeySlot)
10989
15.1k
        PK11_FreeSlot(slot);
10990
59.0k
    if (pms == NULL) {
10991
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10992
0
    }
10993
59.0k
    return pms;
10994
59.0k
}
10995
10996
static void
10997
ssl3_CSwapPK11SymKey(PK11SymKey **x, PK11SymKey **y, PRBool c)
10998
87.9k
{
10999
87.9k
    uintptr_t mask = (uintptr_t)c;
11000
87.9k
    unsigned int i;
11001
615k
    for (i = 1; i < sizeof(uintptr_t) * 8; i <<= 1) {
11002
527k
        mask |= mask << i;
11003
527k
    }
11004
87.9k
    uintptr_t x_ptr = (uintptr_t)*x;
11005
87.9k
    uintptr_t y_ptr = (uintptr_t)*y;
11006
87.9k
    uintptr_t tmp = (x_ptr ^ y_ptr) & mask;
11007
87.9k
    x_ptr = x_ptr ^ tmp;
11008
87.9k
    y_ptr = y_ptr ^ tmp;
11009
87.9k
    *x = (PK11SymKey *)x_ptr;
11010
87.9k
    *y = (PK11SymKey *)y_ptr;
11011
87.9k
}
11012
11013
/* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
11014
 * return any indication of failure of the Client Key Exchange message,
11015
 * where that failure is caused by the content of the client's message.
11016
 * This function must not return SECFailure for any reason that is directly
11017
 * or indirectly caused by the content of the client's encrypted PMS.
11018
 * We must not send an alert and also not drop the connection.
11019
 * Instead, we generate a random PMS.  This will cause a failure
11020
 * in the processing the finished message, which is exactly where
11021
 * the failure must occur.
11022
 *
11023
 * Called from ssl3_HandleClientKeyExchange
11024
 */
11025
static SECStatus
11026
ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
11027
                                PRUint8 *b,
11028
                                PRUint32 length,
11029
                                sslKeyPair *serverKeyPair)
11030
44.0k
{
11031
44.0k
    SECStatus rv;
11032
44.0k
    SECItem enc_pms;
11033
44.0k
    PK11SymKey *pms = NULL;
11034
44.0k
    PK11SymKey *fauxPms = NULL;
11035
44.0k
    PK11SlotInfo *slot = NULL;
11036
11037
44.0k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11038
44.0k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11039
44.0k
    PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
11040
11041
44.0k
    enc_pms.data = b;
11042
44.0k
    enc_pms.len = length;
11043
11044
44.0k
    if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
11045
44.0k
        PRUint32 kLen;
11046
44.0k
        rv = ssl3_ConsumeHandshakeNumber(ss, &kLen, 2, &enc_pms.data, &enc_pms.len);
11047
44.0k
        if (rv != SECSuccess) {
11048
16
            PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
11049
16
            return SECFailure;
11050
16
        }
11051
43.9k
        if ((unsigned)kLen < enc_pms.len) {
11052
17.8k
            enc_pms.len = kLen;
11053
17.8k
        }
11054
43.9k
    }
11055
11056
    /*
11057
     * Get as close to algorithm 2 from RFC 5246; Section 7.4.7.1
11058
     * as we can within the constraints of the PKCS#11 interface.
11059
     *
11060
     * 1. Unconditionally generate a bogus PMS (what RFC 5246
11061
     *    calls R).
11062
     * 2. Attempt the RSA decryption to recover the PMS (what
11063
     *    RFC 5246 calls M).
11064
     * 3. Set PMS = (M == NULL) ? R : M
11065
     * 4. Use ssl3_ComputeMasterSecret(PMS) to attempt to derive
11066
     *    the MS from PMS. This includes performing the version
11067
     *    check and length check.
11068
     * 5. If either the initial RSA decryption failed or
11069
     *    ssl3_ComputeMasterSecret(PMS) failed, then discard
11070
     *    M and set PMS = R. Else, discard R and set PMS = M.
11071
     *
11072
     * We do two derivations here because we can't rely on having
11073
     * a function that only performs the PMS version and length
11074
     * check. The only redundant cost is that this runs the PRF,
11075
     * which isn't necessary here.
11076
     */
11077
11078
    /* Generate the bogus PMS (R) */
11079
43.9k
    slot = PK11_GetSlotFromPrivateKey(serverKeyPair->privKey);
11080
43.9k
    if (!slot) {
11081
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11082
0
        return SECFailure;
11083
0
    }
11084
11085
43.9k
    if (!PK11_DoesMechanism(slot, CKM_SSL3_MASTER_KEY_DERIVE)) {
11086
0
        PK11_FreeSlot(slot);
11087
0
        slot = PK11_GetBestSlot(CKM_SSL3_MASTER_KEY_DERIVE, NULL);
11088
0
        if (!slot) {
11089
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11090
0
            return SECFailure;
11091
0
        }
11092
0
    }
11093
11094
43.9k
    ssl_GetSpecWriteLock(ss);
11095
43.9k
    fauxPms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
11096
43.9k
    ssl_ReleaseSpecWriteLock(ss);
11097
43.9k
    PK11_FreeSlot(slot);
11098
11099
43.9k
    if (fauxPms == NULL) {
11100
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
11101
0
        return SECFailure;
11102
0
    }
11103
11104
    /*
11105
     * unwrap pms out of the incoming buffer
11106
     * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
11107
     *  the unwrap.  Rather, it is the mechanism with which the
11108
     *      unwrapped pms will be used.
11109
     */
11110
43.9k
    pms = PK11_PubUnwrapSymKey(serverKeyPair->privKey, &enc_pms,
11111
43.9k
                               CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
11112
    /* Temporarily use the PMS if unwrapping the real PMS fails. */
11113
43.9k
    ssl3_CSwapPK11SymKey(&pms, &fauxPms, pms == NULL);
11114
11115
    /* Attempt to derive the MS from the PMS. This is the only way to
11116
     * check the version field in the RSA PMS. If this fails, we
11117
     * then use the faux PMS in place of the PMS. Note that this
11118
     * operation should never fail if we are using the faux PMS
11119
     * since it is correctly formatted. */
11120
43.9k
    rv = ssl3_ComputeMasterSecret(ss, pms, NULL);
11121
11122
    /* If we succeeded, then select the true PMS, else select the FPMS. */
11123
43.9k
    ssl3_CSwapPK11SymKey(&pms, &fauxPms, (rv != SECSuccess) & (fauxPms != NULL));
11124
11125
    /* This step will derive the MS from the PMS, among other things. */
11126
43.9k
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
11127
11128
    /* Clear both PMS. */
11129
43.9k
    PK11_FreeSymKey(pms);
11130
43.9k
    PK11_FreeSymKey(fauxPms);
11131
11132
43.9k
    if (rv != SECSuccess) {
11133
202
        (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
11134
202
        return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
11135
202
    }
11136
11137
43.7k
    return SECSuccess;
11138
43.9k
}
11139
11140
static SECStatus
11141
ssl3_HandleDHClientKeyExchange(sslSocket *ss,
11142
                               PRUint8 *b,
11143
                               PRUint32 length,
11144
                               sslKeyPair *serverKeyPair)
11145
3.12k
{
11146
3.12k
    PK11SymKey *pms;
11147
3.12k
    SECStatus rv;
11148
3.12k
    SECKEYPublicKey clntPubKey;
11149
3.12k
    CK_MECHANISM_TYPE target;
11150
3.12k
    PRBool isTLS;
11151
11152
3.12k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11153
3.12k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11154
11155
3.12k
    clntPubKey.keyType = dhKey;
11156
3.12k
    clntPubKey.u.dh.prime.len = serverKeyPair->pubKey->u.dh.prime.len;
11157
3.12k
    clntPubKey.u.dh.prime.data = serverKeyPair->pubKey->u.dh.prime.data;
11158
3.12k
    clntPubKey.u.dh.base.len = serverKeyPair->pubKey->u.dh.base.len;
11159
3.12k
    clntPubKey.u.dh.base.data = serverKeyPair->pubKey->u.dh.base.data;
11160
11161
3.12k
    rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.dh.publicValue,
11162
3.12k
                                       2, &b, &length);
11163
3.12k
    if (rv != SECSuccess) {
11164
42
        return SECFailure;
11165
42
    }
11166
11167
3.08k
    if (!ssl_IsValidDHEShare(&serverKeyPair->pubKey->u.dh.prime,
11168
3.08k
                             &clntPubKey.u.dh.publicValue)) {
11169
60
        PORT_SetError(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE);
11170
60
        return SECFailure;
11171
60
    }
11172
11173
3.02k
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
11174
11175
3.02k
    if (isTLS)
11176
3.02k
        target = CKM_TLS_MASTER_KEY_DERIVE_DH;
11177
0
    else
11178
0
        target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
11179
11180
    /* Determine the PMS */
11181
3.02k
    pms = PK11_PubDerive(serverKeyPair->privKey, &clntPubKey, PR_FALSE, NULL, NULL,
11182
3.02k
                         CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
11183
3.02k
    if (pms == NULL) {
11184
0
        ssl_FreeEphemeralKeyPairs(ss);
11185
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
11186
0
        return SECFailure;
11187
0
    }
11188
11189
3.02k
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
11190
3.02k
    PK11_FreeSymKey(pms);
11191
3.02k
    ssl_FreeEphemeralKeyPairs(ss);
11192
3.02k
    return rv;
11193
3.02k
}
11194
11195
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11196
 * a complete ssl3 ClientKeyExchange message from the remote client
11197
 * Caller must hold Handshake and RecvBuf locks.
11198
 */
11199
static SECStatus
11200
ssl3_HandleClientKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
11201
68.6k
{
11202
68.6k
    sslKeyPair *serverKeyPair = NULL;
11203
68.6k
    SECStatus rv;
11204
68.6k
    const ssl3KEADef *kea_def;
11205
11206
68.6k
    SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
11207
68.6k
                SSL_GETPID(), ss->fd));
11208
11209
68.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11210
68.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11211
11212
68.6k
    if (ss->ssl3.hs.ws != wait_client_key) {
11213
63
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11214
63
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
11215
63
        return SECFailure;
11216
63
    }
11217
11218
68.6k
    kea_def = ss->ssl3.hs.kea_def;
11219
11220
68.6k
    if (kea_def->ephemeral) {
11221
24.4k
        sslEphemeralKeyPair *keyPair;
11222
        /* There should be exactly one pair. */
11223
24.4k
        PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
11224
24.4k
        PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==
11225
24.4k
                    PR_NEXT_LINK(&ss->ephemeralKeyPairs));
11226
24.4k
        keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs);
11227
24.4k
        serverKeyPair = keyPair->keys;
11228
24.4k
        ss->sec.keaKeyBits =
11229
24.4k
            SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
11230
44.1k
    } else {
11231
44.1k
        serverKeyPair = ss->sec.serverCert->serverKeyPair;
11232
44.1k
        ss->sec.keaKeyBits = ss->sec.serverCert->serverKeyBits;
11233
44.1k
    }
11234
11235
68.6k
    if (!serverKeyPair) {
11236
0
        SSL3_SendAlert(ss, alert_fatal, handshake_failure);
11237
0
        PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
11238
0
        return SECFailure;
11239
0
    }
11240
68.6k
    PORT_Assert(serverKeyPair->pubKey);
11241
68.6k
    PORT_Assert(serverKeyPair->privKey);
11242
11243
68.6k
    ss->sec.keaType = kea_def->exchKeyType;
11244
11245
68.6k
    switch (kea_def->exchKeyType) {
11246
44.0k
        case ssl_kea_rsa:
11247
44.0k
            rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKeyPair);
11248
44.0k
            break;
11249
11250
3.12k
        case ssl_kea_dh:
11251
3.12k
            rv = ssl3_HandleDHClientKeyExchange(ss, b, length, serverKeyPair);
11252
3.12k
            break;
11253
11254
21.4k
        case ssl_kea_ecdh:
11255
21.4k
            rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, serverKeyPair);
11256
21.4k
            break;
11257
11258
0
        default:
11259
0
            (void)ssl3_HandshakeFailure(ss);
11260
0
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
11261
0
            return SECFailure;
11262
68.6k
    }
11263
68.6k
    ssl_FreeEphemeralKeyPairs(ss);
11264
68.6k
    if (rv == SECSuccess) {
11265
67.6k
        ss->ssl3.hs.ws = ss->sec.peerCertDER.data ? wait_cert_verify
11266
67.6k
                                                  : wait_change_cipher;
11267
67.6k
    } else {
11268
        /* PORT_SetError has been called by all the Handle*ClientKeyExchange
11269
         * functions above.  However, not all error paths result in an alert, so
11270
         * this ensures that the server knows about the error.  Note that if an
11271
         * alert was already sent, SSL3_SendAlert() is a noop. */
11272
947
        PRErrorCode errCode = PORT_GetError();
11273
947
        (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
11274
947
        PORT_SetError(errCode);
11275
947
    }
11276
68.6k
    return rv;
11277
68.6k
}
11278
11279
/* This is TLS's equivalent of sending a no_certificate alert. */
11280
SECStatus
11281
ssl3_SendEmptyCertificate(sslSocket *ss)
11282
57
{
11283
57
    SECStatus rv;
11284
57
    unsigned int len = 0;
11285
57
    PRBool isTLS13 = PR_FALSE;
11286
57
    const SECItem *context;
11287
11288
57
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
11289
0
        PORT_Assert(ss->ssl3.hs.clientCertRequested);
11290
0
        context = &ss->xtnData.certReqContext;
11291
0
        len = context->len + 1;
11292
0
        isTLS13 = PR_TRUE;
11293
0
    }
11294
11295
57
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate, len + 3);
11296
57
    if (rv != SECSuccess) {
11297
0
        return rv;
11298
0
    }
11299
11300
57
    if (isTLS13) {
11301
0
        rv = ssl3_AppendHandshakeVariable(ss, context->data, context->len, 1);
11302
0
        if (rv != SECSuccess) {
11303
0
            return rv;
11304
0
        }
11305
0
    }
11306
11307
57
    return ssl3_AppendHandshakeNumber(ss, 0, 3);
11308
57
}
11309
11310
/*
11311
 * NewSessionTicket
11312
 * Called from ssl3_HandleFinished
11313
 */
11314
static SECStatus
11315
ssl3_SendNewSessionTicket(sslSocket *ss)
11316
2.91k
{
11317
2.91k
    SECItem ticket = { 0, NULL, 0 };
11318
2.91k
    SECStatus rv;
11319
2.91k
    NewSessionTicket nticket = { 0 };
11320
11321
2.91k
    rv = ssl3_EncodeSessionTicket(ss, &nticket, NULL, 0,
11322
2.91k
                                  ss->ssl3.pwSpec->masterSecret, &ticket);
11323
2.91k
    if (rv != SECSuccess)
11324
0
        goto loser;
11325
11326
    /* Serialize the handshake message. Length =
11327
     * lifetime (4) + ticket length (2) + ticket. */
11328
2.91k
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
11329
2.91k
                                    4 + 2 + ticket.len);
11330
2.91k
    if (rv != SECSuccess)
11331
0
        goto loser;
11332
11333
    /* This is a fixed value. */
11334
2.91k
    rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
11335
2.91k
    if (rv != SECSuccess)
11336
0
        goto loser;
11337
11338
    /* Encode the ticket. */
11339
2.91k
    rv = ssl3_AppendHandshakeVariable(ss, ticket.data, ticket.len, 2);
11340
2.91k
    if (rv != SECSuccess)
11341
0
        goto loser;
11342
11343
2.91k
    rv = SECSuccess;
11344
11345
2.91k
loser:
11346
2.91k
    if (ticket.data) {
11347
2.91k
        SECITEM_FreeItem(&ticket, PR_FALSE);
11348
2.91k
    }
11349
2.91k
    return rv;
11350
2.91k
}
11351
11352
static SECStatus
11353
ssl3_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
11354
120
{
11355
120
    SECStatus rv;
11356
120
    SECItem ticketData;
11357
120
    PRUint32 temp;
11358
11359
120
    SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
11360
120
                SSL_GETPID(), ss->fd));
11361
11362
120
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11363
120
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11364
11365
120
    if (ss->ssl3.hs.ws != wait_new_session_ticket) {
11366
27
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11367
27
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
11368
27
        return SECFailure;
11369
27
    }
11370
11371
93
    PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
11372
93
    PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket);
11373
11374
    /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid
11375
     * until it has verified the server's Finished message." See the comment in
11376
     * ssl3_FinishHandshake for more details.
11377
     */
11378
93
    ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(ss);
11379
93
    if (length < 4) {
11380
5
        (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
11381
5
        PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
11382
5
        return SECFailure;
11383
5
    }
11384
11385
88
    rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 4, &b, &length);
11386
88
    if (rv != SECSuccess) {
11387
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
11388
0
        return SECFailure;
11389
0
    }
11390
88
    ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = temp;
11391
11392
88
    rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length);
11393
88
    if (rv != SECSuccess || length != 0) {
11394
75
        (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
11395
75
        PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
11396
75
        return SECFailure; /* malformed */
11397
75
    }
11398
    /* If the server sent a zero-length ticket, ignore it and keep the
11399
     * existing ticket. */
11400
13
    if (ticketData.len != 0) {
11401
8
        rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket,
11402
8
                              &ticketData);
11403
8
        if (rv != SECSuccess) {
11404
0
            return rv;
11405
0
        }
11406
8
        ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE;
11407
8
    }
11408
11409
13
    ss->ssl3.hs.ws = wait_change_cipher;
11410
13
    return SECSuccess;
11411
13
}
11412
11413
#ifdef NISCC_TEST
11414
static PRInt32 connNum = 0;
11415
11416
static SECStatus
11417
get_fake_cert(SECItem *pCertItem, int *pIndex)
11418
{
11419
    PRFileDesc *cf;
11420
    char *testdir;
11421
    char *startat;
11422
    char *stopat;
11423
    const char *extension;
11424
    int fileNum;
11425
    PRInt32 numBytes = 0;
11426
    PRStatus prStatus;
11427
    PRFileInfo info;
11428
    char cfn[100];
11429
11430
    pCertItem->data = 0;
11431
    if ((testdir = PR_GetEnvSecure("NISCC_TEST")) == NULL) {
11432
        return SECSuccess;
11433
    }
11434
    *pIndex = (NULL != strstr(testdir, "root"));
11435
    extension = (strstr(testdir, "simple") ? "" : ".der");
11436
    fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1;
11437
    if ((startat = PR_GetEnvSecure("START_AT")) != NULL) {
11438
        fileNum += atoi(startat);
11439
    }
11440
    if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL &&
11441
        fileNum >= atoi(stopat)) {
11442
        *pIndex = -1;
11443
        return SECSuccess;
11444
    }
11445
    snprintf(cfn, sizeof(cfn), "%s/%08d%s", testdir, fileNum, extension);
11446
    cf = PR_Open(cfn, PR_RDONLY, 0);
11447
    if (!cf) {
11448
        goto loser;
11449
    }
11450
    prStatus = PR_GetOpenFileInfo(cf, &info);
11451
    if (prStatus != PR_SUCCESS) {
11452
        PR_Close(cf);
11453
        goto loser;
11454
    }
11455
    pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
11456
    if (pCertItem) {
11457
        numBytes = PR_Read(cf, pCertItem->data, info.size);
11458
    }
11459
    PR_Close(cf);
11460
    if (numBytes != info.size) {
11461
        SECITEM_FreeItem(pCertItem, PR_FALSE);
11462
        PORT_SetError(SEC_ERROR_IO);
11463
        goto loser;
11464
    }
11465
    fprintf(stderr, "using %s\n", cfn);
11466
    return SECSuccess;
11467
11468
loser:
11469
    fprintf(stderr, "failed to use %s\n", cfn);
11470
    *pIndex = -1;
11471
    return SECFailure;
11472
}
11473
#endif
11474
11475
/*
11476
 * Used by both client and server.
11477
 * Called from HandleServerHelloDone and from SendServerHelloSequence.
11478
 */
11479
static SECStatus
11480
ssl3_SendCertificate(sslSocket *ss)
11481
75.6k
{
11482
75.6k
    SECStatus rv;
11483
75.6k
    CERTCertificateList *certChain;
11484
75.6k
    int certChainLen = 0;
11485
75.6k
    int i;
11486
#ifdef NISCC_TEST
11487
    SECItem fakeCert;
11488
    int ndex = -1;
11489
#endif
11490
75.6k
    PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
11491
75.6k
    SECItem context = { siBuffer, NULL, 0 };
11492
75.6k
    unsigned int contextLen = 0;
11493
11494
75.6k
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
11495
75.6k
                SSL_GETPID(), ss->fd));
11496
11497
75.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11498
75.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11499
75.6k
    PR_ASSERT(!ss->ssl3.hs.clientCertificatePending);
11500
11501
75.6k
    if (ss->sec.localCert)
11502
55.7k
        CERT_DestroyCertificate(ss->sec.localCert);
11503
75.6k
    if (ss->sec.isServer) {
11504
        /* A server certificate is selected in ssl3_HandleClientHello. */
11505
75.6k
        PORT_Assert(ss->sec.serverCert);
11506
11507
75.6k
        certChain = ss->sec.serverCert->serverCertChain;
11508
75.6k
        ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
11509
75.6k
    } else {
11510
0
        certChain = ss->ssl3.clientCertChain;
11511
0
        ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
11512
0
    }
11513
11514
#ifdef NISCC_TEST
11515
    rv = get_fake_cert(&fakeCert, &ndex);
11516
#endif
11517
11518
75.6k
    if (isTLS13) {
11519
0
        contextLen = 1; /* Size of the context length */
11520
0
        if (!ss->sec.isServer) {
11521
0
            PORT_Assert(ss->ssl3.hs.clientCertRequested);
11522
0
            context = ss->xtnData.certReqContext;
11523
0
            contextLen += context.len;
11524
0
        }
11525
0
    }
11526
75.6k
    if (certChain) {
11527
151k
        for (i = 0; i < certChain->len; i++) {
11528
#ifdef NISCC_TEST
11529
            if (fakeCert.len > 0 && i == ndex) {
11530
                certChainLen += fakeCert.len + 3;
11531
            } else {
11532
                certChainLen += certChain->certs[i].len + 3;
11533
            }
11534
#else
11535
75.6k
            certChainLen += certChain->certs[i].len + 3;
11536
75.6k
#endif
11537
75.6k
        }
11538
75.6k
    }
11539
11540
75.6k
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate,
11541
75.6k
                                    contextLen + certChainLen + 3);
11542
75.6k
    if (rv != SECSuccess) {
11543
0
        return rv; /* err set by AppendHandshake. */
11544
0
    }
11545
11546
75.6k
    if (isTLS13) {
11547
0
        rv = ssl3_AppendHandshakeVariable(ss, context.data,
11548
0
                                          context.len, 1);
11549
0
        if (rv != SECSuccess) {
11550
0
            return rv; /* err set by AppendHandshake. */
11551
0
        }
11552
0
    }
11553
11554
75.6k
    rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3);
11555
75.6k
    if (rv != SECSuccess) {
11556
0
        return rv; /* err set by AppendHandshake. */
11557
0
    }
11558
75.6k
    if (certChain) {
11559
151k
        for (i = 0; i < certChain->len; i++) {
11560
#ifdef NISCC_TEST
11561
            if (fakeCert.len > 0 && i == ndex) {
11562
                rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
11563
                                                  fakeCert.len, 3);
11564
                SECITEM_FreeItem(&fakeCert, PR_FALSE);
11565
            } else {
11566
                rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
11567
                                                  certChain->certs[i].len, 3);
11568
            }
11569
#else
11570
75.6k
            rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
11571
75.6k
                                              certChain->certs[i].len, 3);
11572
75.6k
#endif
11573
75.6k
            if (rv != SECSuccess) {
11574
0
                return rv; /* err set by AppendHandshake. */
11575
0
            }
11576
75.6k
        }
11577
75.6k
    }
11578
11579
75.6k
    return SECSuccess;
11580
75.6k
}
11581
11582
/*
11583
 * Used by server only.
11584
 * single-stapling, send only a single cert status
11585
 */
11586
SECStatus
11587
ssl3_SendCertificateStatus(sslSocket *ss)
11588
75.6k
{
11589
75.6k
    SECStatus rv;
11590
75.6k
    int len = 0;
11591
75.6k
    SECItemArray *statusToSend = NULL;
11592
75.6k
    const sslServerCert *serverCert;
11593
11594
75.6k
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
11595
75.6k
                SSL_GETPID(), ss->fd));
11596
11597
75.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11598
75.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11599
75.6k
    PORT_Assert(ss->sec.isServer);
11600
11601
75.6k
    if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
11602
71.7k
        return SECSuccess;
11603
11604
    /* Use certStatus based on the cert being used. */
11605
3.85k
    serverCert = ss->sec.serverCert;
11606
3.85k
    if (serverCert->certStatusArray && serverCert->certStatusArray->len) {
11607
0
        statusToSend = serverCert->certStatusArray;
11608
0
    }
11609
3.85k
    if (!statusToSend)
11610
3.85k
        return SECSuccess;
11611
11612
    /* Use the array's first item only (single stapling) */
11613
0
    len = 1 + statusToSend->items[0].len + 3;
11614
11615
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_status, len);
11616
0
    if (rv != SECSuccess) {
11617
0
        return rv; /* err set by AppendHandshake. */
11618
0
    }
11619
0
    rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
11620
0
    if (rv != SECSuccess)
11621
0
        return rv; /* err set by AppendHandshake. */
11622
11623
0
    rv = ssl3_AppendHandshakeVariable(ss,
11624
0
                                      statusToSend->items[0].data,
11625
0
                                      statusToSend->items[0].len,
11626
0
                                      3);
11627
0
    if (rv != SECSuccess)
11628
0
        return rv; /* err set by AppendHandshake. */
11629
11630
0
    return SECSuccess;
11631
0
}
11632
11633
/* This is used to delete the CA certificates in the peer certificate chain
11634
 * from the cert database after they've been validated.
11635
 */
11636
void
11637
ssl3_CleanupPeerCerts(sslSocket *ss)
11638
116k
{
11639
116k
    PLArenaPool *arena = ss->ssl3.peerCertArena;
11640
11641
116k
    if (arena)
11642
81.6k
        PORT_FreeArena(arena, PR_FALSE);
11643
116k
    ss->ssl3.peerCertArena = NULL;
11644
116k
    ss->ssl3.peerCertChain = NULL;
11645
11646
116k
    if (ss->sec.peerCertDER.data != NULL) {
11647
50.1k
        if (ss->sec.peerKey) {
11648
0
            SECKEY_DestroyPublicKey(ss->sec.peerKey);
11649
0
            ss->sec.peerKey = NULL;
11650
0
        }
11651
50.1k
        ssl_ClearPeerCertificate(&ss->sec);
11652
50.1k
    }
11653
116k
}
11654
11655
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11656
 * a complete ssl3 CertificateStatus message.
11657
 * Caller must hold Handshake and RecvBuf locks.
11658
 */
11659
static SECStatus
11660
ssl3_HandleCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
11661
172
{
11662
172
    SECStatus rv;
11663
11664
172
    if (ss->ssl3.hs.ws != wait_certificate_status) {
11665
32
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11666
32
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
11667
32
        return SECFailure;
11668
32
    }
11669
11670
140
    rv = ssl_ReadCertificateStatus(ss, b, length);
11671
140
    if (rv != SECSuccess) {
11672
118
        return SECFailure; /* code already set */
11673
118
    }
11674
11675
22
    return ssl3_AuthCertificate(ss);
11676
140
}
11677
11678
SECStatus
11679
ssl_ReadCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
11680
140
{
11681
140
    PRUint32 status, len;
11682
140
    SECStatus rv;
11683
11684
140
    PORT_Assert(!ss->sec.isServer);
11685
11686
    /* Consume the CertificateStatusType enum */
11687
140
    rv = ssl3_ConsumeHandshakeNumber(ss, &status, 1, &b, &length);
11688
140
    if (rv != SECSuccess || status != 1 /* ocsp */) {
11689
14
        return ssl3_DecodeError(ss);
11690
14
    }
11691
11692
126
    rv = ssl3_ConsumeHandshakeNumber(ss, &len, 3, &b, &length);
11693
126
    if (rv != SECSuccess || len != length) {
11694
104
        return ssl3_DecodeError(ss);
11695
104
    }
11696
11697
22
#define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */
11698
22
    if (length > MAX_CERTSTATUS_LEN) {
11699
0
        ssl3_DecodeError(ss); /* sets error code */
11700
0
        return SECFailure;
11701
0
    }
11702
22
#undef MAX_CERTSTATUS_LEN
11703
11704
    /* Array size 1, because we currently implement single-stapling only */
11705
22
    SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
11706
22
    if (!ss->sec.ci.sid->peerCertStatus.items)
11707
0
        return SECFailure; /* code already set */
11708
11709
22
    ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
11710
11711
22
    if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
11712
0
        SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
11713
0
        return SECFailure; /* code already set */
11714
0
    }
11715
11716
22
    PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
11717
22
    ss->sec.ci.sid->peerCertStatus.items[0].len = length;
11718
22
    ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
11719
22
    return SECSuccess;
11720
22
}
11721
11722
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11723
 * a complete ssl3 Certificate message.
11724
 * Caller must hold Handshake and RecvBuf locks.
11725
 */
11726
static SECStatus
11727
ssl3_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
11728
83.5k
{
11729
83.5k
    SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
11730
83.5k
                SSL_GETPID(), ss->fd));
11731
83.5k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11732
83.5k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11733
11734
83.5k
    if ((ss->sec.isServer && ss->ssl3.hs.ws != wait_client_cert) ||
11735
83.4k
        (!ss->sec.isServer && ss->ssl3.hs.ws != wait_server_cert)) {
11736
92
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11737
92
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE);
11738
92
        return SECFailure;
11739
92
    }
11740
11741
83.4k
    if (ss->sec.isServer) {
11742
24.1k
        dtls_ReceivedFirstMessageInFlight(ss);
11743
24.1k
    }
11744
11745
83.4k
    return ssl3_CompleteHandleCertificate(ss, b, length);
11746
83.5k
}
11747
11748
/* Called from ssl3_HandleCertificate
11749
 */
11750
SECStatus
11751
ssl3_CompleteHandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
11752
83.4k
{
11753
83.4k
    ssl3CertNode *c;
11754
83.4k
    ssl3CertNode *lastCert = NULL;
11755
83.4k
    PRUint32 remaining = 0;
11756
83.4k
    PRUint32 size;
11757
83.4k
    SECStatus rv;
11758
83.4k
    PRBool isServer = ss->sec.isServer;
11759
83.4k
    PRBool isTLS;
11760
83.4k
    SSL3AlertDescription desc;
11761
83.4k
    int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
11762
83.4k
    SECItem certItem;
11763
11764
83.4k
    ssl3_CleanupPeerCerts(ss);
11765
83.4k
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
11766
11767
    /* It is reported that some TLS client sends a Certificate message
11768
    ** with a zero-length message body.  We'll treat that case like a
11769
    ** normal no_certificates message to maximize interoperability.
11770
    */
11771
83.4k
    if (length) {
11772
83.2k
        rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 3, &b, &length);
11773
83.2k
        if (rv != SECSuccess)
11774
11
            goto loser; /* fatal alert already sent by ConsumeHandshake. */
11775
83.2k
        if (remaining > length)
11776
289
            goto decode_loser;
11777
83.2k
    }
11778
11779
83.1k
    if (!remaining) {
11780
1.47k
        if (!(isTLS && isServer)) {
11781
9
            desc = bad_certificate;
11782
9
            goto alert_loser;
11783
9
        }
11784
        /* This is TLS's version of a no_certificate alert. */
11785
        /* I'm a server. I've requested a client cert. He hasn't got one. */
11786
1.46k
        rv = ssl3_HandleNoCertificate(ss);
11787
1.46k
        if (rv != SECSuccess) {
11788
10
            errCode = PORT_GetError();
11789
10
            goto loser;
11790
10
        }
11791
11792
1.45k
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11793
1.45k
            ss->ssl3.hs.ws = wait_client_key;
11794
1.45k
        } else {
11795
0
            TLS13_SET_HS_STATE(ss, wait_finished);
11796
0
        }
11797
1.45k
        return SECSuccess;
11798
1.46k
    }
11799
11800
81.6k
    ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
11801
81.6k
    if (ss->ssl3.peerCertArena == NULL) {
11802
0
        goto loser; /* don't send alerts on memory errors */
11803
0
    }
11804
11805
    /* First get the peer cert. */
11806
81.6k
    if (remaining < 3)
11807
12
        goto decode_loser;
11808
11809
81.6k
    remaining -= 3;
11810
81.6k
    rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
11811
81.6k
    if (rv != SECSuccess)
11812
0
        goto loser; /* fatal alert already sent by ConsumeHandshake. */
11813
81.6k
    if (size == 0 || remaining < size)
11814
199
        goto decode_loser;
11815
11816
81.4k
    certItem.data = b;
11817
81.4k
    certItem.len = size;
11818
81.4k
    b += size;
11819
81.4k
    length -= size;
11820
81.4k
    remaining -= size;
11821
11822
    /* This keeps the DER and the subjectPublicKeyInfo parsed out of it;
11823
     * nothing is added to any certificate database.  We should report an alert
11824
     * if the cert was bad, but not if the problem was just some local problem,
11825
     * like memory error.
11826
     */
11827
81.4k
    if (ssl_SetPeerCertificate(&ss->sec, &certItem) != SECSuccess) {
11828
1.03k
        goto ambiguous_err;
11829
1.03k
    }
11830
11831
    /* Now get all of the CA certs. */
11832
85.2k
    while (remaining > 0) {
11833
5.53k
        if (remaining < 3)
11834
70
            goto decode_loser;
11835
11836
5.46k
        remaining -= 3;
11837
5.46k
        rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
11838
5.46k
        if (rv != SECSuccess)
11839
0
            goto loser; /* fatal alert already sent by ConsumeHandshake. */
11840
5.46k
        if (size == 0 || remaining < size)
11841
644
            goto decode_loser;
11842
11843
4.81k
        certItem.data = b;
11844
4.81k
        certItem.len = size;
11845
4.81k
        b += size;
11846
4.81k
        length -= size;
11847
4.81k
        remaining -= size;
11848
11849
4.81k
        c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
11850
4.81k
        if (c == NULL) {
11851
0
            goto loser; /* don't send alerts on memory errors */
11852
0
        }
11853
11854
4.81k
        c->derCert = SECITEM_ArenaDupItem(ss->ssl3.peerCertArena,
11855
4.81k
                                          &certItem);
11856
4.81k
        if (c->derCert == NULL) {
11857
0
            goto loser;
11858
0
        }
11859
11860
4.81k
        c->next = NULL;
11861
4.81k
        if (lastCert) {
11862
2.39k
            lastCert->next = c;
11863
2.41k
        } else {
11864
2.41k
            ss->ssl3.peerCertChain = c;
11865
2.41k
        }
11866
4.81k
        lastCert = c;
11867
4.81k
    }
11868
11869
79.7k
    if (!isServer &&
11870
58.1k
        ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
11871
58.1k
        ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
11872
177
        ss->ssl3.hs.ws = wait_certificate_status;
11873
177
        rv = SECSuccess;
11874
79.5k
    } else {
11875
79.5k
        rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
11876
79.5k
    }
11877
11878
79.7k
    return rv;
11879
11880
1.03k
ambiguous_err:
11881
1.03k
    errCode = PORT_GetError();
11882
1.03k
    switch (errCode) {
11883
0
        case PR_OUT_OF_MEMORY_ERROR:
11884
0
        case SEC_ERROR_BAD_DATABASE:
11885
0
        case SEC_ERROR_NO_MEMORY:
11886
0
            if (isTLS) {
11887
0
                desc = internal_error;
11888
0
                goto alert_loser;
11889
0
            }
11890
0
            goto loser;
11891
1.03k
    }
11892
1.03k
    ssl3_SendAlertForCertError(ss, errCode);
11893
1.03k
    goto loser;
11894
11895
1.21k
decode_loser:
11896
1.21k
    desc = isTLS ? decode_error : bad_certificate;
11897
11898
1.22k
alert_loser:
11899
1.22k
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
11900
11901
2.27k
loser:
11902
2.27k
    (void)ssl_MapLowLevelError(errCode);
11903
2.27k
    return SECFailure;
11904
1.22k
}
11905
11906
SECStatus
11907
ssl_SetAuthKeyBits(sslSocket *ss, const SECKEYPublicKey *pubKey)
11908
56.7k
{
11909
56.7k
    SECStatus rv;
11910
56.7k
    PRUint32 minKey = 0;
11911
56.7k
    PRInt32 optval;
11912
56.7k
    PRBool usePolicyLength = PR_TRUE;
11913
11914
56.7k
    rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS, &optval);
11915
56.7k
    if (rv == SECSuccess) {
11916
56.7k
        usePolicyLength = (PRBool)((optval & NSS_KEY_SIZE_POLICY_SSL_FLAG) == NSS_KEY_SIZE_POLICY_SSL_FLAG);
11917
56.7k
    }
11918
11919
56.7k
    ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(pubKey);
11920
56.7k
    switch (SECKEY_GetPublicKeyType(pubKey)) {
11921
20.4k
        case rsaKey:
11922
20.4k
        case rsaPssKey:
11923
20.4k
        case rsaOaepKey:
11924
20.4k
            rv = usePolicyLength ? NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &optval)
11925
20.4k
                                 : SECFailure;
11926
20.4k
            if (rv == SECSuccess && optval > 0) {
11927
20.4k
                minKey = (PRUint32)optval;
11928
20.4k
            } else {
11929
0
                minKey = SSL_RSA_MIN_MODULUS_BITS;
11930
0
            }
11931
20.4k
            break;
11932
11933
2.39k
        case dsaKey:
11934
2.39k
            rv = usePolicyLength ? NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &optval)
11935
2.39k
                                 : SECFailure;
11936
2.39k
            if (rv == SECSuccess && optval > 0) {
11937
2.39k
                minKey = (PRUint32)optval;
11938
2.39k
            } else {
11939
0
                minKey = SSL_DSA_MIN_P_BITS;
11940
0
            }
11941
2.39k
            break;
11942
11943
43
        case dhKey:
11944
43
            rv = usePolicyLength ? NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &optval)
11945
43
                                 : SECFailure;
11946
43
            if (rv == SECSuccess && optval > 0) {
11947
43
                minKey = (PRUint32)optval;
11948
43
            } else {
11949
0
                minKey = SSL_DH_MIN_P_BITS;
11950
0
            }
11951
43
            break;
11952
11953
33.8k
        case ecKey:
11954
33.8k
            rv = usePolicyLength ? NSS_OptionGet(NSS_ECC_MIN_KEY_SIZE, &optval)
11955
33.8k
                                 : SECFailure;
11956
33.8k
            if (rv == SECSuccess && optval > 0) {
11957
33.8k
                minKey = (PRUint32)optval;
11958
33.8k
            } else {
11959
                /* Don't check EC strength here on the understanding that we
11960
                 * only support curves we like. */
11961
0
                minKey = ss->sec.authKeyBits;
11962
0
            }
11963
33.8k
            break;
11964
36
        case mldsaKey:
11965
            /* ML DSA has fixed sizes per param set and are handled by
11966
             * separate policy oids for each param set */
11967
36
            minKey = ss->sec.authKeyBits;
11968
36
            break;
11969
11970
34
        default:
11971
34
            FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE,
11972
34
                        unsupported_certificate);
11973
34
            return SECFailure;
11974
56.7k
    }
11975
11976
    /* Too small: not good enough. Send a fatal alert. */
11977
56.7k
    if (ss->sec.authKeyBits < minKey) {
11978
624
        FATAL_ERROR(ss, SSL_ERROR_WEAK_SERVER_CERT_KEY,
11979
624
                    ss->version >= SSL_LIBRARY_VERSION_TLS_1_0
11980
624
                        ? insufficient_security
11981
624
                        : illegal_parameter);
11982
624
        return SECFailure;
11983
624
    }
11984
11985
    /* PreliminaryChannelInfo.authKeyBits, scheme, and peerDelegCred are now valid. */
11986
56.1k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_peer_auth;
11987
11988
56.1k
    return SECSuccess;
11989
56.7k
}
11990
11991
SECStatus
11992
ssl3_HandleServerSpki(sslSocket *ss)
11993
57.9k
{
11994
57.9k
    PORT_Assert(!ss->sec.isServer);
11995
57.9k
    SECKEYPublicKey *pubKey;
11996
11997
57.9k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
11998
0
        tls13_IsVerifyingWithDelegatedCredential(ss)) {
11999
0
        sslDelegatedCredential *dc = ss->xtnData.peerDelegCred;
12000
0
        pubKey = SECKEY_ExtractPublicKey(dc->spki);
12001
0
        if (!pubKey) {
12002
0
            FATAL_ERROR(ss, SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE,
12003
0
                        illegal_parameter);
12004
0
            return SECFailure;
12005
0
        }
12006
12007
        /* Because we have only a single authType (ssl_auth_tls13_any)
12008
         * for TLS 1.3 at this point, set the scheme so that the
12009
         * callback can interpret |authKeyBits| correctly.
12010
         */
12011
0
        ss->sec.signatureScheme = dc->expectedCertVerifyAlg;
12012
57.9k
    } else {
12013
57.9k
        pubKey = SECKEY_ExtractPublicKey(ss->sec.peerCertSPKI);
12014
57.9k
        if (!pubKey) {
12015
1.20k
            FATAL_ERROR(ss, SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE,
12016
1.20k
                        bad_certificate);
12017
1.20k
            return SECFailure;
12018
1.20k
        }
12019
57.9k
    }
12020
12021
56.7k
    SECStatus rv = ssl_SetAuthKeyBits(ss, pubKey);
12022
56.7k
    SECKEY_DestroyPublicKey(pubKey);
12023
56.7k
    if (rv != SECSuccess) {
12024
658
        return rv; /* Alert sent and code set. */
12025
658
    }
12026
12027
56.1k
    return SECSuccess;
12028
56.7k
}
12029
12030
SECStatus
12031
ssl3_AuthCertificate(sslSocket *ss)
12032
79.5k
{
12033
79.5k
    SECStatus rv;
12034
79.5k
    PRBool isServer = ss->sec.isServer;
12035
79.5k
    int errCode;
12036
79.5k
    CERTCertList *peerChain = NULL;
12037
12038
79.5k
    ss->ssl3.hs.authCertificatePending = PR_FALSE;
12039
12040
79.5k
    PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
12041
79.5k
                ssl_preinfo_all);
12042
12043
79.5k
    if (!ss->sec.isServer) {
12044
        /* Set the |spki| used to verify the handshake. When verifying with a
12045
         * delegated credential (DC), this corresponds to the DC public key;
12046
         * otherwise it correspond to the public key of the peer's end-entity
12047
         * certificate. */
12048
57.9k
        rv = ssl3_HandleServerSpki(ss);
12049
57.9k
        if (rv != SECSuccess) {
12050
            /* Alert sent and code set. */
12051
1.86k
            errCode = PORT_GetError();
12052
1.86k
            goto loser;
12053
1.86k
        }
12054
12055
56.1k
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
12056
56.1k
            ss->sec.authType = ss->ssl3.hs.kea_def->authKeyType;
12057
56.1k
            ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
12058
56.1k
        }
12059
56.1k
    }
12060
12061
    /*
12062
     * Ask caller-supplied callback function to validate cert chain.
12063
     */
12064
77.7k
    if (ss->opt.dbLoadCertChain) {
12065
        /* Imports the certificate chain into the db. Indirectly used by the
12066
         * authCertificate callback below. */
12067
77.7k
        peerChain = SSL_PeerCertificateChain(ss->fd);
12068
77.7k
        if (!peerChain) {
12069
2.17k
            errCode = PORT_GetError();
12070
2.17k
            goto loser;
12071
2.17k
        }
12072
77.7k
    }
12073
12074
75.5k
    rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
12075
75.5k
                                           PR_TRUE, isServer);
12076
12077
75.5k
    if (ss->opt.dbLoadCertChain && peerChain) {
12078
75.5k
        CERT_DestroyCertList(peerChain);
12079
75.5k
        peerChain = NULL;
12080
75.5k
    }
12081
12082
75.5k
    if (rv != SECSuccess) {
12083
1.48k
        errCode = PORT_GetError();
12084
1.48k
        if (errCode == 0) {
12085
1.01k
            errCode = SSL_ERROR_BAD_CERTIFICATE;
12086
1.01k
        }
12087
1.48k
        if (rv != SECWouldBlock) {
12088
1.48k
            if (ss->handleBadCert) {
12089
0
                rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
12090
0
            }
12091
1.48k
        }
12092
12093
1.48k
        if (rv == SECWouldBlock) {
12094
0
            if (ss->sec.isServer) {
12095
0
                errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
12096
0
                goto loser;
12097
0
            }
12098
12099
0
            ss->ssl3.hs.authCertificatePending = PR_TRUE;
12100
0
            rv = SECSuccess;
12101
0
        }
12102
12103
1.48k
        if (rv != SECSuccess) {
12104
1.48k
            ssl3_SendAlertForCertError(ss, errCode);
12105
1.48k
            goto loser;
12106
1.48k
        }
12107
1.48k
    }
12108
12109
74.0k
    SECITEM_FreeItem(&ss->sec.ci.sid->peerCertDER, PR_FALSE);
12110
74.0k
    if (ss->sec.peerCertDER.data) {
12111
74.0k
        rv = SECITEM_CopyItem(NULL, &ss->sec.ci.sid->peerCertDER,
12112
74.0k
                              &ss->sec.peerCertDER);
12113
74.0k
        if (rv != SECSuccess) {
12114
0
            errCode = PORT_GetError();
12115
0
            goto loser;
12116
0
        }
12117
74.0k
    }
12118
12119
74.0k
    if (!ss->sec.isServer) {
12120
54.8k
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
12121
0
            TLS13_SET_HS_STATE(ss, wait_cert_verify);
12122
54.8k
        } else {
12123
            /* Ephemeral suites require ServerKeyExchange. */
12124
54.8k
            if (ss->ssl3.hs.kea_def->ephemeral) {
12125
                /* require server_key_exchange */
12126
7.96k
                ss->ssl3.hs.ws = wait_server_key;
12127
46.8k
            } else {
12128
                /* disallow server_key_exchange */
12129
46.8k
                ss->ssl3.hs.ws = wait_cert_request;
12130
                /* This is static RSA key exchange so set the key exchange
12131
                 * details to compensate for that. */
12132
46.8k
                ss->sec.keaKeyBits = ss->sec.authKeyBits;
12133
46.8k
                ss->sec.signatureScheme = ssl_sig_none;
12134
46.8k
                ss->sec.keaGroup = NULL;
12135
46.8k
            }
12136
54.8k
        }
12137
54.8k
    } else {
12138
        /* Server */
12139
19.2k
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
12140
19.2k
            ss->ssl3.hs.ws = wait_client_key;
12141
19.2k
        } else {
12142
0
            TLS13_SET_HS_STATE(ss, wait_cert_verify);
12143
0
        }
12144
19.2k
    }
12145
12146
74.0k
    PORT_Assert(rv == SECSuccess);
12147
74.0k
    if (rv != SECSuccess) {
12148
0
        errCode = SEC_ERROR_LIBRARY_FAILURE;
12149
0
        goto loser;
12150
0
    }
12151
12152
74.0k
    return SECSuccess;
12153
12154
5.52k
loser:
12155
5.52k
    (void)ssl_MapLowLevelError(errCode);
12156
5.52k
    return SECFailure;
12157
74.0k
}
12158
12159
static SECStatus ssl3_FinishHandshake(sslSocket *ss);
12160
12161
static SECStatus
12162
ssl3_AlwaysFail(sslSocket *ss)
12163
0
{
12164
    /* The caller should have cleared the callback. */
12165
0
    ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
12166
0
    PORT_SetError(PR_INVALID_STATE_ERROR);
12167
0
    return SECFailure;
12168
0
}
12169
12170
/* Caller must hold 1stHandshakeLock.
12171
 */
12172
SECStatus
12173
ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
12174
0
{
12175
0
    SECStatus rv;
12176
12177
0
    PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
12178
12179
0
    if (ss->sec.isServer) {
12180
0
        PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
12181
0
        return SECFailure;
12182
0
    }
12183
12184
0
    ssl_GetRecvBufLock(ss);
12185
0
    ssl_GetSSL3HandshakeLock(ss);
12186
12187
0
    if (!ss->ssl3.hs.authCertificatePending) {
12188
0
        PORT_SetError(PR_INVALID_STATE_ERROR);
12189
0
        rv = SECFailure;
12190
0
        goto done;
12191
0
    }
12192
12193
0
    ss->ssl3.hs.authCertificatePending = PR_FALSE;
12194
12195
0
    if (error != 0) {
12196
0
        ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
12197
0
        ssl3_SendAlertForCertError(ss, error);
12198
0
        rv = SECSuccess;
12199
0
    } else if (ss->ssl3.hs.restartTarget != NULL) {
12200
0
        sslRestartTarget target = ss->ssl3.hs.restartTarget;
12201
0
        ss->ssl3.hs.restartTarget = NULL;
12202
12203
0
        if (target == ssl3_FinishHandshake) {
12204
0
            SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication lost the race"
12205
0
                        " with peer's finished message",
12206
0
                        SSL_GETPID(), ss->fd));
12207
0
        }
12208
12209
0
        rv = target(ss);
12210
0
    } else {
12211
0
        SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with"
12212
0
                    " peer's finished message",
12213
0
                    SSL_GETPID(), ss->fd));
12214
12215
0
        PORT_Assert(!ss->ssl3.hs.isResuming);
12216
0
        PORT_Assert(ss->ssl3.hs.ws != idle_handshake);
12217
12218
0
        if (ss->opt.enableFalseStart &&
12219
0
            !ss->firstHsDone &&
12220
0
            !ss->ssl3.hs.isResuming &&
12221
0
            ssl3_WaitingForServerSecondRound(ss)) {
12222
            /* ssl3_SendClientSecondRound deferred the false start check because
12223
             * certificate authentication was pending, so we do it now if we still
12224
             * haven't received all of the server's second round yet.
12225
             */
12226
0
            rv = ssl3_CheckFalseStart(ss);
12227
0
        } else {
12228
0
            rv = SECSuccess;
12229
0
        }
12230
0
    }
12231
12232
0
done:
12233
0
    ssl_ReleaseSSL3HandshakeLock(ss);
12234
0
    ssl_ReleaseRecvBufLock(ss);
12235
12236
0
    return rv;
12237
0
}
12238
12239
static SECStatus
12240
ssl3_ComputeTLSFinished(sslSocket *ss, ssl3CipherSpec *spec,
12241
                        PRBool isServer,
12242
                        const SSL3Hashes *hashes,
12243
                        TLSFinished *tlsFinished)
12244
197k
{
12245
197k
    SECStatus rv;
12246
197k
    CK_TLS_MAC_PARAMS tls_mac_params;
12247
197k
    SECItem param = { siBuffer, NULL, 0 };
12248
197k
    PK11Context *prf_context;
12249
197k
    unsigned int retLen;
12250
12251
197k
    PORT_Assert(spec->masterSecret);
12252
197k
    if (!spec->masterSecret) {
12253
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12254
0
        return SECFailure;
12255
0
    }
12256
12257
197k
    if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) {
12258
71.0k
        tls_mac_params.prfHashMechanism = CKM_TLS_PRF;
12259
126k
    } else {
12260
126k
        tls_mac_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
12261
126k
    }
12262
197k
    tls_mac_params.ulMacLength = 12;
12263
197k
    tls_mac_params.ulServerOrClient = isServer ? 1 : 2;
12264
197k
    param.data = (unsigned char *)&tls_mac_params;
12265
197k
    param.len = sizeof(tls_mac_params);
12266
197k
    prf_context = PK11_CreateContextBySymKey(CKM_TLS_MAC, CKA_SIGN,
12267
197k
                                             spec->masterSecret, &param);
12268
197k
    if (!prf_context)
12269
0
        return SECFailure;
12270
12271
197k
    rv = PK11_DigestBegin(prf_context);
12272
197k
    rv |= PK11_DigestOp(prf_context, hashes->u.raw, hashes->len);
12273
197k
    rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data, &retLen,
12274
197k
                           sizeof tlsFinished->verify_data);
12275
197k
    PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data);
12276
12277
197k
    PK11_DestroyContext(prf_context, PR_TRUE);
12278
12279
197k
    return rv;
12280
197k
}
12281
12282
/* The calling function must acquire and release the appropriate
12283
 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
12284
 * ss->ssl3.crSpec).
12285
 */
12286
SECStatus
12287
ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec,
12288
                            const char *label, unsigned int labelLen,
12289
                            const unsigned char *val, unsigned int valLen,
12290
                            unsigned char *out, unsigned int outLen)
12291
0
{
12292
0
    SECItem param = { siBuffer, NULL, 0 };
12293
0
    CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
12294
0
    PK11Context *prf_context;
12295
0
    unsigned int retLen;
12296
0
    SECStatus rv;
12297
12298
0
    if (!spec->masterSecret) {
12299
0
        PORT_Assert(spec->masterSecret);
12300
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12301
0
        return SECFailure;
12302
0
    }
12303
12304
0
    if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
12305
        /* Bug 1312976 non-SHA256 exporters are broken. */
12306
0
        if (ssl3_GetPrfHashMechanism(ss) != CKM_SHA256) {
12307
0
            PORT_Assert(0);
12308
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12309
0
            return SECFailure;
12310
0
        }
12311
0
        mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
12312
0
    }
12313
0
    prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
12314
0
                                             spec->masterSecret, &param);
12315
0
    if (!prf_context)
12316
0
        return SECFailure;
12317
12318
0
    rv = PK11_DigestBegin(prf_context);
12319
0
    rv |= PK11_DigestOp(prf_context, (unsigned char *)label, labelLen);
12320
0
    rv |= PK11_DigestOp(prf_context, val, valLen);
12321
0
    rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
12322
0
    PORT_Assert(rv != SECSuccess || retLen == outLen);
12323
12324
0
    PK11_DestroyContext(prf_context, PR_TRUE);
12325
0
    return rv;
12326
0
}
12327
12328
/* called from ssl3_SendClientSecondRound
12329
 *             ssl3_HandleFinished
12330
 */
12331
static SECStatus
12332
ssl3_SendNextProto(sslSocket *ss)
12333
0
{
12334
0
    SECStatus rv;
12335
0
    int padding_len;
12336
0
    static const unsigned char padding[32] = { 0 };
12337
12338
0
    if (ss->xtnData.nextProto.len == 0 ||
12339
0
        ss->xtnData.nextProtoState == SSL_NEXT_PROTO_SELECTED) {
12340
0
        return SECSuccess;
12341
0
    }
12342
12343
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
12344
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12345
12346
0
    padding_len = 32 - ((ss->xtnData.nextProto.len + 2) % 32);
12347
12348
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_next_proto, ss->xtnData.nextProto.len + 2 + padding_len);
12349
0
    if (rv != SECSuccess) {
12350
0
        return rv; /* error code set by AppendHandshakeHeader */
12351
0
    }
12352
0
    rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.nextProto.data,
12353
0
                                      ss->xtnData.nextProto.len, 1);
12354
0
    if (rv != SECSuccess) {
12355
0
        return rv; /* error code set by AppendHandshake */
12356
0
    }
12357
0
    rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
12358
0
    if (rv != SECSuccess) {
12359
0
        return rv; /* error code set by AppendHandshake */
12360
0
    }
12361
0
    return rv;
12362
0
}
12363
12364
/* called from ssl3_SendFinished, tls13_DeriveSecret and tls13_LogECHSecret.
12365
 *
12366
 * This function is simply a debugging aid and therefore does not return a
12367
 * SECStatus. */
12368
void
12369
ssl3_RecordKeyLog(sslSocket *ss, const char *label, PK11SymKey *secret)
12370
123k
{
12371
123k
#ifdef NSS_ALLOW_SSLKEYLOGFILE
12372
123k
    SECStatus rv;
12373
123k
    SECItem *keyData;
12374
12375
123k
    rv = PK11_ExtractKeyValue(secret);
12376
123k
    if (rv != SECSuccess)
12377
0
        return;
12378
12379
    /* keyData does not need to be freed. */
12380
123k
    keyData = PK11_GetKeyData(secret);
12381
12382
123k
    ssl3_WriteKeyLog(ss, label, keyData);
12383
123k
#endif
12384
123k
}
12385
12386
/* called from ssl3_RecordKeyLog and tls13_EchKeyLog.
12387
 *
12388
 * This function is simply a debugging aid and therefore does not return a
12389
 * SECStatus. */
12390
void
12391
ssl3_WriteKeyLog(sslSocket *ss, const char *label, const SECItem *item)
12392
126k
{
12393
126k
#ifdef NSS_ALLOW_SSLKEYLOGFILE
12394
126k
    char *buf;
12395
126k
    unsigned int offset, len;
12396
12397
126k
    if (item == NULL || item->data == NULL)
12398
0
        return;
12399
12400
126k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12401
12402
126k
    if (!ssl_keylog_iob)
12403
126k
        return;
12404
12405
0
    len = strlen(label) + 1 +          /* label + space */
12406
0
          SSL3_RANDOM_LENGTH * 2 + 1 + /* client random (hex) + space */
12407
0
          item->len * 2 + 1;           /* secret (hex) + newline */
12408
0
    buf = (char *)PORT_Alloc(len);
12409
0
    if (!buf)
12410
0
        return;
12411
12412
    /* There could be multiple, concurrent writers to the
12413
     * keylog, so we have to do everything in a single call to
12414
     * fwrite. */
12415
12416
0
    strcpy(buf, label);
12417
0
    offset = strlen(label);
12418
0
    buf[offset++] += ' ';
12419
0
    hexEncode(buf + offset, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
12420
0
    offset += SSL3_RANDOM_LENGTH * 2;
12421
0
    buf[offset++] = ' ';
12422
0
    hexEncode(buf + offset, item->data, item->len);
12423
0
    offset += item->len * 2;
12424
0
    buf[offset++] = '\n';
12425
12426
0
    PORT_Assert(offset == len);
12427
12428
0
    PR_Lock(ssl_keylog_lock);
12429
0
    if (fwrite(buf, len, 1, ssl_keylog_iob) == 1)
12430
0
        fflush(ssl_keylog_iob);
12431
0
    PR_Unlock(ssl_keylog_lock);
12432
0
    PORT_Free(buf);
12433
0
#endif
12434
0
}
12435
12436
/* called from ssl3_SendClientSecondRound
12437
 *             ssl3_HandleClientHello
12438
 *             ssl3_HandleFinished
12439
 */
12440
static SECStatus
12441
ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
12442
101k
{
12443
101k
    ssl3CipherSpec *cwSpec;
12444
101k
    PRBool isTLS;
12445
101k
    PRBool isServer = ss->sec.isServer;
12446
101k
    SECStatus rv;
12447
101k
    SSL3Sender sender = isServer ? sender_server : sender_client;
12448
101k
    SSL3Hashes hashes;
12449
101k
    TLSFinished tlsFinished;
12450
12451
101k
    SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
12452
12453
101k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
12454
101k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12455
101k
    PR_ASSERT(!ss->ssl3.hs.clientCertificatePending);
12456
12457
101k
    ssl_GetSpecReadLock(ss);
12458
101k
    cwSpec = ss->ssl3.cwSpec;
12459
101k
    isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
12460
101k
    rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
12461
101k
    if (isTLS && rv == SECSuccess) {
12462
101k
        rv = ssl3_ComputeTLSFinished(ss, cwSpec, isServer, &hashes, &tlsFinished);
12463
101k
    }
12464
101k
    ssl_ReleaseSpecReadLock(ss);
12465
101k
    if (rv != SECSuccess) {
12466
0
        goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */
12467
0
    }
12468
12469
101k
    if (isTLS) {
12470
101k
        if (isServer)
12471
56.5k
            ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
12472
45.3k
        else
12473
45.3k
            ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
12474
101k
        ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
12475
101k
        rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof tlsFinished);
12476
101k
        if (rv != SECSuccess)
12477
0
            goto fail; /* err set by AppendHandshake. */
12478
101k
        rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
12479
101k
        if (rv != SECSuccess)
12480
0
            goto fail; /* err set by AppendHandshake. */
12481
101k
    } else {
12482
0
        if (isServer)
12483
0
            ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
12484
0
        else
12485
0
            ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
12486
0
        PORT_Assert(hashes.len == sizeof hashes.u.s);
12487
0
        ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
12488
0
        rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof hashes.u.s);
12489
0
        if (rv != SECSuccess)
12490
0
            goto fail; /* err set by AppendHandshake. */
12491
0
        rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
12492
0
        if (rv != SECSuccess)
12493
0
            goto fail; /* err set by AppendHandshake. */
12494
0
    }
12495
101k
    rv = ssl3_FlushHandshake(ss, flags);
12496
101k
    if (rv != SECSuccess) {
12497
0
        goto fail; /* error code set by ssl3_FlushHandshake */
12498
0
    }
12499
12500
101k
    ssl3_RecordKeyLog(ss, "CLIENT_RANDOM", ss->ssl3.cwSpec->masterSecret);
12501
12502
101k
    return SECSuccess;
12503
12504
0
fail:
12505
0
    return rv;
12506
101k
}
12507
12508
/* wrap the master secret, and put it into the SID.
12509
 * Caller holds the Spec read lock.
12510
 */
12511
SECStatus
12512
ssl3_CacheWrappedSecret(sslSocket *ss, sslSessionID *sid,
12513
                        PK11SymKey *secret)
12514
50.9k
{
12515
50.9k
    PK11SymKey *wrappingKey = NULL;
12516
50.9k
    PK11SlotInfo *symKeySlot;
12517
50.9k
    void *pwArg = ss->pkcs11PinArg;
12518
50.9k
    SECStatus rv = SECFailure;
12519
50.9k
    PRBool isServer = ss->sec.isServer;
12520
50.9k
    CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
12521
12522
50.9k
    symKeySlot = PK11_GetSlotFromKey(secret);
12523
50.9k
    if (!isServer) {
12524
18.1k
        int wrapKeyIndex;
12525
18.1k
        int incarnation;
12526
12527
        /* these next few functions are mere accessors and don't fail. */
12528
18.1k
        sid->u.ssl3.masterWrapIndex = wrapKeyIndex =
12529
18.1k
            PK11_GetCurrentWrapIndex(symKeySlot);
12530
18.1k
        PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
12531
12532
18.1k
        sid->u.ssl3.masterWrapSeries = incarnation =
12533
18.1k
            PK11_GetSlotSeries(symKeySlot);
12534
18.1k
        sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot);
12535
18.1k
        sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
12536
18.1k
        sid->u.ssl3.masterValid = PR_TRUE;
12537
        /* Get the default wrapping key, for wrapping the master secret before
12538
         * placing it in the SID cache entry. */
12539
18.1k
        wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
12540
18.1k
                                      CKM_INVALID_MECHANISM, incarnation,
12541
18.1k
                                      pwArg);
12542
18.1k
        if (wrappingKey) {
12543
18.1k
            mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
12544
18.1k
        } else {
12545
2
            int keyLength;
12546
            /* if the wrappingKey doesn't exist, attempt to create it.
12547
             * Note: we intentionally ignore errors here.  If we cannot
12548
             * generate a wrapping key, it is not fatal to this SSL connection,
12549
             * but we will not be able to restart this session.
12550
             */
12551
2
            mechanism = PK11_GetBestWrapMechanism(symKeySlot);
12552
2
            keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
12553
            /* Zero length means fixed key length algorithm, or error.
12554
             * It's ambiguous.
12555
             */
12556
2
            wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
12557
2
                                      keyLength, pwArg);
12558
2
            if (wrappingKey) {
12559
                /* The thread safety characteristics of PK11_[SG]etWrapKey is
12560
                 * abominable.  This protects against races in calling
12561
                 * PK11_SetWrapKey by dropping and re-acquiring the canonical
12562
                 * value once it is set.  The mutex in PK11_[SG]etWrapKey will
12563
                 * ensure that races produce the same value in the end. */
12564
2
                PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
12565
2
                PK11_FreeSymKey(wrappingKey);
12566
2
                wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
12567
2
                                              CKM_INVALID_MECHANISM, incarnation, pwArg);
12568
2
                if (!wrappingKey) {
12569
0
                    PK11_FreeSlot(symKeySlot);
12570
0
                    return SECFailure;
12571
0
                }
12572
2
            }
12573
2
        }
12574
32.7k
    } else {
12575
        /* server socket using session cache. */
12576
32.7k
        mechanism = PK11_GetBestWrapMechanism(symKeySlot);
12577
32.7k
        if (mechanism != CKM_INVALID_MECHANISM) {
12578
32.7k
            wrappingKey =
12579
32.7k
                ssl3_GetWrappingKey(ss, symKeySlot, mechanism, pwArg);
12580
32.7k
            if (wrappingKey) {
12581
32.7k
                mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
12582
32.7k
            }
12583
32.7k
        }
12584
32.7k
    }
12585
12586
50.9k
    sid->u.ssl3.masterWrapMech = mechanism;
12587
50.9k
    PK11_FreeSlot(symKeySlot);
12588
12589
50.9k
    if (wrappingKey) {
12590
50.9k
        SECItem wmsItem;
12591
12592
50.9k
        wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
12593
50.9k
        wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret;
12594
50.9k
        rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
12595
50.9k
                             secret, &wmsItem);
12596
        /* rv is examined below. */
12597
50.9k
        sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
12598
50.9k
        PK11_FreeSymKey(wrappingKey);
12599
50.9k
    }
12600
50.9k
    return rv;
12601
50.9k
}
12602
12603
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
12604
 * a complete ssl3 Finished message from the peer.
12605
 * Caller must hold Handshake and RecvBuf locks.
12606
 */
12607
static SECStatus
12608
ssl3_HandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
12609
95.6k
{
12610
95.6k
    SECStatus rv = SECSuccess;
12611
95.6k
    PRBool isServer = ss->sec.isServer;
12612
95.6k
    PRBool isTLS;
12613
95.6k
    SSL3Hashes hashes;
12614
12615
95.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12616
95.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12617
12618
95.6k
    SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
12619
95.6k
                SSL_GETPID(), ss->fd));
12620
12621
95.6k
    if (ss->ssl3.hs.ws != wait_finished) {
12622
103
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12623
103
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
12624
103
        return SECFailure;
12625
103
    }
12626
12627
95.5k
    if (!ss->sec.isServer || !ss->opt.requestCertificate) {
12628
81.5k
        dtls_ReceivedFirstMessageInFlight(ss);
12629
81.5k
    }
12630
12631
95.5k
    rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.crSpec, &hashes,
12632
95.5k
                                     isServer ? sender_client : sender_server);
12633
95.5k
    if (rv != SECSuccess) {
12634
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12635
0
        return SECFailure;
12636
0
    }
12637
12638
95.5k
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
12639
95.5k
    if (rv != SECSuccess) {
12640
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12641
0
        return rv;
12642
0
    }
12643
12644
95.5k
    isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
12645
95.5k
    if (isTLS) {
12646
95.5k
        TLSFinished tlsFinished;
12647
12648
95.5k
        if (length != sizeof(tlsFinished)) {
12649
#ifndef UNSAFE_FUZZER_MODE
12650
            (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
12651
0
            PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12652
            return SECFailure;
12653
#endif
12654
80.4k
        }
12655
1
        rv = ssl3_ComputeTLSFinished(ss, ss->ssl3.crSpec, !isServer,
12656
1
                                     &hashes, &tlsFinished);
12657
95.5k
        if (!isServer)
12658
39.0k
            ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
12659
56.5k
        else
12660
56.5k
            ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
12661
1
        ss->ssl3.hs.finishedBytes = sizeof(tlsFinished);
12662
95.5k
        if (rv != SECSuccess ||
12663
95.5k
            0 != NSS_SecureMemcmp(&tlsFinished, b,
12664
95.5k
                                  PR_MIN(length, ss->ssl3.hs.finishedBytes))) {
12665
#ifndef UNSAFE_FUZZER_MODE
12666
            (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
12667
1
            PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12668
            return SECFailure;
12669
#endif
12670
15.2k
        }
12671
1
    } else {
12672
0
        if (length != sizeof(SSL3Finished)) {
12673
0
            (void)ssl3_IllegalParameter(ss);
12674
0
            PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12675
0
            return SECFailure;
12676
0
        }
12677
12678
0
        if (!isServer)
12679
0
            ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
12680
0
        else
12681
0
            ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
12682
0
        PORT_Assert(hashes.len == sizeof hashes.u.s);
12683
0
        ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
12684
0
        if (0 != NSS_SecureMemcmp(&hashes.u.s, b, length)) {
12685
0
            (void)ssl3_HandshakeFailure(ss);
12686
0
            PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12687
0
            return SECFailure;
12688
0
        }
12689
0
    }
12690
12691
95.5k
    ssl_GetXmitBufLock(ss); /*************************************/
12692
12693
95.5k
    if ((isServer && !ss->ssl3.hs.isResuming) ||
12694
56.5k
        (!isServer && ss->ssl3.hs.isResuming)) {
12695
56.5k
        PRInt32 flags = 0;
12696
12697
        /* Send a NewSessionTicket message if the client sent us
12698
         * either an empty session ticket, or one that did not verify.
12699
         * (Note that if either of these conditions was met, then the
12700
         * server has sent a SessionTicket extension in the
12701
         * ServerHello message.)
12702
         */
12703
56.5k
        if (isServer && !ss->ssl3.hs.isResuming &&
12704
56.5k
            ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
12705
2.91k
            ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
12706
            /* RFC 5077 Section 3.3: "In the case of a full handshake, the
12707
             * server MUST verify the client's Finished message before sending
12708
             * the ticket." Presumably, this also means that the client's
12709
             * certificate, if any, must be verified beforehand too.
12710
             */
12711
2.91k
            rv = ssl3_SendNewSessionTicket(ss);
12712
2.91k
            if (rv != SECSuccess) {
12713
0
                goto xmit_loser;
12714
0
            }
12715
2.91k
        }
12716
12717
56.5k
        rv = ssl3_SendChangeCipherSpecs(ss);
12718
56.5k
        if (rv != SECSuccess) {
12719
0
            goto xmit_loser; /* err is set. */
12720
0
        }
12721
        /* If this thread is in SSL_SecureSend (trying to write some data)
12722
        ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
12723
        ** last two handshake messages (change cipher spec and finished)
12724
        ** will be sent in the same send/write call as the application data.
12725
        */
12726
56.5k
        if (ss->writerThread == PR_GetCurrentThread()) {
12727
0
            flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
12728
0
        }
12729
12730
56.5k
        if (!isServer && !ss->firstHsDone) {
12731
0
            rv = ssl3_SendNextProto(ss);
12732
0
            if (rv != SECSuccess) {
12733
0
                goto xmit_loser; /* err code was set. */
12734
0
            }
12735
0
        }
12736
12737
56.5k
        if (IS_DTLS(ss)) {
12738
221
            flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
12739
221
        }
12740
12741
56.5k
        rv = ssl3_SendFinished(ss, flags);
12742
56.5k
        if (rv != SECSuccess) {
12743
0
            goto xmit_loser; /* err is set. */
12744
0
        }
12745
56.5k
    }
12746
12747
95.5k
xmit_loser:
12748
95.5k
    ssl_ReleaseXmitBufLock(ss); /*************************************/
12749
95.5k
    if (rv != SECSuccess) {
12750
0
        return rv;
12751
0
    }
12752
12753
95.5k
    if (ss->ssl3.hs.authCertificatePending) {
12754
0
        if (ss->ssl3.hs.restartTarget) {
12755
0
            PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
12756
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12757
0
            return SECFailure;
12758
0
        }
12759
12760
0
        ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
12761
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
12762
0
        return SECFailure;
12763
0
    }
12764
12765
95.5k
    rv = ssl3_FinishHandshake(ss);
12766
95.5k
    return rv;
12767
95.5k
}
ssl3con.c:ssl3_HandleFinished
Line
Count
Source
12609
95.6k
{
12610
95.6k
    SECStatus rv = SECSuccess;
12611
95.6k
    PRBool isServer = ss->sec.isServer;
12612
95.6k
    PRBool isTLS;
12613
95.6k
    SSL3Hashes hashes;
12614
12615
95.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12616
95.6k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12617
12618
95.6k
    SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
12619
95.6k
                SSL_GETPID(), ss->fd));
12620
12621
95.6k
    if (ss->ssl3.hs.ws != wait_finished) {
12622
92
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12623
92
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
12624
92
        return SECFailure;
12625
92
    }
12626
12627
95.5k
    if (!ss->sec.isServer || !ss->opt.requestCertificate) {
12628
81.5k
        dtls_ReceivedFirstMessageInFlight(ss);
12629
81.5k
    }
12630
12631
95.5k
    rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.crSpec, &hashes,
12632
95.5k
                                     isServer ? sender_client : sender_server);
12633
95.5k
    if (rv != SECSuccess) {
12634
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12635
0
        return SECFailure;
12636
0
    }
12637
12638
95.5k
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
12639
95.5k
    if (rv != SECSuccess) {
12640
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12641
0
        return rv;
12642
0
    }
12643
12644
95.5k
    isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
12645
95.5k
    if (isTLS) {
12646
95.5k
        TLSFinished tlsFinished;
12647
12648
95.5k
        if (length != sizeof(tlsFinished)) {
12649
#ifndef UNSAFE_FUZZER_MODE
12650
            (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
12651
            PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12652
            return SECFailure;
12653
#endif
12654
80.4k
        }
12655
95.5k
        rv = ssl3_ComputeTLSFinished(ss, ss->ssl3.crSpec, !isServer,
12656
95.5k
                                     &hashes, &tlsFinished);
12657
95.5k
        if (!isServer)
12658
39.0k
            ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
12659
56.5k
        else
12660
56.5k
            ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
12661
95.5k
        ss->ssl3.hs.finishedBytes = sizeof(tlsFinished);
12662
95.5k
        if (rv != SECSuccess ||
12663
95.5k
            0 != NSS_SecureMemcmp(&tlsFinished, b,
12664
95.5k
                                  PR_MIN(length, ss->ssl3.hs.finishedBytes))) {
12665
#ifndef UNSAFE_FUZZER_MODE
12666
            (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
12667
            PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12668
            return SECFailure;
12669
#endif
12670
15.2k
        }
12671
95.5k
    } else {
12672
0
        if (length != sizeof(SSL3Finished)) {
12673
0
            (void)ssl3_IllegalParameter(ss);
12674
0
            PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12675
0
            return SECFailure;
12676
0
        }
12677
12678
0
        if (!isServer)
12679
0
            ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
12680
0
        else
12681
0
            ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
12682
0
        PORT_Assert(hashes.len == sizeof hashes.u.s);
12683
0
        ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
12684
0
        if (0 != NSS_SecureMemcmp(&hashes.u.s, b, length)) {
12685
0
            (void)ssl3_HandshakeFailure(ss);
12686
0
            PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12687
0
            return SECFailure;
12688
0
        }
12689
0
    }
12690
12691
95.5k
    ssl_GetXmitBufLock(ss); /*************************************/
12692
12693
95.5k
    if ((isServer && !ss->ssl3.hs.isResuming) ||
12694
56.5k
        (!isServer && ss->ssl3.hs.isResuming)) {
12695
56.5k
        PRInt32 flags = 0;
12696
12697
        /* Send a NewSessionTicket message if the client sent us
12698
         * either an empty session ticket, or one that did not verify.
12699
         * (Note that if either of these conditions was met, then the
12700
         * server has sent a SessionTicket extension in the
12701
         * ServerHello message.)
12702
         */
12703
56.5k
        if (isServer && !ss->ssl3.hs.isResuming &&
12704
56.5k
            ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
12705
2.91k
            ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
12706
            /* RFC 5077 Section 3.3: "In the case of a full handshake, the
12707
             * server MUST verify the client's Finished message before sending
12708
             * the ticket." Presumably, this also means that the client's
12709
             * certificate, if any, must be verified beforehand too.
12710
             */
12711
2.91k
            rv = ssl3_SendNewSessionTicket(ss);
12712
2.91k
            if (rv != SECSuccess) {
12713
0
                goto xmit_loser;
12714
0
            }
12715
2.91k
        }
12716
12717
56.5k
        rv = ssl3_SendChangeCipherSpecs(ss);
12718
56.5k
        if (rv != SECSuccess) {
12719
0
            goto xmit_loser; /* err is set. */
12720
0
        }
12721
        /* If this thread is in SSL_SecureSend (trying to write some data)
12722
        ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
12723
        ** last two handshake messages (change cipher spec and finished)
12724
        ** will be sent in the same send/write call as the application data.
12725
        */
12726
56.5k
        if (ss->writerThread == PR_GetCurrentThread()) {
12727
0
            flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
12728
0
        }
12729
12730
56.5k
        if (!isServer && !ss->firstHsDone) {
12731
0
            rv = ssl3_SendNextProto(ss);
12732
0
            if (rv != SECSuccess) {
12733
0
                goto xmit_loser; /* err code was set. */
12734
0
            }
12735
0
        }
12736
12737
56.5k
        if (IS_DTLS(ss)) {
12738
221
            flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
12739
221
        }
12740
12741
56.5k
        rv = ssl3_SendFinished(ss, flags);
12742
56.5k
        if (rv != SECSuccess) {
12743
0
            goto xmit_loser; /* err is set. */
12744
0
        }
12745
56.5k
    }
12746
12747
95.5k
xmit_loser:
12748
95.5k
    ssl_ReleaseXmitBufLock(ss); /*************************************/
12749
95.5k
    if (rv != SECSuccess) {
12750
0
        return rv;
12751
0
    }
12752
12753
95.5k
    if (ss->ssl3.hs.authCertificatePending) {
12754
0
        if (ss->ssl3.hs.restartTarget) {
12755
0
            PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
12756
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12757
0
            return SECFailure;
12758
0
        }
12759
12760
0
        ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
12761
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
12762
0
        return SECFailure;
12763
0
    }
12764
12765
95.5k
    rv = ssl3_FinishHandshake(ss);
12766
95.5k
    return rv;
12767
95.5k
}
ssl3con.c:ssl3_HandleFinished
Line
Count
Source
12609
12
{
12610
12
    SECStatus rv = SECSuccess;
12611
12
    PRBool isServer = ss->sec.isServer;
12612
12
    PRBool isTLS;
12613
12
    SSL3Hashes hashes;
12614
12615
12
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12616
12
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12617
12618
12
    SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
12619
12
                SSL_GETPID(), ss->fd));
12620
12621
12
    if (ss->ssl3.hs.ws != wait_finished) {
12622
11
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12623
11
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
12624
11
        return SECFailure;
12625
11
    }
12626
12627
1
    if (!ss->sec.isServer || !ss->opt.requestCertificate) {
12628
1
        dtls_ReceivedFirstMessageInFlight(ss);
12629
1
    }
12630
12631
1
    rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.crSpec, &hashes,
12632
1
                                     isServer ? sender_client : sender_server);
12633
1
    if (rv != SECSuccess) {
12634
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12635
0
        return SECFailure;
12636
0
    }
12637
12638
1
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
12639
1
    if (rv != SECSuccess) {
12640
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12641
0
        return rv;
12642
0
    }
12643
12644
1
    isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
12645
1
    if (isTLS) {
12646
1
        TLSFinished tlsFinished;
12647
12648
1
        if (length != sizeof(tlsFinished)) {
12649
0
#ifndef UNSAFE_FUZZER_MODE
12650
0
            (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
12651
0
            PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12652
0
            return SECFailure;
12653
0
#endif
12654
0
        }
12655
1
        rv = ssl3_ComputeTLSFinished(ss, ss->ssl3.crSpec, !isServer,
12656
1
                                     &hashes, &tlsFinished);
12657
1
        if (!isServer)
12658
1
            ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
12659
0
        else
12660
0
            ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
12661
1
        ss->ssl3.hs.finishedBytes = sizeof(tlsFinished);
12662
1
        if (rv != SECSuccess ||
12663
1
            0 != NSS_SecureMemcmp(&tlsFinished, b,
12664
1
                                  PR_MIN(length, ss->ssl3.hs.finishedBytes))) {
12665
1
#ifndef UNSAFE_FUZZER_MODE
12666
1
            (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
12667
1
            PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12668
1
            return SECFailure;
12669
1
#endif
12670
1
        }
12671
1
    } else {
12672
0
        if (length != sizeof(SSL3Finished)) {
12673
0
            (void)ssl3_IllegalParameter(ss);
12674
0
            PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12675
0
            return SECFailure;
12676
0
        }
12677
12678
0
        if (!isServer)
12679
0
            ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
12680
0
        else
12681
0
            ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
12682
0
        PORT_Assert(hashes.len == sizeof hashes.u.s);
12683
0
        ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
12684
0
        if (0 != NSS_SecureMemcmp(&hashes.u.s, b, length)) {
12685
0
            (void)ssl3_HandshakeFailure(ss);
12686
0
            PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12687
0
            return SECFailure;
12688
0
        }
12689
0
    }
12690
12691
0
    ssl_GetXmitBufLock(ss); /*************************************/
12692
12693
0
    if ((isServer && !ss->ssl3.hs.isResuming) ||
12694
0
        (!isServer && ss->ssl3.hs.isResuming)) {
12695
0
        PRInt32 flags = 0;
12696
12697
        /* Send a NewSessionTicket message if the client sent us
12698
         * either an empty session ticket, or one that did not verify.
12699
         * (Note that if either of these conditions was met, then the
12700
         * server has sent a SessionTicket extension in the
12701
         * ServerHello message.)
12702
         */
12703
0
        if (isServer && !ss->ssl3.hs.isResuming &&
12704
0
            ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
12705
0
            ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
12706
            /* RFC 5077 Section 3.3: "In the case of a full handshake, the
12707
             * server MUST verify the client's Finished message before sending
12708
             * the ticket." Presumably, this also means that the client's
12709
             * certificate, if any, must be verified beforehand too.
12710
             */
12711
0
            rv = ssl3_SendNewSessionTicket(ss);
12712
0
            if (rv != SECSuccess) {
12713
0
                goto xmit_loser;
12714
0
            }
12715
0
        }
12716
12717
0
        rv = ssl3_SendChangeCipherSpecs(ss);
12718
0
        if (rv != SECSuccess) {
12719
0
            goto xmit_loser; /* err is set. */
12720
0
        }
12721
        /* If this thread is in SSL_SecureSend (trying to write some data)
12722
        ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
12723
        ** last two handshake messages (change cipher spec and finished)
12724
        ** will be sent in the same send/write call as the application data.
12725
        */
12726
0
        if (ss->writerThread == PR_GetCurrentThread()) {
12727
0
            flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
12728
0
        }
12729
12730
0
        if (!isServer && !ss->firstHsDone) {
12731
0
            rv = ssl3_SendNextProto(ss);
12732
0
            if (rv != SECSuccess) {
12733
0
                goto xmit_loser; /* err code was set. */
12734
0
            }
12735
0
        }
12736
12737
0
        if (IS_DTLS(ss)) {
12738
0
            flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
12739
0
        }
12740
12741
0
        rv = ssl3_SendFinished(ss, flags);
12742
0
        if (rv != SECSuccess) {
12743
0
            goto xmit_loser; /* err is set. */
12744
0
        }
12745
0
    }
12746
12747
0
xmit_loser:
12748
0
    ssl_ReleaseXmitBufLock(ss); /*************************************/
12749
0
    if (rv != SECSuccess) {
12750
0
        return rv;
12751
0
    }
12752
12753
0
    if (ss->ssl3.hs.authCertificatePending) {
12754
0
        if (ss->ssl3.hs.restartTarget) {
12755
0
            PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
12756
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12757
0
            return SECFailure;
12758
0
        }
12759
12760
0
        ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
12761
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
12762
0
        return SECFailure;
12763
0
    }
12764
12765
0
    rv = ssl3_FinishHandshake(ss);
12766
0
    return rv;
12767
0
}
12768
12769
SECStatus
12770
ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid, PK11SymKey *secret)
12771
47.6k
{
12772
47.6k
    PORT_Assert(secret);
12773
12774
    /* fill in the sid */
12775
47.6k
    sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
12776
47.6k
    sid->u.ssl3.policy = ss->ssl3.policy;
12777
47.6k
    sid->version = ss->version;
12778
47.6k
    sid->authType = ss->sec.authType;
12779
47.6k
    sid->authKeyBits = ss->sec.authKeyBits;
12780
47.6k
    sid->keaType = ss->sec.keaType;
12781
47.6k
    sid->keaKeyBits = ss->sec.keaKeyBits;
12782
47.6k
    if (ss->sec.keaGroup) {
12783
23.1k
        sid->keaGroup = ss->sec.keaGroup->name;
12784
24.4k
    } else {
12785
24.4k
        sid->keaGroup = ssl_grp_none;
12786
24.4k
    }
12787
47.6k
    sid->sigScheme = ss->sec.signatureScheme;
12788
47.6k
    sid->lastAccessTime = sid->creationTime = ssl_Time(ss);
12789
47.6k
    sid->expirationTime = sid->creationTime + (ssl_ticket_lifetime * PR_USEC_PER_SEC);
12790
47.6k
    if (sid->localCert) {
12791
0
        CERT_DestroyCertificate(sid->localCert);
12792
0
    }
12793
47.6k
    sid->localCert = CERT_DupCertificate(ss->sec.localCert);
12794
47.6k
    if (ss->sec.isServer) {
12795
29.5k
        sid->namedCurve = ss->sec.serverCert->namedCurve;
12796
29.5k
    }
12797
12798
47.6k
    if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
12799
2
        ss->xtnData.nextProto.data) {
12800
2
        SECITEM_FreeItem(&sid->u.ssl3.alpnSelection, PR_FALSE);
12801
2
        if (SECITEM_CopyItem(
12802
2
                NULL, &sid->u.ssl3.alpnSelection, &ss->xtnData.nextProto) != SECSuccess) {
12803
0
            return SECFailure; /* error already set. */
12804
0
        }
12805
2
    }
12806
12807
    /* Copy the master secret (wrapped or unwrapped) into the sid */
12808
47.6k
    return ssl3_CacheWrappedSecret(ss, ss->sec.ci.sid, secret);
12809
47.6k
}
12810
12811
/* The return type is SECStatus instead of void because this function needs
12812
 * to have type sslRestartTarget.
12813
 */
12814
SECStatus
12815
ssl3_FinishHandshake(sslSocket *ss)
12816
95.5k
{
12817
95.5k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12818
95.5k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12819
95.5k
    PORT_Assert(ss->ssl3.hs.restartTarget == NULL);
12820
95.5k
    sslSessionID *sid = ss->sec.ci.sid;
12821
95.5k
    SECStatus sidRv = SECFailure;
12822
12823
    /* The first handshake is now completed. */
12824
95.5k
    ss->handshake = NULL;
12825
12826
95.5k
    if (sid->cached == never_cached && !ss->opt.noCache) {
12827
        /* If the wrap fails, don't cache the sid. The connection proceeds
12828
         * normally, so the rv is only used to determine whether we cache. */
12829
47.6k
        sidRv = ssl3_FillInCachedSID(ss, sid, ss->ssl3.crSpec->masterSecret);
12830
47.6k
    }
12831
12832
    /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid
12833
     * until it has verified the server's Finished message." When the server
12834
     * sends a NewSessionTicket in a resumption handshake, we must wait until
12835
     * the handshake is finished (we have verified the server's Finished
12836
     * AND the server's certificate) before we update the ticket in the sid.
12837
     *
12838
     * This must be done before we call ssl_CacheSessionID(ss)
12839
     * because CacheSID requires the session ticket to already be set, and also
12840
     * because of the lazy lock creation scheme used by CacheSID and
12841
     * ssl3_SetSIDSessionTicket. */
12842
95.5k
    if (ss->ssl3.hs.receivedNewSessionTicket) {
12843
2
        PORT_Assert(!ss->sec.isServer);
12844
2
        if (sidRv == SECSuccess) {
12845
            /* The sid takes over the ticket data */
12846
1
            ssl3_SetSIDSessionTicket(ss->sec.ci.sid,
12847
1
                                     &ss->ssl3.hs.newSessionTicket);
12848
1
        } else {
12849
1
            PORT_Assert(ss->ssl3.hs.newSessionTicket.ticket.data);
12850
1
            SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket,
12851
1
                             PR_FALSE);
12852
1
        }
12853
2
        PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
12854
2
        ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
12855
2
    }
12856
95.5k
    if (sidRv == SECSuccess) {
12857
47.6k
        PORT_Assert(ss->sec.ci.sid->cached == never_cached);
12858
47.6k
        ssl_CacheSessionID(ss);
12859
47.6k
    }
12860
12861
95.5k
    ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */
12862
95.5k
    ss->ssl3.hs.ws = idle_handshake;
12863
12864
95.5k
    return ssl_FinishHandshake(ss);
12865
95.5k
}
12866
12867
SECStatus
12868
ssl_HashHandshakeMessageInt(sslSocket *ss, SSLHandshakeType ct,
12869
                            PRUint32 dtlsSeq,
12870
                            const PRUint8 *b, PRUint32 length,
12871
                            sslUpdateHandshakeHashes updateHashes)
12872
467k
{
12873
467k
    PRUint8 hdr[4];
12874
467k
    PRUint8 dtlsData[8];
12875
467k
    SECStatus rv;
12876
12877
467k
    PRINT_BUF(50, (ss, "Hash handshake message:", b, length));
12878
12879
467k
    hdr[0] = (PRUint8)ct;
12880
467k
    hdr[1] = (PRUint8)(length >> 16);
12881
467k
    hdr[2] = (PRUint8)(length >> 8);
12882
467k
    hdr[3] = (PRUint8)(length);
12883
12884
467k
    rv = updateHashes(ss, (unsigned char *)hdr, 4);
12885
467k
    if (rv != SECSuccess)
12886
0
        return rv; /* err code already set. */
12887
12888
    /* Extra data to simulate a complete DTLS handshake fragment */
12889
467k
    if (IS_DTLS_1_OR_12(ss)) {
12890
        /* Sequence number */
12891
47.2k
        dtlsData[0] = MSB(dtlsSeq);
12892
47.2k
        dtlsData[1] = LSB(dtlsSeq);
12893
12894
        /* Fragment offset */
12895
47.2k
        dtlsData[2] = 0;
12896
47.2k
        dtlsData[3] = 0;
12897
47.2k
        dtlsData[4] = 0;
12898
12899
        /* Fragment length */
12900
47.2k
        dtlsData[5] = (PRUint8)(length >> 16);
12901
47.2k
        dtlsData[6] = (PRUint8)(length >> 8);
12902
47.2k
        dtlsData[7] = (PRUint8)(length);
12903
12904
47.2k
        rv = updateHashes(ss, (unsigned char *)dtlsData, sizeof(dtlsData));
12905
47.2k
        if (rv != SECSuccess)
12906
0
            return rv; /* err code already set. */
12907
47.2k
    }
12908
12909
    /* The message body */
12910
467k
    rv = updateHashes(ss, b, length);
12911
467k
    if (rv != SECSuccess)
12912
0
        return rv; /* err code already set. */
12913
12914
467k
    return SECSuccess;
12915
467k
}
12916
12917
SECStatus
12918
ssl_HashHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
12919
                         const PRUint8 *b, PRUint32 length)
12920
464k
{
12921
464k
    return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12922
464k
                                       b, length, ssl3_UpdateHandshakeHashes);
12923
464k
}
12924
12925
SECStatus
12926
ssl_HashHandshakeMessageDefault(sslSocket *ss, SSLHandshakeType ct,
12927
                                const PRUint8 *b, PRUint32 length)
12928
2.89k
{
12929
2.89k
    return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12930
2.89k
                                       b, length, ssl3_UpdateDefaultHandshakeHashes);
12931
2.89k
}
12932
SECStatus
12933
ssl_HashHandshakeMessageEchInner(sslSocket *ss, SSLHandshakeType ct,
12934
                                 const PRUint8 *b, PRUint32 length)
12935
674
{
12936
674
    return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12937
674
                                       b, length, ssl3_UpdateInnerHandshakeHashes);
12938
674
}
12939
12940
SECStatus
12941
ssl_HashPostHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
12942
                             const PRUint8 *b, PRUint32 length)
12943
0
{
12944
0
    return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12945
0
                                       b, length, ssl3_UpdatePostHandshakeHashes);
12946
0
}
12947
12948
/* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
12949
 * handshake message.
12950
 * Caller must hold Handshake and RecvBuf locks.
12951
 */
12952
SECStatus
12953
ssl3_HandleHandshakeMessage(sslSocket *ss, PRUint8 *b, PRUint32 length,
12954
                            PRBool endOfRecord)
12955
636k
{
12956
636k
    SECStatus rv = SECSuccess;
12957
636k
    PRUint16 epoch;
12958
12959
636k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12960
636k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12961
12962
636k
    SSL_TRC(30, ("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
12963
636k
                 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
12964
12965
    /* Start new handshake hashes when we start a new handshake. */
12966
636k
    if (ss->ssl3.hs.msg_type == ssl_hs_client_hello) {
12967
83.1k
        ssl3_RestartHandshakeHashes(ss);
12968
83.1k
    }
12969
636k
    switch (ss->ssl3.hs.msg_type) {
12970
43.2k
        case ssl_hs_hello_request:
12971
44.6k
        case ssl_hs_hello_verify_request:
12972
            /* We don't include hello_request and hello_verify_request messages
12973
             * in the handshake hashes */
12974
44.6k
            break;
12975
12976
        /* Defer hashing of these messages until the message handlers. */
12977
83.1k
        case ssl_hs_client_hello:
12978
150k
        case ssl_hs_server_hello:
12979
169k
        case ssl_hs_certificate_verify:
12980
265k
        case ssl_hs_finished:
12981
265k
            break;
12982
12983
326k
        default:
12984
326k
            if (!tls13_IsPostHandshake(ss)) {
12985
207k
                rv = ssl_HashHandshakeMessage(ss, ss->ssl3.hs.msg_type, b, length);
12986
207k
                if (rv != SECSuccess) {
12987
0
                    return SECFailure;
12988
0
                }
12989
207k
            }
12990
636k
    }
12991
12992
636k
    PORT_SetError(0); /* each message starts with no error. */
12993
12994
636k
    if (ss->ssl3.hs.ws == wait_certificate_status &&
12995
168
        ss->ssl3.hs.msg_type != ssl_hs_certificate_status) {
12996
        /* If we negotiated the certificate_status extension then we deferred
12997
         * certificate validation until we get the CertificateStatus messsage.
12998
         * But the CertificateStatus message is optional. If the server did
12999
         * not send it then we need to validate the certificate now. If the
13000
         * server does send the CertificateStatus message then we will
13001
         * authenticate the certificate in ssl3_HandleCertificateStatus.
13002
         */
13003
28
        rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
13004
28
        if (rv != SECSuccess) {
13005
            /* This can't block. */
13006
18
            PORT_Assert(PORT_GetError() != PR_WOULD_BLOCK_ERROR);
13007
18
            return SECFailure;
13008
18
        }
13009
28
    }
13010
13011
636k
    epoch = ss->ssl3.crSpec->epoch;
13012
636k
    switch (ss->ssl3.hs.msg_type) {
13013
83.1k
        case ssl_hs_client_hello:
13014
83.1k
            if (!ss->sec.isServer) {
13015
21
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13016
21
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
13017
21
                return SECFailure;
13018
21
            }
13019
83.1k
            rv = ssl3_HandleClientHello(ss, b, length);
13020
83.1k
            break;
13021
67.4k
        case ssl_hs_server_hello:
13022
67.4k
            if (ss->sec.isServer) {
13023
11
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13024
11
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
13025
11
                return SECFailure;
13026
11
            }
13027
67.4k
            rv = ssl3_HandleServerHello(ss, b, length);
13028
67.4k
            break;
13029
486k
        default:
13030
486k
            if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
13031
366k
                rv = ssl3_HandlePostHelloHandshakeMessage(ss, b, length);
13032
366k
            } else {
13033
120k
                rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length);
13034
120k
            }
13035
486k
            break;
13036
636k
    }
13037
636k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
13038
131k
        (epoch != ss->ssl3.crSpec->epoch) && !endOfRecord) {
13039
        /* If we changed read cipher states, there must not be any
13040
         * data in the input queue. */
13041
174
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13042
174
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
13043
174
        return SECFailure;
13044
174
    }
13045
    /* We consider the record to have been handled if SECSuccess or else WOULD_BLOCK is set
13046
     * Whoever set WOULD_BLOCK must handle any remaining actions required to finsih processing the record.
13047
     * e.g. by setting restartTarget.
13048
     */
13049
636k
    if (IS_DTLS(ss) && (rv == SECSuccess || (rv == SECFailure && PR_GetError() == PR_WOULD_BLOCK_ERROR))) {
13050
        /* Increment the expected sequence number */
13051
47.1k
        ss->ssl3.hs.recvMessageSeq++;
13052
47.1k
    }
13053
13054
    /* Taint the message so that it's easier to detect UAFs. */
13055
636k
    PORT_Memset(b, 'N', length);
13056
13057
636k
    return rv;
13058
636k
}
13059
13060
static SECStatus
13061
ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b,
13062
                                     PRUint32 length)
13063
366k
{
13064
366k
    SECStatus rv;
13065
366k
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
13066
13067
366k
    switch (ss->ssl3.hs.msg_type) {
13068
43.2k
        case ssl_hs_hello_request:
13069
43.2k
            if (length != 0) {
13070
63
                (void)ssl3_DecodeError(ss);
13071
63
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
13072
63
                return SECFailure;
13073
63
            }
13074
43.2k
            if (ss->sec.isServer) {
13075
22
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13076
22
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
13077
22
                return SECFailure;
13078
22
            }
13079
43.2k
            rv = ssl3_HandleHelloRequest(ss);
13080
43.2k
            break;
13081
13082
1.38k
        case ssl_hs_hello_verify_request:
13083
1.38k
            if (!IS_DTLS(ss) || ss->sec.isServer) {
13084
8
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13085
8
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
13086
8
                return SECFailure;
13087
8
            }
13088
1.38k
            rv = dtls_HandleHelloVerifyRequest(ss, b, length);
13089
1.38k
            break;
13090
83.5k
        case ssl_hs_certificate:
13091
83.5k
            rv = ssl3_HandleCertificate(ss, b, length);
13092
83.5k
            break;
13093
172
        case ssl_hs_certificate_status:
13094
172
            rv = ssl3_HandleCertificateStatus(ss, b, length);
13095
172
            break;
13096
7.51k
        case ssl_hs_server_key_exchange:
13097
7.51k
            if (ss->sec.isServer) {
13098
18
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13099
18
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
13100
18
                return SECFailure;
13101
18
            }
13102
7.49k
            rv = ssl3_HandleServerKeyExchange(ss, b, length);
13103
7.49k
            break;
13104
901
        case ssl_hs_certificate_request:
13105
901
            if (ss->sec.isServer) {
13106
15
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13107
15
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
13108
15
                return SECFailure;
13109
15
            }
13110
886
            rv = ssl3_HandleCertificateRequest(ss, b, length);
13111
886
            break;
13112
46.0k
        case ssl_hs_server_hello_done:
13113
46.0k
            if (length != 0) {
13114
69
                (void)ssl3_DecodeError(ss);
13115
69
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
13116
69
                return SECFailure;
13117
69
            }
13118
45.9k
            if (ss->sec.isServer) {
13119
9
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13120
9
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
13121
9
                return SECFailure;
13122
9
            }
13123
45.9k
            rv = ssl3_HandleServerHelloDone(ss);
13124
45.9k
            break;
13125
18.5k
        case ssl_hs_certificate_verify:
13126
18.5k
            if (!ss->sec.isServer) {
13127
4
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13128
4
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
13129
4
                return SECFailure;
13130
4
            }
13131
18.5k
            rv = ssl3_HandleCertificateVerify(ss, b, length);
13132
18.5k
            break;
13133
68.6k
        case ssl_hs_client_key_exchange:
13134
68.6k
            if (!ss->sec.isServer) {
13135
9
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13136
9
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
13137
9
                return SECFailure;
13138
9
            }
13139
68.6k
            rv = ssl3_HandleClientKeyExchange(ss, b, length);
13140
68.6k
            break;
13141
128
        case ssl_hs_new_session_ticket:
13142
128
            if (ss->sec.isServer) {
13143
8
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13144
8
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
13145
8
                return SECFailure;
13146
8
            }
13147
120
            rv = ssl3_HandleNewSessionTicket(ss, b, length);
13148
120
            break;
13149
95.6k
        case ssl_hs_finished:
13150
95.6k
            rv = ssl3_HandleFinished(ss, b, length);
13151
95.6k
            break;
13152
114
        default:
13153
114
            (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13154
114
            PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
13155
114
            rv = SECFailure;
13156
366k
    }
13157
13158
365k
    return rv;
13159
366k
}
13160
13161
/* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
13162
 * origBuf is the decrypted ssl record content.
13163
 * Caller must hold the handshake and RecvBuf locks.
13164
 */
13165
static SECStatus
13166
ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
13167
1.45M
{
13168
1.45M
    sslBuffer buf = *origBuf; /* Work from a copy. */
13169
1.45M
    SECStatus rv;
13170
13171
1.45M
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
13172
1.45M
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
13173
13174
4.17M
    while (buf.len > 0) {
13175
2.82M
        if (ss->ssl3.hs.header_bytes < 4) {
13176
2.32M
            PRUint8 t;
13177
2.32M
            t = *(buf.buf++);
13178
2.32M
            buf.len--;
13179
2.32M
            if (ss->ssl3.hs.header_bytes++ == 0)
13180
580k
                ss->ssl3.hs.msg_type = (SSLHandshakeType)t;
13181
1.74M
            else
13182
1.74M
                ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
13183
2.32M
            if (ss->ssl3.hs.header_bytes < 4)
13184
1.74M
                continue;
13185
13186
580k
#define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
13187
580k
            if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
13188
293
                (void)ssl3_DecodeError(ss);
13189
293
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
13190
293
                goto loser;
13191
293
            }
13192
579k
#undef MAX_HANDSHAKE_MSG_LEN
13193
13194
            /* If msg_len is zero, be sure we fall through,
13195
            ** even if buf.len is zero.
13196
            */
13197
579k
            if (ss->ssl3.hs.msg_len > 0)
13198
413k
                continue;
13199
579k
        }
13200
13201
        /*
13202
         * Header has been gathered and there is at least one byte of new
13203
         * data available for this message. If it can be done right out
13204
         * of the original buffer, then use it from there.
13205
         */
13206
667k
        if (ss->ssl3.hs.msg_body.len == 0 && buf.len >= ss->ssl3.hs.msg_len) {
13207
            /* handle it from input buffer */
13208
555k
            rv = ssl3_HandleHandshakeMessage(ss, buf.buf, ss->ssl3.hs.msg_len,
13209
555k
                                             buf.len == ss->ssl3.hs.msg_len);
13210
555k
            buf.buf += ss->ssl3.hs.msg_len;
13211
555k
            buf.len -= ss->ssl3.hs.msg_len;
13212
555k
            ss->ssl3.hs.msg_len = 0;
13213
555k
            ss->ssl3.hs.header_bytes = 0;
13214
555k
            if (rv != SECSuccess) {
13215
13.1k
                goto loser;
13216
13.1k
            }
13217
555k
        } else {
13218
            /* must be copied to msg_body and dealt with from there */
13219
111k
            unsigned int bytes;
13220
13221
111k
            PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
13222
111k
            bytes = PR_MIN(buf.len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
13223
13224
            /* Grow the buffer if needed */
13225
111k
            rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
13226
111k
            if (rv != SECSuccess) {
13227
                /* sslBuffer_Grow has set a memory error code. */
13228
0
                goto loser;
13229
0
            }
13230
13231
111k
            PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
13232
111k
                        buf.buf, bytes);
13233
111k
            ss->ssl3.hs.msg_body.len += bytes;
13234
111k
            buf.buf += bytes;
13235
111k
            buf.len -= bytes;
13236
13237
111k
            PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
13238
13239
            /* if we have a whole message, do it */
13240
111k
            if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
13241
23.1k
                rv = ssl3_HandleHandshakeMessage(
13242
23.1k
                    ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len,
13243
23.1k
                    buf.len == 0);
13244
23.1k
                ss->ssl3.hs.msg_body.len = 0;
13245
23.1k
                ss->ssl3.hs.msg_len = 0;
13246
23.1k
                ss->ssl3.hs.header_bytes = 0;
13247
23.1k
                if (rv != SECSuccess) {
13248
904
                    goto loser;
13249
904
                }
13250
88.5k
            } else {
13251
88.5k
                PORT_Assert(buf.len == 0);
13252
88.5k
                break;
13253
88.5k
            }
13254
111k
        }
13255
667k
    } /* end loop */
13256
13257
1.43M
    origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
13258
1.43M
    return SECSuccess;
13259
13260
14.3k
loser: {
13261
    /* Make sure to remove any data that was consumed. */
13262
14.3k
    unsigned int consumed = origBuf->len - buf.len;
13263
14.3k
    PORT_Assert(consumed == buf.buf - origBuf->buf);
13264
14.3k
    if (consumed > 0) {
13265
14.3k
        memmove(origBuf->buf, origBuf->buf + consumed, buf.len);
13266
14.3k
        origBuf->len = buf.len;
13267
14.3k
    }
13268
14.3k
}
13269
14.3k
    return SECFailure;
13270
1.45M
}
13271
13272
/* SECStatusToMask returns, in constant time, a mask value of all ones if
13273
 * rv == SECSuccess.  Otherwise it returns zero. */
13274
static unsigned int
13275
SECStatusToMask(SECStatus rv)
13276
196k
{
13277
196k
    return PORT_CT_EQ(rv, SECSuccess);
13278
196k
}
13279
13280
/* ssl_ConstantTimeGE returns 0xffffffff if a>=b and 0x00 otherwise. */
13281
static unsigned char
13282
ssl_ConstantTimeGE(unsigned int a, unsigned int b)
13283
2.98M
{
13284
2.98M
    return PORT_CT_GE(a, b);
13285
2.98M
}
13286
13287
/* ssl_ConstantTimeEQ returns 0xffffffff if a==b and 0x00 otherwise. */
13288
static unsigned char
13289
ssl_ConstantTimeEQ(unsigned char a, unsigned char b)
13290
16.8M
{
13291
16.8M
    return PORT_CT_EQ(a, b);
13292
16.8M
}
13293
13294
/* ssl_constantTimeSelect return a if mask is 0xFF and b if mask is 0x00 */
13295
static unsigned char
13296
ssl_constantTimeSelect(unsigned char mask, unsigned char a, unsigned char b)
13297
623k
{
13298
623k
    return (mask & a) | (~mask & b);
13299
623k
}
13300
13301
static SECStatus
13302
ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
13303
                          unsigned int blockSize,
13304
                          unsigned int macSize)
13305
0
{
13306
0
    unsigned int paddingLength, good;
13307
0
    const unsigned int overhead = 1 /* padding length byte */ + macSize;
13308
13309
    /* These lengths are all public so we can test them in non-constant
13310
     * time. */
13311
0
    if (overhead > plaintext->len) {
13312
0
        return SECFailure;
13313
0
    }
13314
13315
0
    paddingLength = plaintext->buf[plaintext->len - 1];
13316
    /* SSLv3 padding bytes are random and cannot be checked. */
13317
0
    good = PORT_CT_GE(plaintext->len, paddingLength + overhead);
13318
    /* SSLv3 requires that the padding is minimal. */
13319
0
    good &= PORT_CT_GE(blockSize, paddingLength + 1);
13320
0
    plaintext->len -= good & (paddingLength + 1);
13321
0
    return (good & SECSuccess) | (~good & SECFailure);
13322
0
}
Unexecuted instantiation: ssl3con.c:ssl_RemoveSSLv3CBCPadding
Unexecuted instantiation: ssl3con.c:ssl_RemoveSSLv3CBCPadding
13323
13324
SECStatus
13325
ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
13326
23.0k
{
13327
23.0k
    unsigned int paddingLength, good, toCheck, i;
13328
23.0k
    const unsigned int overhead = 1 /* padding length byte */ + macSize;
13329
13330
    /* These lengths are all public so we can test them in non-constant
13331
     * time. */
13332
23.0k
    if (overhead > plaintext->len) {
13333
0
        return SECFailure;
13334
0
    }
13335
13336
23.0k
    paddingLength = plaintext->buf[plaintext->len - 1];
13337
23.0k
    good = PORT_CT_GE(plaintext->len, paddingLength + overhead);
13338
13339
    /* The padding consists of a length byte at the end of the record and then
13340
     * that many bytes of padding, all with the same value as the length byte.
13341
     * Thus, with the length byte included, there are paddingLength+1 bytes of
13342
     * padding.
13343
     *
13344
     * We can't check just |paddingLength+1| bytes because that leaks
13345
     * decrypted information. Therefore we always have to check the maximum
13346
     * amount of padding possible. (Again, the length of the record is
13347
     * public information so we can use it.) */
13348
23.0k
    toCheck = 256; /* maximum amount of padding + 1. */
13349
23.0k
    if (toCheck > plaintext->len) {
13350
21.4k
        toCheck = plaintext->len;
13351
21.4k
    }
13352
13353
1.17M
    for (i = 0; i < toCheck; i++) {
13354
        /* If i <= paddingLength then the MSB of t is zero and mask is
13355
         * 0xff.  Otherwise, mask is 0. */
13356
1.15M
        unsigned char mask = PORT_CT_LE(i, paddingLength);
13357
1.15M
        unsigned char b = plaintext->buf[plaintext->len - 1 - i];
13358
        /* The final |paddingLength+1| bytes should all have the value
13359
         * |paddingLength|. Therefore the XOR should be zero. */
13360
1.15M
        good &= ~(mask & (paddingLength ^ b));
13361
1.15M
    }
13362
13363
    /* If any of the final |paddingLength+1| bytes had the wrong value,
13364
     * one or more of the lower eight bits of |good| will be cleared. We
13365
     * AND the bottom 8 bits together and duplicate the result to all the
13366
     * bits. */
13367
23.0k
    good &= good >> 4;
13368
23.0k
    good &= good >> 2;
13369
23.0k
    good &= good >> 1;
13370
23.0k
    good <<= sizeof(good) * 8 - 1;
13371
23.0k
    good = PORT_CT_DUPLICATE_MSB_TO_ALL(good);
13372
13373
23.0k
    plaintext->len -= good & (paddingLength + 1);
13374
23.0k
    return (good & SECSuccess) | (~good & SECFailure);
13375
23.0k
}
13376
13377
/* On entry:
13378
 *   originalLength >= macSize
13379
 *   macSize <= MAX_MAC_LENGTH
13380
 *   plaintext->len >= macSize
13381
 */
13382
static void
13383
ssl_CBCExtractMAC(sslBuffer *plaintext,
13384
                  unsigned int originalLength,
13385
                  PRUint8 *out,
13386
                  unsigned int macSize)
13387
23.0k
{
13388
23.0k
    unsigned char rotatedMac[MAX_MAC_LENGTH];
13389
    /* macEnd is the index of |plaintext->buf| just after the end of the
13390
     * MAC. */
13391
23.0k
    unsigned macEnd = plaintext->len;
13392
23.0k
    unsigned macStart = macEnd - macSize;
13393
    /* scanStart contains the number of bytes that we can ignore because
13394
     * the MAC's position can only vary by 255 bytes. */
13395
23.0k
    unsigned scanStart = 0;
13396
23.0k
    unsigned i, j;
13397
23.0k
    unsigned char rotateOffset;
13398
13399
23.0k
    if (originalLength > macSize + 255 + 1) {
13400
1.24k
        scanStart = originalLength - (macSize + 255 + 1);
13401
1.24k
    }
13402
13403
    /* We want to compute
13404
     * rotateOffset = (macStart - scanStart) % macSize
13405
     * But the time to compute this varies based on the amount of padding. Thus
13406
     * we explicitely handle all mac sizes with (hopefully) constant time modulo
13407
     * using Barrett reduction:
13408
     *  q := (rotateOffset * m) >> k
13409
     *  rotateOffset -= q * n
13410
     *  if (n <= rotateOffset) rotateOffset -= n
13411
     */
13412
23.0k
    rotateOffset = macStart - scanStart;
13413
    /* rotateOffset < 255 + 1 + 48 = 304 */
13414
23.0k
    if (macSize == 16) {
13415
0
        rotateOffset &= 15;
13416
23.0k
    } else if (macSize == 20) {
13417
        /*
13418
         * Correctness: rotateOffset * ( 1/20 - 25/2^9 ) < 1
13419
         *              with rotateOffset <= 853
13420
         */
13421
17.0k
        unsigned q = (rotateOffset * 25) >> 9;
13422
17.0k
        rotateOffset -= q * 20;
13423
17.0k
        rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 20),
13424
17.0k
                                               20, 0);
13425
17.0k
    } else if (macSize == 32) {
13426
2.96k
        rotateOffset &= 31;
13427
3.02k
    } else if (macSize == 48) {
13428
        /*
13429
         * Correctness: rotateOffset * ( 1/48 - 10/2^9 ) < 1
13430
         *              with rotateOffset < 768
13431
         */
13432
3.02k
        unsigned q = (rotateOffset * 10) >> 9;
13433
3.02k
        rotateOffset -= q * 48;
13434
3.02k
        rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 48),
13435
3.02k
                                               48, 0);
13436
3.02k
    } else {
13437
        /*
13438
         * SHA384 (macSize == 48) is the largest we support. We should never
13439
         * get here.
13440
         */
13441
0
        PORT_Assert(0);
13442
0
        rotateOffset = rotateOffset % macSize;
13443
0
    }
13444
13445
23.0k
    memset(rotatedMac, 0, macSize);
13446
88.4k
    for (i = scanStart; i < originalLength;) {
13447
1.24M
        for (j = 0; j < macSize && i < originalLength; i++, j++) {
13448
1.18M
            unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
13449
1.18M
            unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
13450
1.18M
            unsigned char b = 0;
13451
1.18M
            b = plaintext->buf[i];
13452
1.18M
            rotatedMac[j] |= b & macStarted & ~macEnded;
13453
1.18M
        }
13454
65.4k
    }
13455
13456
    /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
13457
     * we could line-align |rotatedMac| and rotate in place. */
13458
23.0k
    memset(out, 0, macSize);
13459
23.0k
    rotateOffset = macSize - rotateOffset;
13460
23.0k
    rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
13461
23.0k
                                          0, rotateOffset);
13462
603k
    for (i = 0; i < macSize; i++) {
13463
17.3M
        for (j = 0; j < macSize; j++) {
13464
16.8M
            out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ(j, rotateOffset);
13465
16.8M
        }
13466
580k
        rotateOffset++;
13467
580k
        rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
13468
580k
                                              0, rotateOffset);
13469
580k
    }
13470
23.0k
}
Unexecuted instantiation: ssl3con.c:ssl_CBCExtractMAC
ssl3con.c:ssl_CBCExtractMAC
Line
Count
Source
13387
23.0k
{
13388
23.0k
    unsigned char rotatedMac[MAX_MAC_LENGTH];
13389
    /* macEnd is the index of |plaintext->buf| just after the end of the
13390
     * MAC. */
13391
23.0k
    unsigned macEnd = plaintext->len;
13392
23.0k
    unsigned macStart = macEnd - macSize;
13393
    /* scanStart contains the number of bytes that we can ignore because
13394
     * the MAC's position can only vary by 255 bytes. */
13395
23.0k
    unsigned scanStart = 0;
13396
23.0k
    unsigned i, j;
13397
23.0k
    unsigned char rotateOffset;
13398
13399
23.0k
    if (originalLength > macSize + 255 + 1) {
13400
1.24k
        scanStart = originalLength - (macSize + 255 + 1);
13401
1.24k
    }
13402
13403
    /* We want to compute
13404
     * rotateOffset = (macStart - scanStart) % macSize
13405
     * But the time to compute this varies based on the amount of padding. Thus
13406
     * we explicitely handle all mac sizes with (hopefully) constant time modulo
13407
     * using Barrett reduction:
13408
     *  q := (rotateOffset * m) >> k
13409
     *  rotateOffset -= q * n
13410
     *  if (n <= rotateOffset) rotateOffset -= n
13411
     */
13412
23.0k
    rotateOffset = macStart - scanStart;
13413
    /* rotateOffset < 255 + 1 + 48 = 304 */
13414
23.0k
    if (macSize == 16) {
13415
0
        rotateOffset &= 15;
13416
23.0k
    } else if (macSize == 20) {
13417
        /*
13418
         * Correctness: rotateOffset * ( 1/20 - 25/2^9 ) < 1
13419
         *              with rotateOffset <= 853
13420
         */
13421
17.0k
        unsigned q = (rotateOffset * 25) >> 9;
13422
17.0k
        rotateOffset -= q * 20;
13423
17.0k
        rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 20),
13424
17.0k
                                               20, 0);
13425
17.0k
    } else if (macSize == 32) {
13426
2.96k
        rotateOffset &= 31;
13427
3.02k
    } else if (macSize == 48) {
13428
        /*
13429
         * Correctness: rotateOffset * ( 1/48 - 10/2^9 ) < 1
13430
         *              with rotateOffset < 768
13431
         */
13432
3.02k
        unsigned q = (rotateOffset * 10) >> 9;
13433
3.02k
        rotateOffset -= q * 48;
13434
3.02k
        rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 48),
13435
3.02k
                                               48, 0);
13436
3.02k
    } else {
13437
        /*
13438
         * SHA384 (macSize == 48) is the largest we support. We should never
13439
         * get here.
13440
         */
13441
0
        PORT_Assert(0);
13442
0
        rotateOffset = rotateOffset % macSize;
13443
0
    }
13444
13445
23.0k
    memset(rotatedMac, 0, macSize);
13446
88.4k
    for (i = scanStart; i < originalLength;) {
13447
1.24M
        for (j = 0; j < macSize && i < originalLength; i++, j++) {
13448
1.18M
            unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
13449
1.18M
            unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
13450
1.18M
            unsigned char b = 0;
13451
1.18M
            b = plaintext->buf[i];
13452
1.18M
            rotatedMac[j] |= b & macStarted & ~macEnded;
13453
1.18M
        }
13454
65.4k
    }
13455
13456
    /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
13457
     * we could line-align |rotatedMac| and rotate in place. */
13458
23.0k
    memset(out, 0, macSize);
13459
23.0k
    rotateOffset = macSize - rotateOffset;
13460
23.0k
    rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
13461
23.0k
                                          0, rotateOffset);
13462
603k
    for (i = 0; i < macSize; i++) {
13463
17.3M
        for (j = 0; j < macSize; j++) {
13464
16.8M
            out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ(j, rotateOffset);
13465
16.8M
        }
13466
580k
        rotateOffset++;
13467
580k
        rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
13468
580k
                                              0, rotateOffset);
13469
580k
    }
13470
23.0k
}
13471
13472
/* MAX_EXPANSION is the amount by which a record might plausibly be expanded
13473
 * when protected.  It's the worst case estimate, so the sum of block cipher
13474
 * padding (up to 256 octets), HMAC (48 octets for SHA-384), and IV (16
13475
 * octets for AES). */
13476
152k
#define MAX_EXPANSION (256 + 48 + 16)
13477
13478
/* Unprotect an SSL3 record and leave the result in plaintext.
13479
 *
13480
 * If SECFailure is returned, we:
13481
 * 1. Set |*alert| to the alert to be sent.
13482
 * 2. Call PORT_SetError() with an appropriate code.
13483
 *
13484
 * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
13485
 * Therefore, we MUST not call SSL3_SendAlert().
13486
 *
13487
 */
13488
static SECStatus
13489
ssl3_UnprotectRecord(sslSocket *ss,
13490
                     ssl3CipherSpec *spec,
13491
                     SSL3Ciphertext *cText, sslBuffer *plaintext,
13492
                     SSL3AlertDescription *alert)
13493
154k
{
13494
154k
    const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
13495
154k
    PRBool isTLS;
13496
154k
    unsigned int good;
13497
154k
    unsigned int ivLen = 0;
13498
154k
    SSLContentType rType;
13499
154k
    SSL3ProtocolVersion rVersion;
13500
154k
    unsigned int minLength;
13501
154k
    unsigned int originalLen = 0;
13502
154k
    PRUint8 headerBuf[13];
13503
154k
    sslBuffer header = SSL_BUFFER(headerBuf);
13504
154k
    PRUint8 hash[MAX_MAC_LENGTH];
13505
154k
    PRUint8 givenHashBuf[MAX_MAC_LENGTH];
13506
154k
    PRUint8 *givenHash;
13507
154k
    unsigned int hashBytes = MAX_MAC_LENGTH + 1;
13508
154k
    SECStatus rv;
13509
13510
154k
    PORT_Assert(spec->direction == ssl_secret_read);
13511
13512
154k
    good = ~0U;
13513
154k
    minLength = spec->macDef->mac_size;
13514
154k
    if (cipher_def->type == type_block) {
13515
        /* CBC records have a padding length byte at the end. */
13516
24.9k
        minLength++;
13517
24.9k
        if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
13518
            /* With >= TLS 1.1, CBC records have an explicit IV. */
13519
24.7k
            minLength += cipher_def->iv_size;
13520
24.7k
        }
13521
129k
    } else if (cipher_def->type == type_aead) {
13522
1.66k
        minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
13523
1.66k
    }
13524
13525
    /* We can perform this test in variable time because the record's total
13526
     * length and the ciphersuite are both public knowledge. */
13527
154k
    if (cText->buf->len < minLength) {
13528
2.74k
        goto decrypt_loser;
13529
2.74k
    }
13530
13531
152k
    if (cipher_def->type == type_block &&
13532
23.7k
        spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
13533
        /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
13534
         * "The receiver decrypts the entire GenericBlockCipher structure and
13535
         * then discards the first cipher block corresponding to the IV
13536
         * component." Instead, we decrypt the first cipher block and then
13537
         * discard it before decrypting the rest.
13538
         */
13539
23.5k
        PRUint8 iv[MAX_IV_LENGTH];
13540
23.5k
        unsigned int decoded;
13541
13542
23.5k
        ivLen = cipher_def->iv_size;
13543
23.5k
        if (ivLen < 8 || ivLen > sizeof(iv)) {
13544
0
            *alert = internal_error;
13545
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
13546
0
            return SECFailure;
13547
0
        }
13548
13549
23.5k
        PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
13550
13551
        /* The decryption result is garbage, but since we just throw away
13552
         * the block it doesn't matter.  The decryption of the next block
13553
         * depends only on the ciphertext of the IV block.
13554
         */
13555
23.5k
        rv = spec->cipher(spec->cipherContext, iv, &decoded,
13556
23.5k
                          sizeof(iv), cText->buf->buf, ivLen);
13557
13558
23.5k
        good &= SECStatusToMask(rv);
13559
23.5k
    }
13560
13561
152k
    PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
13562
152k
                   cText->buf->len - ivLen));
13563
13564
    /* Check if the ciphertext can be valid if we assume maximum plaintext and
13565
     * add the maximum possible ciphersuite expansion.
13566
     * This way we detect overlong plaintexts/padding before decryption.
13567
     * This check enforces size limitations more strict than the RFC.
13568
     * [RFC5246, Section 6.2.3] */
13569
152k
    if (cText->buf->len > (spec->recordSizeLimit + MAX_EXPANSION)) {
13570
221
        *alert = record_overflow;
13571
221
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13572
221
        return SECFailure;
13573
221
    }
13574
13575
151k
    isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
13576
151k
    rType = (SSLContentType)cText->hdr[0];
13577
151k
    rVersion = ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
13578
151k
               (SSL3ProtocolVersion)cText->hdr[2];
13579
151k
    if (cipher_def->type == type_aead) {
13580
        /* XXX For many AEAD ciphers, the plaintext is shorter than the
13581
         * ciphertext by a fixed byte count, but it is not true in general.
13582
         * Each AEAD cipher should provide a function that returns the
13583
         * plaintext length for a given ciphertext. */
13584
1.14k
        const unsigned int explicitNonceLen = cipher_def->explicit_nonce_size;
13585
1.14k
        const unsigned int tagLen = cipher_def->tag_size;
13586
1.14k
        unsigned int nonceLen = explicitNonceLen;
13587
1.14k
        unsigned int decryptedLen = cText->buf->len - nonceLen - tagLen;
13588
        /* even though read doesn't return and IV, we still need a space to put
13589
         * the combined iv/nonce n the gcm 1.2 case*/
13590
1.14k
        unsigned char ivOut[MAX_IV_LENGTH];
13591
1.14k
        unsigned char *iv = NULL;
13592
1.14k
        unsigned char *nonce = NULL;
13593
13594
1.14k
        ivLen = cipher_def->iv_size;
13595
13596
1.14k
        rv = ssl3_BuildRecordPseudoHeader(
13597
1.14k
            spec->epoch, cText->seqNum,
13598
1.14k
            rType, isTLS, rVersion, IS_DTLS(ss), decryptedLen, &header, spec->version);
13599
1.14k
        PORT_Assert(rv == SECSuccess);
13600
13601
        /* build the iv */
13602
1.14k
        if (explicitNonceLen == 0) {
13603
693
            nonceLen = sizeof(cText->seqNum);
13604
693
            iv = spec->keyMaterial.iv;
13605
693
            nonce = SSL_BUFFER_BASE(&header);
13606
693
        } else {
13607
450
            PORT_Memcpy(ivOut, spec->keyMaterial.iv, ivLen);
13608
450
            PORT_Memset(ivOut + ivLen, 0, explicitNonceLen);
13609
450
            iv = ivOut;
13610
450
            nonce = cText->buf->buf;
13611
450
            nonceLen = explicitNonceLen;
13612
450
        }
13613
1.14k
        rv = tls13_AEAD(spec->cipherContext, PR_TRUE,
13614
1.14k
                        CKG_NO_GENERATE, 0,       /* iv generator params
13615
                                                   * (not used in decrypt)*/
13616
1.14k
                        iv,                       /* iv in */
13617
1.14k
                        NULL,                     /* iv out */
13618
1.14k
                        ivLen + explicitNonceLen, /* full iv length */
13619
1.14k
                        nonce, nonceLen,          /* nonce in */
13620
1.14k
                        SSL_BUFFER_BASE(&header), /* aad */
13621
1.14k
                        SSL_BUFFER_LEN(&header),  /* aadlen */
13622
1.14k
                        plaintext->buf,           /* output  */
13623
1.14k
                        &plaintext->len,          /* out len */
13624
1.14k
                        plaintext->space,         /* max out */
13625
1.14k
                        tagLen,
13626
1.14k
                        cText->buf->buf + explicitNonceLen,  /* input */
13627
1.14k
                        cText->buf->len - explicitNonceLen); /* input len */
13628
1.14k
        if (rv != SECSuccess) {
13629
1.14k
            good = 0;
13630
1.14k
        }
13631
150k
    } else {
13632
150k
        if (cipher_def->type == type_block &&
13633
23.6k
            ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
13634
682
            goto decrypt_loser;
13635
682
        }
13636
13637
        /* decrypt from cText buf to plaintext. */
13638
150k
        rv = spec->cipher(
13639
150k
            spec->cipherContext, plaintext->buf, &plaintext->len,
13640
150k
            plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
13641
150k
        if (rv != SECSuccess) {
13642
0
            goto decrypt_loser;
13643
0
        }
13644
13645
150k
        PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
13646
13647
150k
        originalLen = plaintext->len;
13648
13649
        /* If it's a block cipher, check and strip the padding. */
13650
150k
        if (cipher_def->type == type_block) {
13651
23.0k
            const unsigned int blockSize = cipher_def->block_size;
13652
23.0k
            const unsigned int macSize = spec->macDef->mac_size;
13653
13654
23.0k
            if (!isTLS) {
13655
0
                good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
13656
0
                    plaintext, blockSize, macSize));
13657
23.0k
            } else {
13658
23.0k
                good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
13659
23.0k
                    plaintext, macSize));
13660
23.0k
            }
13661
23.0k
        }
13662
13663
        /* compute the MAC */
13664
150k
        rv = ssl3_BuildRecordPseudoHeader(
13665
150k
            spec->epoch, cText->seqNum,
13666
150k
            rType, isTLS, rVersion, IS_DTLS(ss),
13667
150k
            plaintext->len - spec->macDef->mac_size, &header, spec->version);
13668
150k
        PORT_Assert(rv == SECSuccess);
13669
150k
        if (cipher_def->type == type_block) {
13670
23.0k
            rv = ssl3_ComputeRecordMACConstantTime(
13671
23.0k
                spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
13672
23.0k
                plaintext->buf, plaintext->len, originalLen,
13673
23.0k
                hash, &hashBytes);
13674
13675
23.0k
            ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
13676
23.0k
                              spec->macDef->mac_size);
13677
23.0k
            givenHash = givenHashBuf;
13678
13679
            /* plaintext->len will always have enough space to remove the MAC
13680
             * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
13681
             * plaintext->len if the result has enough space for the MAC and we
13682
             * tested the unadjusted size against minLength, above. */
13683
23.0k
            plaintext->len -= spec->macDef->mac_size;
13684
127k
        } else {
13685
            /* This is safe because we checked the minLength above. */
13686
127k
            plaintext->len -= spec->macDef->mac_size;
13687
13688
127k
            rv = ssl3_ComputeRecordMAC(
13689
127k
                spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
13690
127k
                plaintext->buf, plaintext->len, hash, &hashBytes);
13691
13692
            /* We can read the MAC directly from the record because its location
13693
             * is public when a stream cipher is used. */
13694
127k
            givenHash = plaintext->buf + plaintext->len;
13695
127k
        }
13696
13697
150k
        good &= SECStatusToMask(rv);
13698
13699
150k
        if (hashBytes != (unsigned)spec->macDef->mac_size ||
13700
150k
            NSS_SecureMemcmp(givenHash, hash, spec->macDef->mac_size) != 0) {
13701
            /* We're allowed to leak whether or not the MAC check was correct */
13702
53.0k
            good = 0;
13703
53.0k
        }
13704
150k
    }
13705
13706
151k
    if (good == 0) {
13707
57.5k
    decrypt_loser:
13708
        /* always log mac error, in case attacker can read server logs. */
13709
57.5k
        PORT_SetError(SSL_ERROR_BAD_MAC_READ);
13710
57.5k
        *alert = bad_record_mac;
13711
57.5k
        return SECFailure;
13712
54.1k
    }
13713
97.1k
    return SECSuccess;
13714
151k
}
Unexecuted instantiation: ssl3con.c:ssl3_UnprotectRecord
ssl3con.c:ssl3_UnprotectRecord
Line
Count
Source
13493
154k
{
13494
154k
    const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
13495
154k
    PRBool isTLS;
13496
154k
    unsigned int good;
13497
154k
    unsigned int ivLen = 0;
13498
154k
    SSLContentType rType;
13499
154k
    SSL3ProtocolVersion rVersion;
13500
154k
    unsigned int minLength;
13501
154k
    unsigned int originalLen = 0;
13502
154k
    PRUint8 headerBuf[13];
13503
154k
    sslBuffer header = SSL_BUFFER(headerBuf);
13504
154k
    PRUint8 hash[MAX_MAC_LENGTH];
13505
154k
    PRUint8 givenHashBuf[MAX_MAC_LENGTH];
13506
154k
    PRUint8 *givenHash;
13507
154k
    unsigned int hashBytes = MAX_MAC_LENGTH + 1;
13508
154k
    SECStatus rv;
13509
13510
154k
    PORT_Assert(spec->direction == ssl_secret_read);
13511
13512
154k
    good = ~0U;
13513
154k
    minLength = spec->macDef->mac_size;
13514
154k
    if (cipher_def->type == type_block) {
13515
        /* CBC records have a padding length byte at the end. */
13516
24.9k
        minLength++;
13517
24.9k
        if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
13518
            /* With >= TLS 1.1, CBC records have an explicit IV. */
13519
24.7k
            minLength += cipher_def->iv_size;
13520
24.7k
        }
13521
129k
    } else if (cipher_def->type == type_aead) {
13522
1.66k
        minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
13523
1.66k
    }
13524
13525
    /* We can perform this test in variable time because the record's total
13526
     * length and the ciphersuite are both public knowledge. */
13527
154k
    if (cText->buf->len < minLength) {
13528
2.74k
        goto decrypt_loser;
13529
2.74k
    }
13530
13531
152k
    if (cipher_def->type == type_block &&
13532
23.7k
        spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
13533
        /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
13534
         * "The receiver decrypts the entire GenericBlockCipher structure and
13535
         * then discards the first cipher block corresponding to the IV
13536
         * component." Instead, we decrypt the first cipher block and then
13537
         * discard it before decrypting the rest.
13538
         */
13539
23.5k
        PRUint8 iv[MAX_IV_LENGTH];
13540
23.5k
        unsigned int decoded;
13541
13542
23.5k
        ivLen = cipher_def->iv_size;
13543
23.5k
        if (ivLen < 8 || ivLen > sizeof(iv)) {
13544
0
            *alert = internal_error;
13545
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
13546
0
            return SECFailure;
13547
0
        }
13548
13549
23.5k
        PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
13550
13551
        /* The decryption result is garbage, but since we just throw away
13552
         * the block it doesn't matter.  The decryption of the next block
13553
         * depends only on the ciphertext of the IV block.
13554
         */
13555
23.5k
        rv = spec->cipher(spec->cipherContext, iv, &decoded,
13556
23.5k
                          sizeof(iv), cText->buf->buf, ivLen);
13557
13558
23.5k
        good &= SECStatusToMask(rv);
13559
23.5k
    }
13560
13561
152k
    PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
13562
152k
                   cText->buf->len - ivLen));
13563
13564
    /* Check if the ciphertext can be valid if we assume maximum plaintext and
13565
     * add the maximum possible ciphersuite expansion.
13566
     * This way we detect overlong plaintexts/padding before decryption.
13567
     * This check enforces size limitations more strict than the RFC.
13568
     * [RFC5246, Section 6.2.3] */
13569
152k
    if (cText->buf->len > (spec->recordSizeLimit + MAX_EXPANSION)) {
13570
221
        *alert = record_overflow;
13571
221
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13572
221
        return SECFailure;
13573
221
    }
13574
13575
151k
    isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
13576
151k
    rType = (SSLContentType)cText->hdr[0];
13577
151k
    rVersion = ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
13578
151k
               (SSL3ProtocolVersion)cText->hdr[2];
13579
151k
    if (cipher_def->type == type_aead) {
13580
        /* XXX For many AEAD ciphers, the plaintext is shorter than the
13581
         * ciphertext by a fixed byte count, but it is not true in general.
13582
         * Each AEAD cipher should provide a function that returns the
13583
         * plaintext length for a given ciphertext. */
13584
1.14k
        const unsigned int explicitNonceLen = cipher_def->explicit_nonce_size;
13585
1.14k
        const unsigned int tagLen = cipher_def->tag_size;
13586
1.14k
        unsigned int nonceLen = explicitNonceLen;
13587
1.14k
        unsigned int decryptedLen = cText->buf->len - nonceLen - tagLen;
13588
        /* even though read doesn't return and IV, we still need a space to put
13589
         * the combined iv/nonce n the gcm 1.2 case*/
13590
1.14k
        unsigned char ivOut[MAX_IV_LENGTH];
13591
1.14k
        unsigned char *iv = NULL;
13592
1.14k
        unsigned char *nonce = NULL;
13593
13594
1.14k
        ivLen = cipher_def->iv_size;
13595
13596
1.14k
        rv = ssl3_BuildRecordPseudoHeader(
13597
1.14k
            spec->epoch, cText->seqNum,
13598
1.14k
            rType, isTLS, rVersion, IS_DTLS(ss), decryptedLen, &header, spec->version);
13599
1.14k
        PORT_Assert(rv == SECSuccess);
13600
13601
        /* build the iv */
13602
1.14k
        if (explicitNonceLen == 0) {
13603
693
            nonceLen = sizeof(cText->seqNum);
13604
693
            iv = spec->keyMaterial.iv;
13605
693
            nonce = SSL_BUFFER_BASE(&header);
13606
693
        } else {
13607
450
            PORT_Memcpy(ivOut, spec->keyMaterial.iv, ivLen);
13608
450
            PORT_Memset(ivOut + ivLen, 0, explicitNonceLen);
13609
450
            iv = ivOut;
13610
450
            nonce = cText->buf->buf;
13611
450
            nonceLen = explicitNonceLen;
13612
450
        }
13613
1.14k
        rv = tls13_AEAD(spec->cipherContext, PR_TRUE,
13614
1.14k
                        CKG_NO_GENERATE, 0,       /* iv generator params
13615
                                                   * (not used in decrypt)*/
13616
1.14k
                        iv,                       /* iv in */
13617
1.14k
                        NULL,                     /* iv out */
13618
1.14k
                        ivLen + explicitNonceLen, /* full iv length */
13619
1.14k
                        nonce, nonceLen,          /* nonce in */
13620
1.14k
                        SSL_BUFFER_BASE(&header), /* aad */
13621
1.14k
                        SSL_BUFFER_LEN(&header),  /* aadlen */
13622
1.14k
                        plaintext->buf,           /* output  */
13623
1.14k
                        &plaintext->len,          /* out len */
13624
1.14k
                        plaintext->space,         /* max out */
13625
1.14k
                        tagLen,
13626
1.14k
                        cText->buf->buf + explicitNonceLen,  /* input */
13627
1.14k
                        cText->buf->len - explicitNonceLen); /* input len */
13628
1.14k
        if (rv != SECSuccess) {
13629
1.14k
            good = 0;
13630
1.14k
        }
13631
150k
    } else {
13632
150k
        if (cipher_def->type == type_block &&
13633
23.6k
            ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
13634
682
            goto decrypt_loser;
13635
682
        }
13636
13637
        /* decrypt from cText buf to plaintext. */
13638
150k
        rv = spec->cipher(
13639
150k
            spec->cipherContext, plaintext->buf, &plaintext->len,
13640
150k
            plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
13641
150k
        if (rv != SECSuccess) {
13642
0
            goto decrypt_loser;
13643
0
        }
13644
13645
150k
        PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
13646
13647
150k
        originalLen = plaintext->len;
13648
13649
        /* If it's a block cipher, check and strip the padding. */
13650
150k
        if (cipher_def->type == type_block) {
13651
23.0k
            const unsigned int blockSize = cipher_def->block_size;
13652
23.0k
            const unsigned int macSize = spec->macDef->mac_size;
13653
13654
23.0k
            if (!isTLS) {
13655
0
                good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
13656
0
                    plaintext, blockSize, macSize));
13657
23.0k
            } else {
13658
23.0k
                good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
13659
23.0k
                    plaintext, macSize));
13660
23.0k
            }
13661
23.0k
        }
13662
13663
        /* compute the MAC */
13664
150k
        rv = ssl3_BuildRecordPseudoHeader(
13665
150k
            spec->epoch, cText->seqNum,
13666
150k
            rType, isTLS, rVersion, IS_DTLS(ss),
13667
150k
            plaintext->len - spec->macDef->mac_size, &header, spec->version);
13668
150k
        PORT_Assert(rv == SECSuccess);
13669
150k
        if (cipher_def->type == type_block) {
13670
23.0k
            rv = ssl3_ComputeRecordMACConstantTime(
13671
23.0k
                spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
13672
23.0k
                plaintext->buf, plaintext->len, originalLen,
13673
23.0k
                hash, &hashBytes);
13674
13675
23.0k
            ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
13676
23.0k
                              spec->macDef->mac_size);
13677
23.0k
            givenHash = givenHashBuf;
13678
13679
            /* plaintext->len will always have enough space to remove the MAC
13680
             * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
13681
             * plaintext->len if the result has enough space for the MAC and we
13682
             * tested the unadjusted size against minLength, above. */
13683
23.0k
            plaintext->len -= spec->macDef->mac_size;
13684
127k
        } else {
13685
            /* This is safe because we checked the minLength above. */
13686
127k
            plaintext->len -= spec->macDef->mac_size;
13687
13688
127k
            rv = ssl3_ComputeRecordMAC(
13689
127k
                spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
13690
127k
                plaintext->buf, plaintext->len, hash, &hashBytes);
13691
13692
            /* We can read the MAC directly from the record because its location
13693
             * is public when a stream cipher is used. */
13694
127k
            givenHash = plaintext->buf + plaintext->len;
13695
127k
        }
13696
13697
150k
        good &= SECStatusToMask(rv);
13698
13699
150k
        if (hashBytes != (unsigned)spec->macDef->mac_size ||
13700
150k
            NSS_SecureMemcmp(givenHash, hash, spec->macDef->mac_size) != 0) {
13701
            /* We're allowed to leak whether or not the MAC check was correct */
13702
53.0k
            good = 0;
13703
53.0k
        }
13704
150k
    }
13705
13706
151k
    if (good == 0) {
13707
57.5k
    decrypt_loser:
13708
        /* always log mac error, in case attacker can read server logs. */
13709
57.5k
        PORT_SetError(SSL_ERROR_BAD_MAC_READ);
13710
57.5k
        *alert = bad_record_mac;
13711
57.5k
        return SECFailure;
13712
54.1k
    }
13713
97.1k
    return SECSuccess;
13714
151k
}
13715
13716
SECStatus
13717
ssl3_HandleNonApplicationData(sslSocket *ss, SSLContentType rType,
13718
                              DTLSEpoch epoch, sslSequenceNumber seqNum,
13719
                              sslBuffer *databuf)
13720
1.67M
{
13721
1.67M
    SECStatus rv;
13722
13723
    /* check for Token Presence */
13724
1.67M
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13725
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13726
0
        return SECFailure;
13727
0
    }
13728
13729
1.67M
    ssl_GetSSL3HandshakeLock(ss);
13730
13731
    /* All the functions called in this switch MUST set error code if
13732
    ** they return SECFailure.
13733
    */
13734
1.67M
    switch (rType) {
13735
99.6k
        case ssl_ct_change_cipher_spec:
13736
99.6k
            rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
13737
99.6k
            break;
13738
69.0k
        case ssl_ct_alert:
13739
69.0k
            rv = ssl3_HandleAlert(ss, databuf);
13740
69.0k
            break;
13741
1.50M
        case ssl_ct_handshake:
13742
1.50M
            if (!IS_DTLS(ss)) {
13743
1.45M
                rv = ssl3_HandleHandshake(ss, databuf);
13744
1.45M
            } else {
13745
50.3k
                rv = dtls_HandleHandshake(ss, epoch, seqNum, databuf);
13746
50.3k
            }
13747
1.50M
            break;
13748
2.05k
        case ssl_ct_ack:
13749
2.05k
            if (IS_DTLS(ss) && tls13_MaybeTls13(ss)) {
13750
2.00k
                rv = dtls13_HandleAck(ss, databuf);
13751
2.00k
                break;
13752
2.00k
            }
13753
        /* Fall through. */
13754
520
        default:
13755
            /* If a TLS implementation receives an unexpected record type,
13756
             * it MUST terminate the connection with an "unexpected_message"
13757
             * alert [RFC8446, Section 5].
13758
             *
13759
             * For TLS 1.3 the outer content type is checked before in
13760
             * tls13con.c/tls13_UnprotectRecord(),
13761
             * For DTLS 1.3 the outer content type is checked before in
13762
             * ssl3gthr.c/dtls_GatherData.
13763
             * The inner content types will be checked here.
13764
             *
13765
             * In DTLS generally invalid records SHOULD be silently discarded,
13766
             * no alert is sent [RFC6347, Section 4.1.2.7].
13767
             */
13768
520
            if (!IS_DTLS(ss)) {
13769
212
                SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13770
212
            }
13771
520
            PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
13772
520
            SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
13773
520
                     SSL_GETPID(), ss->fd, rType));
13774
520
            rv = SECFailure;
13775
520
            break;
13776
1.67M
    }
13777
13778
1.67M
    ssl_ReleaseSSL3HandshakeLock(ss);
13779
1.67M
    return rv;
13780
1.67M
}
13781
13782
/* Find the cipher spec to use for a given record. For TLS, this
13783
 * is the current cipherspec. For DTLS, we look up by epoch.
13784
 * In DTLS < 1.3 this just means the current epoch or nothing,
13785
 * but in DTLS >= 1.3, we keep multiple reading cipherspecs.
13786
 * Returns NULL if no appropriate cipher spec is found.
13787
 */
13788
static ssl3CipherSpec *
13789
ssl3_GetCipherSpec(sslSocket *ss, SSL3Ciphertext *cText)
13790
11.9M
{
13791
11.9M
    ssl3CipherSpec *crSpec = ss->ssl3.crSpec;
13792
11.9M
    ssl3CipherSpec *newSpec = NULL;
13793
11.9M
    DTLSEpoch epoch;
13794
13795
11.9M
    if (!IS_DTLS(ss)) {
13796
2.51M
        return crSpec;
13797
2.51M
    }
13798
9.43M
    epoch = dtls_ReadEpoch(crSpec->version, crSpec->epoch, cText->hdr);
13799
9.43M
    if (crSpec->epoch == epoch) {
13800
7.06M
        return crSpec;
13801
7.06M
    }
13802
2.36M
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
13803
        /* Try to find the cipher spec. */
13804
27.5k
        newSpec = ssl_FindCipherSpecByEpoch(ss, ssl_secret_read,
13805
27.5k
                                            epoch);
13806
27.5k
        if (newSpec != NULL) {
13807
8.53k
            return newSpec;
13808
8.53k
        }
13809
27.5k
    }
13810
2.36M
    SSL_TRC(10, ("%d: DTLS[%d]: %s couldn't find cipherspec from epoch %d",
13811
2.36M
                 SSL_GETPID(), ss->fd, SSL_ROLE(ss), epoch));
13812
2.36M
    return NULL;
13813
2.36M
}
13814
13815
/* if cText is non-null, then decipher and check the MAC of the
13816
 * SSL record from cText->buf (typically gs->inbuf)
13817
 * into databuf (typically gs->buf), and any previous contents of databuf
13818
 * is lost.  Then handle databuf according to its SSL record type,
13819
 * unless it's an application record.
13820
 *
13821
 * If cText is NULL, then the ciphertext has previously been deciphered and
13822
 * checked, and is already sitting in databuf.  It is processed as an SSL
13823
 * Handshake message.
13824
 *
13825
 * DOES NOT process the decrypted application data.
13826
 * On return, databuf contains the decrypted record.
13827
 *
13828
 * Called from ssl3_GatherCompleteHandshake
13829
 *             ssl3_RestartHandshakeAfterCertReq
13830
 *
13831
 * Caller must hold the RecvBufLock.
13832
 *
13833
 * This function aquires and releases the SSL3Handshake Lock, holding the
13834
 * lock around any calls to functions that handle records other than
13835
 * Application Data records.
13836
 */
13837
SECStatus
13838
ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText)
13839
11.9M
{
13840
11.9M
    SECStatus rv = SECFailure;
13841
11.9M
    PRBool isTLS, isTLS13;
13842
11.9M
    DTLSEpoch epoch;
13843
11.9M
    ssl3CipherSpec *spec = NULL;
13844
11.9M
    PRUint16 recordSizeLimit, cTextSizeLimit;
13845
11.9M
    PRBool outOfOrderSpec = PR_FALSE;
13846
11.9M
    SSLContentType rType;
13847
11.9M
    sslBuffer *plaintext = &ss->gs.buf;
13848
11.9M
    SSL3AlertDescription alert = internal_error;
13849
11.9M
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
13850
13851
    /* check for Token Presence */
13852
11.9M
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13853
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13854
0
        return SECFailure;
13855
0
    }
13856
13857
    /* Clear out the buffer in case this exits early.  Any data then won't be
13858
     * processed twice. */
13859
11.9M
    plaintext->len = 0;
13860
13861
    /* We're waiting for another ClientHello, which will appear unencrypted.
13862
     * Use the content type to tell whether this should be discarded. */
13863
11.9M
    if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr &&
13864
21.3k
        cText->hdr[0] == ssl_ct_application_data) {
13865
1.15k
        PORT_Assert(ss->ssl3.hs.ws == wait_client_hello);
13866
1.15k
        return SECSuccess;
13867
1.15k
    }
13868
13869
11.9M
    ssl_GetSpecReadLock(ss); /******************************************/
13870
11.9M
    spec = ssl3_GetCipherSpec(ss, cText);
13871
11.9M
    if (!spec) {
13872
2.36M
        PORT_Assert(IS_DTLS(ss));
13873
2.36M
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13874
2.36M
        return SECSuccess;
13875
2.36M
    }
13876
9.58M
    if (spec != ss->ssl3.crSpec) {
13877
8.53k
        PORT_Assert(IS_DTLS(ss));
13878
8.53k
        SSL_TRC(3, ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d",
13879
8.53k
                    SSL_GETPID(), ss->fd, spec->epoch));
13880
8.53k
        outOfOrderSpec = PR_TRUE;
13881
8.53k
    }
13882
9.58M
    isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
13883
9.58M
    if (IS_DTLS(ss)) {
13884
7.07M
        if (dtls13_MaskSequenceNumber(ss, spec, cText->hdr,
13885
7.07M
                                      SSL_BUFFER_BASE(cText->buf), SSL_BUFFER_LEN(cText->buf)) != SECSuccess) {
13886
25
            ssl_ReleaseSpecReadLock(ss); /*****************************/
13887
            /* code already set. */
13888
25
            return SECFailure;
13889
25
        }
13890
7.07M
        if (!dtls_IsRelevant(ss, spec, cText, &cText->seqNum)) {
13891
6.89M
            ssl_ReleaseSpecReadLock(ss); /*****************************/
13892
6.89M
            return SECSuccess;
13893
6.89M
        }
13894
7.07M
    } else {
13895
2.51M
        cText->seqNum = spec->nextSeqNum;
13896
2.51M
    }
13897
2.68M
    if (cText->seqNum >= spec->cipherDef->max_records) {
13898
138
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13899
138
        SSL_TRC(3, ("%d: SSL[%d]: read sequence number at limit 0x%0llx",
13900
138
                    SSL_GETPID(), ss->fd, cText->seqNum));
13901
138
        PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
13902
138
        return SECFailure;
13903
138
    }
13904
13905
2.68M
    isTLS13 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
13906
2.68M
    recordSizeLimit = spec->recordSizeLimit;
13907
2.68M
    cTextSizeLimit = recordSizeLimit;
13908
2.68M
    cTextSizeLimit += (isTLS13) ? TLS_1_3_MAX_EXPANSION : TLS_1_2_MAX_EXPANSION;
13909
13910
    /* Check if the specified recordSizeLimit and the RFC8446 specified max
13911
     * expansion are respected. recordSizeLimit is probably at the default for
13912
     * the first (hello) handshake message and then set to a smaller size by
13913
     * the Record Size Limit Extension.
13914
     * Stricter expansion size checks dependent on implemented cipher suites
13915
     * are performed in ssl3con.c/ssl3_UnprotectRecord() OR
13916
     * tls13con.c/tls13_UnprotextRecord().
13917
     * After Decryption the plaintext size is checked (l. 13424). This also
13918
     * applies to unencrypted records. */
13919
2.68M
    if (cText->buf->len > cTextSizeLimit) {
13920
1.15k
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13921
        /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
13922
1.15k
        if (IS_DTLS(ss)) {
13923
1.11k
            return SECSuccess;
13924
1.11k
        }
13925
37
        SSL3_SendAlert(ss, alert_fatal, record_overflow);
13926
37
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13927
37
        return SECFailure;
13928
1.15k
    }
13929
13930
2.68M
#ifdef DEBUG
13931
    /* In debug builds the gather buffers are freed after the handling of each
13932
     * record for advanced ASAN coverage. Allocate the buffer again to the
13933
     * maximum possibly needed size as on gather initialization in
13934
     * ssl3gthr.c/ssl3_InitGather(). */
13935
2.68M
    PR_ASSERT(sslBuffer_Grow(plaintext, TLS_1_2_MAX_CTEXT_LENGTH) == SECSuccess);
13936
2.68M
#endif
13937
    /* This replaces a dynamic plaintext buffer size check, since the buffer is
13938
     * allocated to the maximum size in ssl3gthr.c/ssl3_InitGather(). The buffer
13939
     * was always grown to the maximum size at first record gathering before. */
13940
2.68M
    PR_ASSERT(plaintext->space >= cTextSizeLimit);
13941
13942
    /* Most record types aside from protected TLS 1.3 records carry the content
13943
     * type in the first octet. TLS 1.3 will override this value later. */
13944
2.68M
    rType = cText->hdr[0];
13945
    /* Encrypted application data records could arrive before the handshake
13946
     * completes in DTLS 1.3. These can look like valid TLS 1.2 application_data
13947
     * records in epoch 0, which is never valid. Pretend they didn't decrypt. */
13948
2.68M
    if (spec->epoch == 0 && ((IS_DTLS(ss) &&
13949
105k
                              dtls_IsDtls13Ciphertext(0, rType)) ||
13950
1.13M
                             rType == ssl_ct_application_data)) {
13951
45.3k
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
13952
45.3k
        alert = unexpected_message;
13953
45.3k
        rv = SECFailure;
13954
2.64M
    } else {
13955
#ifdef UNSAFE_FUZZER_MODE
13956
        rv = Null_Cipher(NULL, plaintext->buf, &plaintext->len,
13957
                         plaintext->space, cText->buf->buf, cText->buf->len);
13958
#else
13959
        /* IMPORTANT:
13960
         * Unprotect functions MUST NOT send alerts
13961
         * because we still hold the spec read lock. Instead, if they
13962
         * return SECFailure, they set *alert to the alert to be sent.
13963
         * Additionaly, this is used to silently drop DTLS encryption/record
13964
         * errors/alerts using the error handling below as suggested in the
13965
         * DTLS specification [RFC6347, Section 4.1.2.7]. */
13966
623k
        if (spec->cipherDef->cipher == cipher_null && cText->buf->len == 0) {
13967
            /* Handle a zero-length unprotected record
13968
             * In this case, we treat it as a no-op and let later functions decide
13969
             * whether to ignore or alert accordingly. */
13970
450k
            PR_ASSERT(plaintext->len == 0);
13971
450k
            rv = SECSuccess;
13972
450k
        } else if (spec->version < SSL_LIBRARY_VERSION_TLS_1_3 || spec->epoch == 0) {
13973
154k
            rv = ssl3_UnprotectRecord(ss, spec, cText, plaintext, &alert);
13974
154k
        } else {
13975
17.5k
            rv = tls13_UnprotectRecord(ss, spec, cText, plaintext, &rType,
13976
17.5k
                                       &alert);
13977
17.5k
        }
13978
#endif
13979
2.64M
    }
13980
13981
    /* Error/Alert handling for ssl3/tls13_UnprotectRecord */
13982
2.68M
    if (rv != SECSuccess) {
13983
120k
        ssl_ReleaseSpecReadLock(ss); /***************************/
13984
13985
120k
        SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
13986
13987
        /* Ensure that we don't process this data again. */
13988
120k
        plaintext->len = 0;
13989
13990
        /* Ignore a CCS if compatibility mode is negotiated.  Note that this
13991
         * will fail if the server fails to negotiate compatibility mode in a
13992
         * 0-RTT session that is resumed from a session that did negotiate it.
13993
         * We don't care about that corner case right now. */
13994
120k
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
13995
55.4k
            cText->hdr[0] == ssl_ct_change_cipher_spec &&
13996
821
            ss->ssl3.hs.ws != idle_handshake &&
13997
821
            cText->buf->len == 1 &&
13998
574
            cText->buf->buf[0] == change_cipher_spec_choice) {
13999
378
            if (!ss->ssl3.hs.rejectCcs) {
14000
                /* Allow only the first CCS. */
14001
18
                ss->ssl3.hs.rejectCcs = PR_TRUE;
14002
18
                return SECSuccess;
14003
360
            } else {
14004
360
                alert = unexpected_message;
14005
360
                PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
14006
360
            }
14007
378
        }
14008
14009
        /* All errors/alerts that might occur during unprotection are related
14010
         * to invalid records (e.g. invalid formatting, length, MAC, ...).
14011
         * Following the DTLS specification such errors/alerts SHOULD be
14012
         * dropped silently [RFC9147, Section 4.5.2].
14013
         * This is done below. */
14014
14015
120k
        if ((IS_DTLS(ss) && !dtls13_AeadLimitReached(spec)) ||
14016
6.69k
            (!IS_DTLS(ss) && ss->sec.isServer &&
14017
120k
             ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_trial)) {
14018
            /* Silently drop the packet unless we set ss->ssl3.fatalAlertSent.
14019
             * (Manually or by using functions like
14020
             * SSL3_SendAlert(.., alert_fatal,..))
14021
             * This is not currently used in the unprotection functions since
14022
             * all TLS and DTLS errors are propagated to this handler. */
14023
120k
            if (ss->ssl3.fatalAlertSent) {
14024
0
                return SECFailure;
14025
0
            }
14026
120k
            return SECSuccess;
14027
120k
        }
14028
14029
678
        int errCode = PORT_GetError();
14030
678
        SSL3_SendAlert(ss, alert_fatal, alert);
14031
        /* Reset the error code in case SSL3_SendAlert called
14032
         * PORT_SetError(). */
14033
678
        PORT_SetError(errCode);
14034
678
        return SECFailure;
14035
120k
    }
14036
14037
    /* SECSuccess */
14038
2.56M
    if (IS_DTLS(ss)) {
14039
62.8k
        dtls_RecordSetRecvd(&spec->recvdRecords, cText->seqNum);
14040
62.8k
        spec->nextSeqNum = PR_MAX(spec->nextSeqNum, cText->seqNum + 1);
14041
2.50M
    } else {
14042
2.50M
        ++spec->nextSeqNum;
14043
2.50M
    }
14044
2.56M
    epoch = spec->epoch;
14045
14046
2.56M
    ssl_ReleaseSpecReadLock(ss); /*****************************************/
14047
14048
    /*
14049
     * The decrypted data is now in plaintext.
14050
     */
14051
14052
    /* IMPORTANT: We are in DTLS 1.3 mode and we have processed something
14053
     * from the wrong epoch. Divert to a divert processing function to make
14054
     * sure we don't accidentally use the data unsafely. */
14055
14056
    /* We temporary allowed reading the records from the previous epoch n-1
14057
    until the moment we get a message from the new epoch n. */
14058
14059
2.56M
    if (outOfOrderSpec) {
14060
2.46k
        PORT_Assert(IS_DTLS(ss) && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
14061
2.46k
        ssl_GetSSL3HandshakeLock(ss);
14062
2.46k
        if (ss->ssl3.hs.allowPreviousEpoch && spec->epoch == ss->ssl3.crSpec->epoch - 1) {
14063
0
            SSL_TRC(30, ("%d: DTLS13[%d]: Out of order message %d is accepted",
14064
0
                         SSL_GETPID(), ss->fd, spec->epoch));
14065
0
            ssl_ReleaseSSL3HandshakeLock(ss);
14066
2.46k
        } else {
14067
2.46k
            ssl_ReleaseSSL3HandshakeLock(ss);
14068
2.46k
            return dtls13_HandleOutOfEpochRecord(ss, spec, rType, plaintext);
14069
2.46k
        }
14070
2.56M
    } else {
14071
2.56M
        ssl_GetSSL3HandshakeLock(ss);
14072
        /* Forbid (application) messages from the previous epoch.
14073
           From now, messages that arrive out of order will be discarded. */
14074
2.56M
        ss->ssl3.hs.allowPreviousEpoch = PR_FALSE;
14075
2.56M
        ssl_ReleaseSSL3HandshakeLock(ss);
14076
2.56M
    }
14077
14078
    /* Check the length of the plaintext. */
14079
2.56M
    if (isTLS && plaintext->len > recordSizeLimit) {
14080
94
        plaintext->len = 0;
14081
        /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
14082
94
        if (IS_DTLS(ss)) {
14083
85
            return SECSuccess;
14084
85
        }
14085
9
        SSL3_SendAlert(ss, alert_fatal, record_overflow);
14086
9
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
14087
9
        return SECFailure;
14088
94
    }
14089
14090
    /* Application data records are processed by the caller of this
14091
    ** function, not by this function.
14092
    */
14093
2.56M
    if (rType == ssl_ct_application_data) {
14094
890k
        if (ss->firstHsDone)
14095
889k
            return SECSuccess;
14096
163
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
14097
12
            ss->sec.isServer &&
14098
12
            ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
14099
0
            return tls13_HandleEarlyApplicationData(ss, plaintext);
14100
0
        }
14101
163
        plaintext->len = 0;
14102
        /* DTLS 1.2 [RFC 6347, Section 4.1.2.7] and DTLS 1.3 [RFC 9147,
14103
         * Section 4.5.2]: invalid records SHOULD be silently discarded. */
14104
163
        if (IS_DTLS(ss)) {
14105
153
            return SECSuccess;
14106
153
        }
14107
10
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
14108
10
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
14109
10
        return SECFailure;
14110
163
    }
14111
14112
1.67M
    rv = ssl3_HandleNonApplicationData(ss, rType, epoch, cText->seqNum,
14113
1.67M
                                       plaintext);
14114
14115
1.67M
#ifdef DEBUG
14116
    /* In Debug builds free and zero gather plaintext buffer after its content
14117
     * has been used/copied for advanced ASAN coverage/utilization.
14118
     * This frees buffer for non application data records, for application data
14119
     * records it is freed in sslsecur.c/DoRecv(). */
14120
1.67M
    sslBuffer_Clear(&ss->gs.buf);
14121
1.67M
#endif
14122
14123
1.67M
    return rv;
14124
2.56M
}
ssl3_HandleRecord
Line
Count
Source
13839
5.87M
{
13840
5.87M
    SECStatus rv = SECFailure;
13841
5.87M
    PRBool isTLS, isTLS13;
13842
5.87M
    DTLSEpoch epoch;
13843
5.87M
    ssl3CipherSpec *spec = NULL;
13844
5.87M
    PRUint16 recordSizeLimit, cTextSizeLimit;
13845
5.87M
    PRBool outOfOrderSpec = PR_FALSE;
13846
5.87M
    SSLContentType rType;
13847
5.87M
    sslBuffer *plaintext = &ss->gs.buf;
13848
5.87M
    SSL3AlertDescription alert = internal_error;
13849
5.87M
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
13850
13851
    /* check for Token Presence */
13852
5.87M
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13853
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13854
0
        return SECFailure;
13855
0
    }
13856
13857
    /* Clear out the buffer in case this exits early.  Any data then won't be
13858
     * processed twice. */
13859
5.87M
    plaintext->len = 0;
13860
13861
    /* We're waiting for another ClientHello, which will appear unencrypted.
13862
     * Use the content type to tell whether this should be discarded. */
13863
5.87M
    if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr &&
13864
19.9k
        cText->hdr[0] == ssl_ct_application_data) {
13865
421
        PORT_Assert(ss->ssl3.hs.ws == wait_client_hello);
13866
421
        return SECSuccess;
13867
421
    }
13868
13869
5.87M
    ssl_GetSpecReadLock(ss); /******************************************/
13870
5.87M
    spec = ssl3_GetCipherSpec(ss, cText);
13871
5.87M
    if (!spec) {
13872
259k
        PORT_Assert(IS_DTLS(ss));
13873
259k
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13874
259k
        return SECSuccess;
13875
259k
    }
13876
5.61M
    if (spec != ss->ssl3.crSpec) {
13877
6.42k
        PORT_Assert(IS_DTLS(ss));
13878
6.42k
        SSL_TRC(3, ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d",
13879
6.42k
                    SSL_GETPID(), ss->fd, spec->epoch));
13880
6.42k
        outOfOrderSpec = PR_TRUE;
13881
6.42k
    }
13882
5.61M
    isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
13883
5.61M
    if (IS_DTLS(ss)) {
13884
3.62M
        if (dtls13_MaskSequenceNumber(ss, spec, cText->hdr,
13885
3.62M
                                      SSL_BUFFER_BASE(cText->buf), SSL_BUFFER_LEN(cText->buf)) != SECSuccess) {
13886
0
            ssl_ReleaseSpecReadLock(ss); /*****************************/
13887
            /* code already set. */
13888
0
            return SECFailure;
13889
0
        }
13890
3.62M
        if (!dtls_IsRelevant(ss, spec, cText, &cText->seqNum)) {
13891
3.59M
            ssl_ReleaseSpecReadLock(ss); /*****************************/
13892
3.59M
            return SECSuccess;
13893
3.59M
        }
13894
3.62M
    } else {
13895
1.98M
        cText->seqNum = spec->nextSeqNum;
13896
1.98M
    }
13897
2.02M
    if (cText->seqNum >= spec->cipherDef->max_records) {
13898
80
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13899
80
        SSL_TRC(3, ("%d: SSL[%d]: read sequence number at limit 0x%0llx",
13900
80
                    SSL_GETPID(), ss->fd, cText->seqNum));
13901
80
        PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
13902
80
        return SECFailure;
13903
80
    }
13904
13905
2.02M
    isTLS13 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
13906
2.02M
    recordSizeLimit = spec->recordSizeLimit;
13907
2.02M
    cTextSizeLimit = recordSizeLimit;
13908
2.02M
    cTextSizeLimit += (isTLS13) ? TLS_1_3_MAX_EXPANSION : TLS_1_2_MAX_EXPANSION;
13909
13910
    /* Check if the specified recordSizeLimit and the RFC8446 specified max
13911
     * expansion are respected. recordSizeLimit is probably at the default for
13912
     * the first (hello) handshake message and then set to a smaller size by
13913
     * the Record Size Limit Extension.
13914
     * Stricter expansion size checks dependent on implemented cipher suites
13915
     * are performed in ssl3con.c/ssl3_UnprotectRecord() OR
13916
     * tls13con.c/tls13_UnprotextRecord().
13917
     * After Decryption the plaintext size is checked (l. 13424). This also
13918
     * applies to unencrypted records. */
13919
2.02M
    if (cText->buf->len > cTextSizeLimit) {
13920
524
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13921
        /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
13922
524
        if (IS_DTLS(ss)) {
13923
502
            return SECSuccess;
13924
502
        }
13925
22
        SSL3_SendAlert(ss, alert_fatal, record_overflow);
13926
22
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13927
22
        return SECFailure;
13928
524
    }
13929
13930
2.02M
#ifdef DEBUG
13931
    /* In debug builds the gather buffers are freed after the handling of each
13932
     * record for advanced ASAN coverage. Allocate the buffer again to the
13933
     * maximum possibly needed size as on gather initialization in
13934
     * ssl3gthr.c/ssl3_InitGather(). */
13935
2.02M
    PR_ASSERT(sslBuffer_Grow(plaintext, TLS_1_2_MAX_CTEXT_LENGTH) == SECSuccess);
13936
2.02M
#endif
13937
    /* This replaces a dynamic plaintext buffer size check, since the buffer is
13938
     * allocated to the maximum size in ssl3gthr.c/ssl3_InitGather(). The buffer
13939
     * was always grown to the maximum size at first record gathering before. */
13940
2.02M
    PR_ASSERT(plaintext->space >= cTextSizeLimit);
13941
13942
    /* Most record types aside from protected TLS 1.3 records carry the content
13943
     * type in the first octet. TLS 1.3 will override this value later. */
13944
2.02M
    rType = cText->hdr[0];
13945
    /* Encrypted application data records could arrive before the handshake
13946
     * completes in DTLS 1.3. These can look like valid TLS 1.2 application_data
13947
     * records in epoch 0, which is never valid. Pretend they didn't decrypt. */
13948
2.02M
    if (spec->epoch == 0 && ((IS_DTLS(ss) &&
13949
36.2k
                              dtls_IsDtls13Ciphertext(0, rType)) ||
13950
564k
                             rType == ssl_ct_application_data)) {
13951
7.13k
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
13952
7.13k
        alert = unexpected_message;
13953
7.13k
        rv = SECFailure;
13954
2.01M
    } else {
13955
2.01M
#ifdef UNSAFE_FUZZER_MODE
13956
2.01M
        rv = Null_Cipher(NULL, plaintext->buf, &plaintext->len,
13957
2.01M
                         plaintext->space, cText->buf->buf, cText->buf->len);
13958
#else
13959
        /* IMPORTANT:
13960
         * Unprotect functions MUST NOT send alerts
13961
         * because we still hold the spec read lock. Instead, if they
13962
         * return SECFailure, they set *alert to the alert to be sent.
13963
         * Additionaly, this is used to silently drop DTLS encryption/record
13964
         * errors/alerts using the error handling below as suggested in the
13965
         * DTLS specification [RFC6347, Section 4.1.2.7]. */
13966
        if (spec->cipherDef->cipher == cipher_null && cText->buf->len == 0) {
13967
            /* Handle a zero-length unprotected record
13968
             * In this case, we treat it as a no-op and let later functions decide
13969
             * whether to ignore or alert accordingly. */
13970
            PR_ASSERT(plaintext->len == 0);
13971
            rv = SECSuccess;
13972
        } else if (spec->version < SSL_LIBRARY_VERSION_TLS_1_3 || spec->epoch == 0) {
13973
            rv = ssl3_UnprotectRecord(ss, spec, cText, plaintext, &alert);
13974
        } else {
13975
            rv = tls13_UnprotectRecord(ss, spec, cText, plaintext, &rType,
13976
                                       &alert);
13977
        }
13978
#endif
13979
2.01M
    }
13980
13981
    /* Error/Alert handling for ssl3/tls13_UnprotectRecord */
13982
2.02M
    if (rv != SECSuccess) {
13983
7.13k
        ssl_ReleaseSpecReadLock(ss); /***************************/
13984
13985
7.13k
        SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
13986
13987
        /* Ensure that we don't process this data again. */
13988
7.13k
        plaintext->len = 0;
13989
13990
        /* Ignore a CCS if compatibility mode is negotiated.  Note that this
13991
         * will fail if the server fails to negotiate compatibility mode in a
13992
         * 0-RTT session that is resumed from a session that did negotiate it.
13993
         * We don't care about that corner case right now. */
13994
7.13k
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
13995
1.38k
            cText->hdr[0] == ssl_ct_change_cipher_spec &&
13996
0
            ss->ssl3.hs.ws != idle_handshake &&
13997
0
            cText->buf->len == 1 &&
13998
0
            cText->buf->buf[0] == change_cipher_spec_choice) {
13999
0
            if (!ss->ssl3.hs.rejectCcs) {
14000
                /* Allow only the first CCS. */
14001
0
                ss->ssl3.hs.rejectCcs = PR_TRUE;
14002
0
                return SECSuccess;
14003
0
            } else {
14004
0
                alert = unexpected_message;
14005
0
                PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
14006
0
            }
14007
0
        }
14008
14009
        /* All errors/alerts that might occur during unprotection are related
14010
         * to invalid records (e.g. invalid formatting, length, MAC, ...).
14011
         * Following the DTLS specification such errors/alerts SHOULD be
14012
         * dropped silently [RFC9147, Section 4.5.2].
14013
         * This is done below. */
14014
14015
7.13k
        if ((IS_DTLS(ss) && !dtls13_AeadLimitReached(spec)) ||
14016
12
            (!IS_DTLS(ss) && ss->sec.isServer &&
14017
7.12k
             ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_trial)) {
14018
            /* Silently drop the packet unless we set ss->ssl3.fatalAlertSent.
14019
             * (Manually or by using functions like
14020
             * SSL3_SendAlert(.., alert_fatal,..))
14021
             * This is not currently used in the unprotection functions since
14022
             * all TLS and DTLS errors are propagated to this handler. */
14023
7.12k
            if (ss->ssl3.fatalAlertSent) {
14024
0
                return SECFailure;
14025
0
            }
14026
7.12k
            return SECSuccess;
14027
7.12k
        }
14028
14029
12
        int errCode = PORT_GetError();
14030
12
        SSL3_SendAlert(ss, alert_fatal, alert);
14031
        /* Reset the error code in case SSL3_SendAlert called
14032
         * PORT_SetError(). */
14033
12
        PORT_SetError(errCode);
14034
12
        return SECFailure;
14035
7.13k
    }
14036
14037
    /* SECSuccess */
14038
2.01M
    if (IS_DTLS(ss)) {
14039
31.3k
        dtls_RecordSetRecvd(&spec->recvdRecords, cText->seqNum);
14040
31.3k
        spec->nextSeqNum = PR_MAX(spec->nextSeqNum, cText->seqNum + 1);
14041
1.98M
    } else {
14042
1.98M
        ++spec->nextSeqNum;
14043
1.98M
    }
14044
2.01M
    epoch = spec->epoch;
14045
14046
2.01M
    ssl_ReleaseSpecReadLock(ss); /*****************************************/
14047
14048
    /*
14049
     * The decrypted data is now in plaintext.
14050
     */
14051
14052
    /* IMPORTANT: We are in DTLS 1.3 mode and we have processed something
14053
     * from the wrong epoch. Divert to a divert processing function to make
14054
     * sure we don't accidentally use the data unsafely. */
14055
14056
    /* We temporary allowed reading the records from the previous epoch n-1
14057
    until the moment we get a message from the new epoch n. */
14058
14059
2.01M
    if (outOfOrderSpec) {
14060
1.28k
        PORT_Assert(IS_DTLS(ss) && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
14061
1.28k
        ssl_GetSSL3HandshakeLock(ss);
14062
1.28k
        if (ss->ssl3.hs.allowPreviousEpoch && spec->epoch == ss->ssl3.crSpec->epoch - 1) {
14063
0
            SSL_TRC(30, ("%d: DTLS13[%d]: Out of order message %d is accepted",
14064
0
                         SSL_GETPID(), ss->fd, spec->epoch));
14065
0
            ssl_ReleaseSSL3HandshakeLock(ss);
14066
1.28k
        } else {
14067
1.28k
            ssl_ReleaseSSL3HandshakeLock(ss);
14068
1.28k
            return dtls13_HandleOutOfEpochRecord(ss, spec, rType, plaintext);
14069
1.28k
        }
14070
2.01M
    } else {
14071
2.01M
        ssl_GetSSL3HandshakeLock(ss);
14072
        /* Forbid (application) messages from the previous epoch.
14073
           From now, messages that arrive out of order will be discarded. */
14074
2.01M
        ss->ssl3.hs.allowPreviousEpoch = PR_FALSE;
14075
2.01M
        ssl_ReleaseSSL3HandshakeLock(ss);
14076
2.01M
    }
14077
14078
    /* Check the length of the plaintext. */
14079
2.01M
    if (isTLS && plaintext->len > recordSizeLimit) {
14080
57
        plaintext->len = 0;
14081
        /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
14082
57
        if (IS_DTLS(ss)) {
14083
51
            return SECSuccess;
14084
51
        }
14085
6
        SSL3_SendAlert(ss, alert_fatal, record_overflow);
14086
6
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
14087
6
        return SECFailure;
14088
57
    }
14089
14090
    /* Application data records are processed by the caller of this
14091
    ** function, not by this function.
14092
    */
14093
2.01M
    if (rType == ssl_ct_application_data) {
14094
890k
        if (ss->firstHsDone)
14095
889k
            return SECSuccess;
14096
139
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
14097
12
            ss->sec.isServer &&
14098
12
            ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
14099
0
            return tls13_HandleEarlyApplicationData(ss, plaintext);
14100
0
        }
14101
139
        plaintext->len = 0;
14102
        /* DTLS 1.2 [RFC 6347, Section 4.1.2.7] and DTLS 1.3 [RFC 9147,
14103
         * Section 4.5.2]: invalid records SHOULD be silently discarded. */
14104
139
        if (IS_DTLS(ss)) {
14105
132
            return SECSuccess;
14106
132
        }
14107
7
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
14108
7
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
14109
7
        return SECFailure;
14110
139
    }
14111
14112
1.12M
    rv = ssl3_HandleNonApplicationData(ss, rType, epoch, cText->seqNum,
14113
1.12M
                                       plaintext);
14114
14115
1.12M
#ifdef DEBUG
14116
    /* In Debug builds free and zero gather plaintext buffer after its content
14117
     * has been used/copied for advanced ASAN coverage/utilization.
14118
     * This frees buffer for non application data records, for application data
14119
     * records it is freed in sslsecur.c/DoRecv(). */
14120
1.12M
    sslBuffer_Clear(&ss->gs.buf);
14121
1.12M
#endif
14122
14123
1.12M
    return rv;
14124
2.01M
}
ssl3_HandleRecord
Line
Count
Source
13839
6.06M
{
13840
6.06M
    SECStatus rv = SECFailure;
13841
6.06M
    PRBool isTLS, isTLS13;
13842
6.06M
    DTLSEpoch epoch;
13843
6.06M
    ssl3CipherSpec *spec = NULL;
13844
6.06M
    PRUint16 recordSizeLimit, cTextSizeLimit;
13845
6.06M
    PRBool outOfOrderSpec = PR_FALSE;
13846
6.06M
    SSLContentType rType;
13847
6.06M
    sslBuffer *plaintext = &ss->gs.buf;
13848
6.06M
    SSL3AlertDescription alert = internal_error;
13849
6.06M
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
13850
13851
    /* check for Token Presence */
13852
6.06M
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13853
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13854
0
        return SECFailure;
13855
0
    }
13856
13857
    /* Clear out the buffer in case this exits early.  Any data then won't be
13858
     * processed twice. */
13859
6.06M
    plaintext->len = 0;
13860
13861
    /* We're waiting for another ClientHello, which will appear unencrypted.
13862
     * Use the content type to tell whether this should be discarded. */
13863
6.06M
    if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr &&
13864
1.48k
        cText->hdr[0] == ssl_ct_application_data) {
13865
734
        PORT_Assert(ss->ssl3.hs.ws == wait_client_hello);
13866
734
        return SECSuccess;
13867
734
    }
13868
13869
6.06M
    ssl_GetSpecReadLock(ss); /******************************************/
13870
6.06M
    spec = ssl3_GetCipherSpec(ss, cText);
13871
6.06M
    if (!spec) {
13872
2.10M
        PORT_Assert(IS_DTLS(ss));
13873
2.10M
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13874
2.10M
        return SECSuccess;
13875
2.10M
    }
13876
3.96M
    if (spec != ss->ssl3.crSpec) {
13877
2.10k
        PORT_Assert(IS_DTLS(ss));
13878
2.10k
        SSL_TRC(3, ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d",
13879
2.10k
                    SSL_GETPID(), ss->fd, spec->epoch));
13880
2.10k
        outOfOrderSpec = PR_TRUE;
13881
2.10k
    }
13882
3.96M
    isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
13883
3.96M
    if (IS_DTLS(ss)) {
13884
3.44M
        if (dtls13_MaskSequenceNumber(ss, spec, cText->hdr,
13885
3.44M
                                      SSL_BUFFER_BASE(cText->buf), SSL_BUFFER_LEN(cText->buf)) != SECSuccess) {
13886
25
            ssl_ReleaseSpecReadLock(ss); /*****************************/
13887
            /* code already set. */
13888
25
            return SECFailure;
13889
25
        }
13890
3.44M
        if (!dtls_IsRelevant(ss, spec, cText, &cText->seqNum)) {
13891
3.30M
            ssl_ReleaseSpecReadLock(ss); /*****************************/
13892
3.30M
            return SECSuccess;
13893
3.30M
        }
13894
3.44M
    } else {
13895
523k
        cText->seqNum = spec->nextSeqNum;
13896
523k
    }
13897
662k
    if (cText->seqNum >= spec->cipherDef->max_records) {
13898
58
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13899
58
        SSL_TRC(3, ("%d: SSL[%d]: read sequence number at limit 0x%0llx",
13900
58
                    SSL_GETPID(), ss->fd, cText->seqNum));
13901
58
        PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
13902
58
        return SECFailure;
13903
58
    }
13904
13905
662k
    isTLS13 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
13906
662k
    recordSizeLimit = spec->recordSizeLimit;
13907
662k
    cTextSizeLimit = recordSizeLimit;
13908
662k
    cTextSizeLimit += (isTLS13) ? TLS_1_3_MAX_EXPANSION : TLS_1_2_MAX_EXPANSION;
13909
13910
    /* Check if the specified recordSizeLimit and the RFC8446 specified max
13911
     * expansion are respected. recordSizeLimit is probably at the default for
13912
     * the first (hello) handshake message and then set to a smaller size by
13913
     * the Record Size Limit Extension.
13914
     * Stricter expansion size checks dependent on implemented cipher suites
13915
     * are performed in ssl3con.c/ssl3_UnprotectRecord() OR
13916
     * tls13con.c/tls13_UnprotextRecord().
13917
     * After Decryption the plaintext size is checked (l. 13424). This also
13918
     * applies to unencrypted records. */
13919
662k
    if (cText->buf->len > cTextSizeLimit) {
13920
628
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13921
        /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
13922
628
        if (IS_DTLS(ss)) {
13923
613
            return SECSuccess;
13924
613
        }
13925
15
        SSL3_SendAlert(ss, alert_fatal, record_overflow);
13926
15
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13927
15
        return SECFailure;
13928
628
    }
13929
13930
661k
#ifdef DEBUG
13931
    /* In debug builds the gather buffers are freed after the handling of each
13932
     * record for advanced ASAN coverage. Allocate the buffer again to the
13933
     * maximum possibly needed size as on gather initialization in
13934
     * ssl3gthr.c/ssl3_InitGather(). */
13935
661k
    PR_ASSERT(sslBuffer_Grow(plaintext, TLS_1_2_MAX_CTEXT_LENGTH) == SECSuccess);
13936
661k
#endif
13937
    /* This replaces a dynamic plaintext buffer size check, since the buffer is
13938
     * allocated to the maximum size in ssl3gthr.c/ssl3_InitGather(). The buffer
13939
     * was always grown to the maximum size at first record gathering before. */
13940
661k
    PR_ASSERT(plaintext->space >= cTextSizeLimit);
13941
13942
    /* Most record types aside from protected TLS 1.3 records carry the content
13943
     * type in the first octet. TLS 1.3 will override this value later. */
13944
661k
    rType = cText->hdr[0];
13945
    /* Encrypted application data records could arrive before the handshake
13946
     * completes in DTLS 1.3. These can look like valid TLS 1.2 application_data
13947
     * records in epoch 0, which is never valid. Pretend they didn't decrypt. */
13948
661k
    if (spec->epoch == 0 && ((IS_DTLS(ss) &&
13949
69.6k
                              dtls_IsDtls13Ciphertext(0, rType)) ||
13950
567k
                             rType == ssl_ct_application_data)) {
13951
38.2k
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
13952
38.2k
        alert = unexpected_message;
13953
38.2k
        rv = SECFailure;
13954
623k
    } else {
13955
#ifdef UNSAFE_FUZZER_MODE
13956
        rv = Null_Cipher(NULL, plaintext->buf, &plaintext->len,
13957
                         plaintext->space, cText->buf->buf, cText->buf->len);
13958
#else
13959
        /* IMPORTANT:
13960
         * Unprotect functions MUST NOT send alerts
13961
         * because we still hold the spec read lock. Instead, if they
13962
         * return SECFailure, they set *alert to the alert to be sent.
13963
         * Additionaly, this is used to silently drop DTLS encryption/record
13964
         * errors/alerts using the error handling below as suggested in the
13965
         * DTLS specification [RFC6347, Section 4.1.2.7]. */
13966
623k
        if (spec->cipherDef->cipher == cipher_null && cText->buf->len == 0) {
13967
            /* Handle a zero-length unprotected record
13968
             * In this case, we treat it as a no-op and let later functions decide
13969
             * whether to ignore or alert accordingly. */
13970
450k
            PR_ASSERT(plaintext->len == 0);
13971
450k
            rv = SECSuccess;
13972
450k
        } else if (spec->version < SSL_LIBRARY_VERSION_TLS_1_3 || spec->epoch == 0) {
13973
154k
            rv = ssl3_UnprotectRecord(ss, spec, cText, plaintext, &alert);
13974
154k
        } else {
13975
17.5k
            rv = tls13_UnprotectRecord(ss, spec, cText, plaintext, &rType,
13976
17.5k
                                       &alert);
13977
17.5k
        }
13978
623k
#endif
13979
623k
    }
13980
13981
    /* Error/Alert handling for ssl3/tls13_UnprotectRecord */
13982
661k
    if (rv != SECSuccess) {
13983
113k
        ssl_ReleaseSpecReadLock(ss); /***************************/
13984
13985
113k
        SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
13986
13987
        /* Ensure that we don't process this data again. */
13988
113k
        plaintext->len = 0;
13989
13990
        /* Ignore a CCS if compatibility mode is negotiated.  Note that this
13991
         * will fail if the server fails to negotiate compatibility mode in a
13992
         * 0-RTT session that is resumed from a session that did negotiate it.
13993
         * We don't care about that corner case right now. */
13994
113k
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
13995
54.0k
            cText->hdr[0] == ssl_ct_change_cipher_spec &&
13996
821
            ss->ssl3.hs.ws != idle_handshake &&
13997
821
            cText->buf->len == 1 &&
13998
574
            cText->buf->buf[0] == change_cipher_spec_choice) {
13999
378
            if (!ss->ssl3.hs.rejectCcs) {
14000
                /* Allow only the first CCS. */
14001
18
                ss->ssl3.hs.rejectCcs = PR_TRUE;
14002
18
                return SECSuccess;
14003
360
            } else {
14004
360
                alert = unexpected_message;
14005
360
                PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
14006
360
            }
14007
378
        }
14008
14009
        /* All errors/alerts that might occur during unprotection are related
14010
         * to invalid records (e.g. invalid formatting, length, MAC, ...).
14011
         * Following the DTLS specification such errors/alerts SHOULD be
14012
         * dropped silently [RFC9147, Section 4.5.2].
14013
         * This is done below. */
14014
14015
113k
        if ((IS_DTLS(ss) && !dtls13_AeadLimitReached(spec)) ||
14016
6.68k
            (!IS_DTLS(ss) && ss->sec.isServer &&
14017
112k
             ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_trial)) {
14018
            /* Silently drop the packet unless we set ss->ssl3.fatalAlertSent.
14019
             * (Manually or by using functions like
14020
             * SSL3_SendAlert(.., alert_fatal,..))
14021
             * This is not currently used in the unprotection functions since
14022
             * all TLS and DTLS errors are propagated to this handler. */
14023
112k
            if (ss->ssl3.fatalAlertSent) {
14024
0
                return SECFailure;
14025
0
            }
14026
112k
            return SECSuccess;
14027
112k
        }
14028
14029
666
        int errCode = PORT_GetError();
14030
666
        SSL3_SendAlert(ss, alert_fatal, alert);
14031
        /* Reset the error code in case SSL3_SendAlert called
14032
         * PORT_SetError(). */
14033
666
        PORT_SetError(errCode);
14034
666
        return SECFailure;
14035
113k
    }
14036
14037
    /* SECSuccess */
14038
547k
    if (IS_DTLS(ss)) {
14039
31.4k
        dtls_RecordSetRecvd(&spec->recvdRecords, cText->seqNum);
14040
31.4k
        spec->nextSeqNum = PR_MAX(spec->nextSeqNum, cText->seqNum + 1);
14041
516k
    } else {
14042
516k
        ++spec->nextSeqNum;
14043
516k
    }
14044
547k
    epoch = spec->epoch;
14045
14046
547k
    ssl_ReleaseSpecReadLock(ss); /*****************************************/
14047
14048
    /*
14049
     * The decrypted data is now in plaintext.
14050
     */
14051
14052
    /* IMPORTANT: We are in DTLS 1.3 mode and we have processed something
14053
     * from the wrong epoch. Divert to a divert processing function to make
14054
     * sure we don't accidentally use the data unsafely. */
14055
14056
    /* We temporary allowed reading the records from the previous epoch n-1
14057
    until the moment we get a message from the new epoch n. */
14058
14059
547k
    if (outOfOrderSpec) {
14060
1.18k
        PORT_Assert(IS_DTLS(ss) && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
14061
1.18k
        ssl_GetSSL3HandshakeLock(ss);
14062
1.18k
        if (ss->ssl3.hs.allowPreviousEpoch && spec->epoch == ss->ssl3.crSpec->epoch - 1) {
14063
0
            SSL_TRC(30, ("%d: DTLS13[%d]: Out of order message %d is accepted",
14064
0
                         SSL_GETPID(), ss->fd, spec->epoch));
14065
0
            ssl_ReleaseSSL3HandshakeLock(ss);
14066
1.18k
        } else {
14067
1.18k
            ssl_ReleaseSSL3HandshakeLock(ss);
14068
1.18k
            return dtls13_HandleOutOfEpochRecord(ss, spec, rType, plaintext);
14069
1.18k
        }
14070
546k
    } else {
14071
546k
        ssl_GetSSL3HandshakeLock(ss);
14072
        /* Forbid (application) messages from the previous epoch.
14073
           From now, messages that arrive out of order will be discarded. */
14074
546k
        ss->ssl3.hs.allowPreviousEpoch = PR_FALSE;
14075
546k
        ssl_ReleaseSSL3HandshakeLock(ss);
14076
546k
    }
14077
14078
    /* Check the length of the plaintext. */
14079
546k
    if (isTLS && plaintext->len > recordSizeLimit) {
14080
37
        plaintext->len = 0;
14081
        /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
14082
37
        if (IS_DTLS(ss)) {
14083
34
            return SECSuccess;
14084
34
        }
14085
3
        SSL3_SendAlert(ss, alert_fatal, record_overflow);
14086
3
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
14087
3
        return SECFailure;
14088
37
    }
14089
14090
    /* Application data records are processed by the caller of this
14091
    ** function, not by this function.
14092
    */
14093
546k
    if (rType == ssl_ct_application_data) {
14094
24
        if (ss->firstHsDone)
14095
0
            return SECSuccess;
14096
24
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
14097
0
            ss->sec.isServer &&
14098
0
            ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
14099
0
            return tls13_HandleEarlyApplicationData(ss, plaintext);
14100
0
        }
14101
24
        plaintext->len = 0;
14102
        /* DTLS 1.2 [RFC 6347, Section 4.1.2.7] and DTLS 1.3 [RFC 9147,
14103
         * Section 4.5.2]: invalid records SHOULD be silently discarded. */
14104
24
        if (IS_DTLS(ss)) {
14105
21
            return SECSuccess;
14106
21
        }
14107
3
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
14108
3
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
14109
3
        return SECFailure;
14110
24
    }
14111
14112
546k
    rv = ssl3_HandleNonApplicationData(ss, rType, epoch, cText->seqNum,
14113
546k
                                       plaintext);
14114
14115
546k
#ifdef DEBUG
14116
    /* In Debug builds free and zero gather plaintext buffer after its content
14117
     * has been used/copied for advanced ASAN coverage/utilization.
14118
     * This frees buffer for non application data records, for application data
14119
     * records it is freed in sslsecur.c/DoRecv(). */
14120
546k
    sslBuffer_Clear(&ss->gs.buf);
14121
546k
#endif
14122
14123
546k
    return rv;
14124
546k
}
14125
14126
/*
14127
 * Initialization functions
14128
 */
14129
14130
void
14131
ssl_InitSecState(sslSecurityInfo *sec)
14132
62.0k
{
14133
62.0k
    sec->authType = ssl_auth_null;
14134
62.0k
    sec->authKeyBits = 0;
14135
62.0k
    sec->signatureScheme = ssl_sig_none;
14136
62.0k
    sec->keaType = ssl_kea_null;
14137
62.0k
    sec->keaKeyBits = 0;
14138
62.0k
    sec->keaGroup = NULL;
14139
62.0k
}
14140
14141
SECStatus
14142
ssl3_InitState(sslSocket *ss)
14143
62.0k
{
14144
62.0k
    SECStatus rv;
14145
14146
62.0k
    ss->ssl3.policy = SSL_ALLOWED;
14147
14148
62.0k
    ssl_InitSecState(&ss->sec);
14149
14150
62.0k
    ssl_GetSpecWriteLock(ss);
14151
62.0k
    PR_INIT_CLIST(&ss->ssl3.hs.cipherSpecs);
14152
62.0k
    rv = ssl_SetupNullCipherSpec(ss, ssl_secret_read);
14153
62.0k
    rv |= ssl_SetupNullCipherSpec(ss, ssl_secret_write);
14154
62.0k
    ss->ssl3.pwSpec = ss->ssl3.prSpec = NULL;
14155
62.0k
    ssl_ReleaseSpecWriteLock(ss);
14156
62.0k
    if (rv != SECSuccess) {
14157
        /* Rely on ssl_CreateNullCipherSpec() to set error code. */
14158
0
        return SECFailure;
14159
0
    }
14160
14161
62.0k
    ss->ssl3.hs.sendingSCSV = PR_FALSE;
14162
62.0k
    ss->ssl3.hs.preliminaryInfo = 0;
14163
62.0k
    ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : idle_handshake;
14164
14165
62.0k
    ssl3_ResetExtensionData(&ss->xtnData, ss);
14166
62.0k
    PR_INIT_CLIST(&ss->ssl3.hs.remoteExtensions);
14167
62.0k
    PR_INIT_CLIST(&ss->ssl3.hs.echOuterExtensions);
14168
62.0k
    if (IS_DTLS(ss)) {
14169
29.0k
        ss->ssl3.hs.sendMessageSeq = 0;
14170
29.0k
        ss->ssl3.hs.recvMessageSeq = 0;
14171
29.0k
        ss->ssl3.hs.rtTimer->timeout = DTLS_RETRANSMIT_INITIAL_MS;
14172
29.0k
        ss->ssl3.hs.rtRetries = 0;
14173
29.0k
        ss->ssl3.hs.recvdHighWater = -1;
14174
29.0k
        PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
14175
29.0k
        dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
14176
29.0k
    }
14177
14178
62.0k
    ss->ssl3.hs.currentSecret = NULL;
14179
62.0k
    ss->ssl3.hs.resumptionMasterSecret = NULL;
14180
62.0k
    ss->ssl3.hs.dheSecret = NULL;
14181
62.0k
    ss->ssl3.hs.clientEarlyTrafficSecret = NULL;
14182
62.0k
    ss->ssl3.hs.clientHsTrafficSecret = NULL;
14183
62.0k
    ss->ssl3.hs.serverHsTrafficSecret = NULL;
14184
62.0k
    ss->ssl3.hs.clientTrafficSecret = NULL;
14185
62.0k
    ss->ssl3.hs.serverTrafficSecret = NULL;
14186
62.0k
    ss->ssl3.hs.echHpkeCtx = NULL;
14187
62.0k
    ss->ssl3.hs.greaseEchSize = 100;
14188
62.0k
    ss->ssl3.hs.echAccepted = PR_FALSE;
14189
62.0k
    ss->ssl3.hs.echDecided = PR_FALSE;
14190
14191
62.0k
    ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
14192
62.0k
    ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
14193
14194
62.0k
    PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
14195
62.0k
    ss->ssl3.hs.messages.buf = NULL;
14196
62.0k
    ss->ssl3.hs.messages.space = 0;
14197
14198
62.0k
    ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
14199
62.0k
    PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0,
14200
62.0k
                sizeof(ss->ssl3.hs.newSessionTicket));
14201
14202
62.0k
    ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
14203
14204
62.0k
    ss->ssl3.hs.dtlsReceivedHVR = PR_FALSE;
14205
62.0k
    return SECSuccess;
14206
62.0k
}
14207
14208
/* record the export policy for this cipher suite */
14209
SECStatus
14210
ssl3_SetPolicy(ssl3CipherSuite which, int policy)
14211
0
{
14212
0
    ssl3CipherSuiteCfg *suite;
14213
14214
0
    suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
14215
0
    if (suite == NULL) {
14216
0
        return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
14217
0
    }
14218
0
    suite->policy = policy;
14219
14220
0
    return SECSuccess;
14221
0
}
14222
14223
SECStatus
14224
ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
14225
0
{
14226
0
    const ssl3CipherSuiteCfg *suite;
14227
0
    PRInt32 policy;
14228
0
    SECStatus rv;
14229
14230
0
    suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
14231
0
    if (suite) {
14232
0
        policy = suite->policy;
14233
0
        rv = SECSuccess;
14234
0
    } else {
14235
0
        policy = SSL_NOT_ALLOWED;
14236
0
        rv = SECFailure; /* err code was set by Lookup. */
14237
0
    }
14238
0
    *oPolicy = policy;
14239
0
    return rv;
14240
0
}
14241
14242
/* record the user preference for this suite */
14243
SECStatus
14244
ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
14245
0
{
14246
0
    ssl3CipherSuiteCfg *suite;
14247
14248
0
    suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
14249
0
    if (suite == NULL) {
14250
0
        return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
14251
0
    }
14252
0
    suite->enabled = enabled;
14253
0
    return SECSuccess;
14254
0
}
14255
14256
/* return the user preference for this suite */
14257
SECStatus
14258
ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
14259
0
{
14260
0
    const ssl3CipherSuiteCfg *suite;
14261
0
    PRBool pref;
14262
0
    SECStatus rv;
14263
14264
0
    suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
14265
0
    if (suite) {
14266
0
        pref = suite->enabled;
14267
0
        rv = SECSuccess;
14268
0
    } else {
14269
0
        pref = SSL_NOT_ALLOWED;
14270
0
        rv = SECFailure; /* err code was set by Lookup. */
14271
0
    }
14272
0
    *enabled = pref;
14273
0
    return rv;
14274
0
}
14275
14276
SECStatus
14277
ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
14278
4.60M
{
14279
4.60M
    ssl3CipherSuiteCfg *suite;
14280
14281
4.60M
    suite = ssl_LookupCipherSuiteCfgMutable(which, ss->cipherSuites);
14282
4.60M
    if (suite == NULL) {
14283
0
        return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
14284
0
    }
14285
4.60M
    suite->enabled = enabled;
14286
4.60M
    return SECSuccess;
14287
4.60M
}
14288
14289
SECStatus
14290
ssl3_CipherPrefGet(const sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
14291
162k
{
14292
162k
    const ssl3CipherSuiteCfg *suite;
14293
162k
    PRBool pref;
14294
162k
    SECStatus rv;
14295
14296
162k
    suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
14297
162k
    if (suite) {
14298
162k
        pref = suite->enabled;
14299
162k
        rv = SECSuccess;
14300
162k
    } else {
14301
0
        pref = SSL_NOT_ALLOWED;
14302
0
        rv = SECFailure; /* err code was set by Lookup. */
14303
0
    }
14304
162k
    *enabled = pref;
14305
162k
    return rv;
14306
162k
}
14307
14308
SECStatus
14309
SSL_SignatureSchemePrefSet(PRFileDesc *fd, const SSLSignatureScheme *schemes,
14310
                           unsigned int count)
14311
0
{
14312
0
    sslSocket *ss;
14313
0
    unsigned int i;
14314
0
    unsigned int supported = 0;
14315
14316
0
    ss = ssl_FindSocket(fd);
14317
0
    if (!ss) {
14318
0
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefSet",
14319
0
                 SSL_GETPID(), fd));
14320
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14321
0
        return SECFailure;
14322
0
    }
14323
14324
0
    if (!count) {
14325
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14326
0
        return SECFailure;
14327
0
    }
14328
14329
0
    for (i = 0; i < count; ++i) {
14330
0
        if (ssl_IsSupportedSignatureScheme(schemes[i])) {
14331
0
            ++supported;
14332
0
        }
14333
0
    }
14334
    /* We don't check for duplicates, so it's possible to get too many. */
14335
0
    if (supported > MAX_SIGNATURE_SCHEMES) {
14336
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14337
0
        return SECFailure;
14338
0
    }
14339
14340
0
    ss->ssl3.signatureSchemeCount = 0;
14341
0
    for (i = 0; i < count; ++i) {
14342
0
        if (!ssl_IsSupportedSignatureScheme(schemes[i])) {
14343
0
            SSL_DBG(("%d: SSL[%d]: invalid signature scheme %d ignored",
14344
0
                     SSL_GETPID(), fd, schemes[i]));
14345
0
            continue;
14346
0
        }
14347
14348
0
        ss->ssl3.signatureSchemes[ss->ssl3.signatureSchemeCount++] = schemes[i];
14349
0
    }
14350
14351
0
    if (ss->ssl3.signatureSchemeCount == 0) {
14352
0
        PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
14353
0
        return SECFailure;
14354
0
    }
14355
0
    return SECSuccess;
14356
0
}
14357
14358
SECStatus
14359
SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms,
14360
                     unsigned int count)
14361
0
{
14362
0
    SSLSignatureScheme schemes[MAX_SIGNATURE_SCHEMES];
14363
0
    unsigned int i;
14364
14365
0
    count = PR_MIN(PR_ARRAY_SIZE(schemes), count);
14366
0
    for (i = 0; i < count; ++i) {
14367
0
        schemes[i] = (algorithms[i].hashAlg << 8) | algorithms[i].sigAlg;
14368
0
    }
14369
0
    return SSL_SignatureSchemePrefSet(fd, schemes, count);
14370
0
}
14371
14372
SECStatus
14373
SSL_SignatureSchemePrefGet(PRFileDesc *fd, SSLSignatureScheme *schemes,
14374
                           unsigned int *count, unsigned int maxCount)
14375
0
{
14376
0
    sslSocket *ss;
14377
14378
0
    ss = ssl_FindSocket(fd);
14379
0
    if (!ss) {
14380
0
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefGet",
14381
0
                 SSL_GETPID(), fd));
14382
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14383
0
        return SECFailure;
14384
0
    }
14385
14386
0
    if (!schemes || !count ||
14387
0
        maxCount < ss->ssl3.signatureSchemeCount) {
14388
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14389
0
        return SECFailure;
14390
0
    }
14391
14392
0
    PORT_Memcpy(schemes, ss->ssl3.signatureSchemes,
14393
0
                ss->ssl3.signatureSchemeCount * sizeof(SSLSignatureScheme));
14394
0
    *count = ss->ssl3.signatureSchemeCount;
14395
0
    return SECSuccess;
14396
0
}
14397
14398
SECStatus
14399
SSL_SignaturePrefGet(PRFileDesc *fd, SSLSignatureAndHashAlg *algorithms,
14400
                     unsigned int *count, unsigned int maxCount)
14401
0
{
14402
0
    sslSocket *ss;
14403
0
    unsigned int i;
14404
14405
0
    ss = ssl_FindSocket(fd);
14406
0
    if (!ss) {
14407
0
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignaturePrefGet",
14408
0
                 SSL_GETPID(), fd));
14409
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14410
0
        return SECFailure;
14411
0
    }
14412
14413
0
    if (!algorithms || !count ||
14414
0
        maxCount < ss->ssl3.signatureSchemeCount) {
14415
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14416
0
        return SECFailure;
14417
0
    }
14418
14419
0
    for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
14420
0
        algorithms[i].hashAlg = (ss->ssl3.signatureSchemes[i] >> 8) & 0xff;
14421
0
        algorithms[i].sigAlg = ss->ssl3.signatureSchemes[i] & 0xff;
14422
0
    }
14423
0
    *count = ss->ssl3.signatureSchemeCount;
14424
0
    return SECSuccess;
14425
0
}
14426
14427
unsigned int
14428
SSL_SignatureMaxCount(void)
14429
0
{
14430
0
    return MAX_SIGNATURE_SCHEMES;
14431
0
}
14432
14433
/* copy global default policy into socket. */
14434
void
14435
ssl3_InitSocketPolicy(sslSocket *ss)
14436
62.0k
{
14437
62.0k
    PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof(cipherSuites));
14438
62.0k
    PORT_Memcpy(ss->ssl3.signatureSchemes, defaultSignatureSchemes,
14439
62.0k
                sizeof(defaultSignatureSchemes));
14440
62.0k
    ss->ssl3.signatureSchemeCount = PR_ARRAY_SIZE(defaultSignatureSchemes);
14441
62.0k
}
14442
14443
/*
14444
** If ssl3 socket has completed the first handshake, and is in idle state,
14445
** then start a new handshake.
14446
** If flushCache is true, the SID cache will be flushed first, forcing a
14447
** "Full" handshake (not a session restart handshake), to be done.
14448
**
14449
** called from SSL_RedoHandshake(), which already holds the handshake locks.
14450
*/
14451
SECStatus
14452
ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
14453
0
{
14454
0
    sslSessionID *sid = ss->sec.ci.sid;
14455
0
    SECStatus rv;
14456
14457
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
14458
14459
0
    if (!ss->firstHsDone || (ss->ssl3.hs.ws != idle_handshake)) {
14460
0
        PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
14461
0
        return SECFailure;
14462
0
    }
14463
14464
0
    if (IS_DTLS(ss)) {
14465
0
        dtls_RehandshakeCleanup(ss);
14466
0
    }
14467
14468
0
    if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER ||
14469
0
        ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
14470
0
        PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
14471
0
        return SECFailure;
14472
0
    }
14473
0
    if (ss->version > ss->vrange.max || ss->version < ss->vrange.min) {
14474
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
14475
0
        return SECFailure;
14476
0
    }
14477
14478
0
    if (sid && flushCache) {
14479
0
        ssl_UncacheSessionID(ss);   /* remove it from whichever cache it's in. */
14480
0
        ssl_SetSocketSID(ss, NULL); /* dec ref count and free if zero. */
14481
0
    }
14482
14483
0
    ssl_GetXmitBufLock(ss); /**************************************/
14484
14485
    /* start off a new handshake. */
14486
0
    if (ss->sec.isServer) {
14487
0
        rv = ssl3_SendHelloRequest(ss);
14488
0
    } else {
14489
0
        rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
14490
0
    }
14491
14492
0
    ssl_ReleaseXmitBufLock(ss); /**************************************/
14493
0
    return rv;
14494
0
}
14495
14496
/* Called from ssl_DestroySocketContents() in sslsock.c */
14497
void
14498
ssl3_DestroySSL3Info(sslSocket *ss)
14499
62.0k
{
14500
14501
62.0k
    CERT_DestroyCertificate(ss->ssl3.clientCertificate);
14502
62.0k
    ss->ssl3.clientCertificate = NULL;
14503
14504
62.0k
    SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
14505
62.0k
    ss->ssl3.clientPrivateKey = NULL;
14506
14507
62.0k
    if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL) {
14508
0
        PORT_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
14509
0
        ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
14510
0
        ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
14511
0
    }
14512
14513
62.0k
    if (ss->ssl3.peerCertArena != NULL)
14514
31.5k
        ssl3_CleanupPeerCerts(ss);
14515
14516
62.0k
    if (ss->ssl3.clientCertChain != NULL) {
14517
0
        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
14518
0
        ss->ssl3.clientCertChain = NULL;
14519
0
    }
14520
62.0k
    if (ss->ssl3.ca_list) {
14521
0
        CERT_FreeDistNames(ss->ssl3.ca_list);
14522
0
        ss->ssl3.ca_list = NULL;
14523
0
    }
14524
14525
    /* clean up handshake */
14526
62.0k
    if (ss->ssl3.hs.md5) {
14527
7.83k
        PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
14528
7.83k
        ss->ssl3.hs.md5 = NULL;
14529
7.83k
    }
14530
62.0k
    if (ss->ssl3.hs.sha) {
14531
13.3k
        PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
14532
13.3k
        ss->ssl3.hs.sha = NULL;
14533
13.3k
    }
14534
62.0k
    if (ss->ssl3.hs.shaEchInner) {
14535
96
        PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
14536
96
        ss->ssl3.hs.shaEchInner = NULL;
14537
96
    }
14538
62.0k
    if (ss->ssl3.hs.shaPostHandshake) {
14539
0
        PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
14540
0
        ss->ssl3.hs.shaPostHandshake = NULL;
14541
0
    }
14542
62.0k
    if (ss->ssl3.hs.messages.buf) {
14543
43.7k
        sslBuffer_Clear(&ss->ssl3.hs.messages);
14544
43.7k
    }
14545
62.0k
    if (ss->ssl3.hs.echInnerMessages.buf) {
14546
2.77k
        sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
14547
2.77k
    }
14548
62.0k
    if (ss->ssl3.hs.dtls13ClientMessageBuffer.buf) {
14549
1.86k
        sslBuffer_Clear(&ss->ssl3.hs.dtls13ClientMessageBuffer);
14550
1.86k
    }
14551
14552
    /* free the SSL3Buffer (msg_body) */
14553
62.0k
    PORT_Free(ss->ssl3.hs.msg_body.buf);
14554
62.0k
    ss->ssl3.hs.msg_body.buf = NULL;
14555
14556
62.0k
    SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
14557
62.0k
    SECITEM_FreeItem(&ss->ssl3.hs.srvVirtName, PR_FALSE);
14558
62.0k
    SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
14559
62.0k
    SECITEM_FreeItem(&ss->ssl3.hs.cookie, PR_FALSE);
14560
14561
    /* Destroy the DTLS data */
14562
62.0k
    if (IS_DTLS(ss)) {
14563
29.0k
        dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
14564
29.0k
        if (ss->ssl3.hs.recvdFragments.buf) {
14565
1.00k
            PORT_Free(ss->ssl3.hs.recvdFragments.buf);
14566
1.00k
        }
14567
29.0k
    }
14568
14569
    /* Destroy remote extensions */
14570
62.0k
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
14571
62.0k
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.echOuterExtensions);
14572
62.0k
    ssl3_DestroyExtensionData(&ss->xtnData);
14573
14574
    /* Destroy cipher specs */
14575
62.0k
    ssl_DestroyCipherSpecs(&ss->ssl3.hs.cipherSpecs);
14576
14577
    /* Destroy TLS 1.3 keys */
14578
62.0k
    PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
14579
62.0k
    ss->ssl3.hs.currentSecret = NULL;
14580
62.0k
    PK11_FreeSymKey(ss->ssl3.hs.resumptionMasterSecret);
14581
62.0k
    ss->ssl3.hs.resumptionMasterSecret = NULL;
14582
62.0k
    PK11_FreeSymKey(ss->ssl3.hs.dheSecret);
14583
62.0k
    ss->ssl3.hs.dheSecret = NULL;
14584
62.0k
    PK11_FreeSymKey(ss->ssl3.hs.clientEarlyTrafficSecret);
14585
62.0k
    ss->ssl3.hs.clientEarlyTrafficSecret = NULL;
14586
62.0k
    PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
14587
62.0k
    ss->ssl3.hs.clientHsTrafficSecret = NULL;
14588
62.0k
    PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
14589
62.0k
    ss->ssl3.hs.serverHsTrafficSecret = NULL;
14590
62.0k
    PK11_FreeSymKey(ss->ssl3.hs.clientTrafficSecret);
14591
62.0k
    ss->ssl3.hs.clientTrafficSecret = NULL;
14592
62.0k
    PK11_FreeSymKey(ss->ssl3.hs.serverTrafficSecret);
14593
62.0k
    ss->ssl3.hs.serverTrafficSecret = NULL;
14594
62.0k
    PK11_FreeSymKey(ss->ssl3.hs.earlyExporterSecret);
14595
62.0k
    ss->ssl3.hs.earlyExporterSecret = NULL;
14596
62.0k
    PK11_FreeSymKey(ss->ssl3.hs.exporterSecret);
14597
62.0k
    ss->ssl3.hs.exporterSecret = NULL;
14598
14599
62.0k
    ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
14600
    /* Destroy TLS 1.3 buffered early data. */
14601
62.0k
    tls13_DestroyEarlyData(&ss->ssl3.hs.bufferedEarlyData);
14602
14603
    /* Destroy TLS 1.3 PSKs. */
14604
62.0k
    tls13_DestroyPskList(&ss->ssl3.hs.psks);
14605
14606
    /* TLS 1.3 ECH state. */
14607
62.0k
    PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE);
14608
62.0k
    ss->ssl3.hs.echHpkeCtx = NULL;
14609
62.0k
    PORT_Free((void *)ss->ssl3.hs.echPublicName); /* CONST */
14610
62.0k
    ss->ssl3.hs.echPublicName = NULL;
14611
62.0k
    sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
14612
14613
    /* TLS 1.3 GREASE (client) state. */
14614
62.0k
    tls13_ClientGreaseDestroy(ss);
14615
14616
    /* TLS ClientHello Extension Permutation state. */
14617
62.0k
    tls_ClientHelloExtensionPermutationDestroy(ss);
14618
62.0k
}
14619
14620
/* check if the current cipher spec is FIPS. We only need to
14621
 * check the contexts here, if the kea, prf or keys were not FIPS,
14622
 * that status would have been rolled up in the create context
14623
 * call */
14624
static PRBool
14625
ssl_cipherSpecIsFips(ssl3CipherSpec *spec)
14626
0
{
14627
0
    if (!spec || !spec->cipherDef) {
14628
0
        return PR_FALSE;
14629
0
    }
14630
14631
0
    if (spec->cipherDef->type != type_aead) {
14632
0
        if (spec->keyMaterial.macContext == NULL) {
14633
0
            return PR_FALSE;
14634
0
        }
14635
0
        if (!PK11_ContextGetFIPSStatus(spec->keyMaterial.macContext)) {
14636
0
            return PR_FALSE;
14637
0
        }
14638
0
    }
14639
0
    if (!spec->cipherContext) {
14640
0
        return PR_FALSE;
14641
0
    }
14642
0
    return PK11_ContextGetFIPSStatus(spec->cipherContext);
14643
0
}
14644
14645
/* return true if the current operation is running in FIPS mode */
14646
PRBool
14647
ssl_isFIPS(sslSocket *ss)
14648
0
{
14649
0
    PRBool isFIPS;
14650
14651
0
    ssl_GetSpecReadLock(ss);
14652
0
    isFIPS = ssl_cipherSpecIsFips(ss->ssl3.crSpec) &&
14653
0
             ssl_cipherSpecIsFips(ss->ssl3.cwSpec);
14654
0
    ssl_ReleaseSpecReadLock(ss);
14655
14656
0
    return isFIPS;
14657
0
}
14658
14659
/*
14660
 * parse the policy value for a single algorithm in a cipher_suite,
14661
 *   return TRUE if we disallow by the cipher suite by policy
14662
 *   (we don't have to parse any more algorithm policies on this cipher suite),
14663
 *  otherwise return FALSE.
14664
 *   1. If we don't have the required policy, disable by default, disallow by
14665
 *      policy and return TRUE (no more processing needed).
14666
 *   2. If we have the required policy, and we are disabled, return FALSE,
14667
 *      (if we are disabled, we only need to parse policy, not default).
14668
 *   3. If we have the required policy, and we aren't adjusting the defaults
14669
 *      return FALSE. (only parsing the policy, not default).
14670
 *   4. We have the required policy and we are adjusting the defaults.
14671
 *      If we are setting default = FALSE, set isDisabled to true so that
14672
 *      we don't try to re-enable the cipher suite based on a different
14673
 *      algorithm.
14674
 */
14675
PRBool
14676
ssl_HandlePolicy(int cipher_suite, SECOidTag policyOid,
14677
                 PRUint32 requiredPolicy, PRBool *isDisabled)
14678
0
{
14679
0
    PRUint32 policy;
14680
0
    SECStatus rv;
14681
14682
    /* first fetch the policy for this algorithm */
14683
0
    rv = NSS_GetAlgorithmPolicy(policyOid, &policy);
14684
0
    if (rv != SECSuccess) {
14685
0
        return PR_FALSE; /* no policy value, continue to the next algorithm */
14686
0
    }
14687
    /* first, are we allowed by policy, if not turn off allow and disable */
14688
0
    if (!(policy & requiredPolicy)) {
14689
0
        ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE);
14690
0
        ssl_CipherPolicySet(cipher_suite, SSL_NOT_ALLOWED);
14691
0
        return PR_TRUE;
14692
0
    }
14693
    /* If we are already disabled, or the policy isn't setting a default
14694
     * we are done processing this algorithm */
14695
0
    if (*isDisabled || (policy & NSS_USE_DEFAULT_NOT_VALID)) {
14696
0
        return PR_FALSE;
14697
0
    }
14698
    /* set the default value for the cipher suite. If we disable the cipher
14699
     * suite, remember that so we don't process the next default. This has
14700
     * the effect of disabling the whole cipher suite if any of the
14701
     * algorithms it uses are disabled by default. We still have to
14702
     * process the upper level because the cipher suite is still allowed
14703
     * by policy, and we may still have to disallow it based on other
14704
     * algorithms in the cipher suite. */
14705
0
    if (policy & NSS_USE_DEFAULT_SSL_ENABLE) {
14706
0
        ssl_CipherPrefSetDefault(cipher_suite, PR_TRUE);
14707
0
    } else {
14708
0
        *isDisabled = PR_TRUE;
14709
0
        ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE);
14710
0
    }
14711
0
    return PR_FALSE;
14712
0
}
14713
14714
0
#define MAP_NULL(x) (((x) != 0) ? (x) : SEC_OID_NULL_CIPHER)
14715
14716
SECStatus
14717
ssl3_ApplyNSSPolicy(void)
14718
9
{
14719
9
    unsigned i;
14720
9
    SECStatus rv;
14721
9
    PRUint32 policy = 0;
14722
14723
9
    rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy);
14724
9
    if (rv != SECSuccess || !(policy & NSS_USE_POLICY_IN_SSL)) {
14725
9
        return SECSuccess; /* do nothing */
14726
9
    }
14727
14728
    /* disable every ciphersuite */
14729
0
    for (i = 1; i < PR_ARRAY_SIZE(cipher_suite_defs); ++i) {
14730
0
        const ssl3CipherSuiteDef *suite = &cipher_suite_defs[i];
14731
0
        SECOidTag policyOid;
14732
0
        PRBool isDisabled = PR_FALSE;
14733
14734
        /* if we haven't explicitly disabled it below enable by policy */
14735
0
        ssl_CipherPolicySet(suite->cipher_suite, SSL_ALLOWED);
14736
14737
        /* now check the various key exchange, ciphers and macs and
14738
         * if we ever disallow by policy, we are done, go to the next cipher
14739
         */
14740
0
        policyOid = MAP_NULL(kea_defs[suite->key_exchange_alg].oid);
14741
0
        if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14742
0
                             NSS_USE_ALG_IN_SSL_KX, &isDisabled)) {
14743
0
            continue;
14744
0
        }
14745
14746
0
        policyOid = MAP_NULL(ssl_GetBulkCipherDef(suite)->oid);
14747
0
        if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14748
0
                             NSS_USE_ALG_IN_SSL, &isDisabled)) {
14749
0
            continue;
14750
0
        }
14751
14752
0
        if (ssl_GetBulkCipherDef(suite)->type != type_aead) {
14753
0
            policyOid = MAP_NULL(ssl_GetMacDefByAlg(suite->mac_alg)->oid);
14754
0
            if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14755
0
                                 NSS_USE_ALG_IN_SSL, &isDisabled)) {
14756
0
                continue;
14757
0
            }
14758
0
        }
14759
0
    }
14760
14761
0
    rv = ssl3_ConstrainRangeByPolicy();
14762
14763
0
    return rv;
14764
9
}
14765
14766
/* End of ssl3con.c */