Coverage Report

Created: 2024-05-20 06:23

/src/nss/lib/ssl/ssl3con.c
Line
Count
Source (jump to first uncovered line)
1
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
/*
3
 * SSL3 Protocol
4
 *
5
 * This Source Code Form is subject to the terms of the Mozilla Public
6
 * License, v. 2.0. If a copy of the MPL was not distributed with this
7
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8
9
/* TODO(ekr): Implement HelloVerifyRequest on server side. OK for now. */
10
11
#include "cert.h"
12
#include "ssl.h"
13
#include "cryptohi.h" /* for DSAU_ stuff */
14
#include "keyhi.h"
15
#include "secder.h"
16
#include "secitem.h"
17
#include "sechash.h"
18
19
#include "sslimpl.h"
20
#include "sslproto.h"
21
#include "sslerr.h"
22
#include "ssl3ext.h"
23
#include "ssl3exthandle.h"
24
#include "tls13ech.h"
25
#include "tls13exthandle.h"
26
#include "tls13psk.h"
27
#include "tls13subcerts.h"
28
#include "prtime.h"
29
#include "prinrval.h"
30
#include "prerror.h"
31
#include "pratom.h"
32
#include "prthread.h"
33
#include "nss.h"
34
#include "nssoptions.h"
35
36
#include "pk11func.h"
37
#include "secmod.h"
38
#include "blapi.h"
39
40
#include <stdio.h>
41
42
static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
43
                                       PK11SlotInfo *serverKeySlot);
44
static SECStatus ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
45
                                          PK11SymKey **msp);
46
static SECStatus ssl3_DeriveConnectionKeys(sslSocket *ss,
47
                                           PK11SymKey *masterSecret);
48
static SECStatus ssl3_HandshakeFailure(sslSocket *ss);
49
static SECStatus ssl3_SendCertificate(sslSocket *ss);
50
static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
51
static SECStatus ssl3_SendNextProto(sslSocket *ss);
52
static SECStatus ssl3_SendFinished(sslSocket *ss, PRInt32 flags);
53
static SECStatus ssl3_SendServerHelloDone(sslSocket *ss);
54
static SECStatus ssl3_SendServerKeyExchange(sslSocket *ss);
55
static SECStatus ssl3_HandleClientHelloPart2(sslSocket *ss,
56
                                             SECItem *suites,
57
                                             sslSessionID *sid,
58
                                             const PRUint8 *msg,
59
                                             unsigned int len);
60
static SECStatus ssl3_HandleServerHelloPart2(sslSocket *ss,
61
                                             const SECItem *sidBytes,
62
                                             int *retErrCode);
63
static SECStatus ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss,
64
                                                      PRUint8 *b,
65
                                                      PRUint32 length);
66
static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
67
static CK_MECHANISM_TYPE ssl3_GetHashMechanismByHashType(SSLHashType hashType);
68
static CK_MECHANISM_TYPE ssl3_GetMgfMechanismByHashType(SSLHashType hash);
69
PRBool ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme);
70
PRBool ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme);
71
PRBool ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme);
72
PRBool ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme);
73
static SECStatus ssl3_UpdateDefaultHandshakeHashes(sslSocket *ss,
74
                                                   const unsigned char *b,
75
                                                   unsigned int l);
76
const PRUint32 kSSLSigSchemePolicy =
77
    NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_ANY_SIGNATURE;
78
79
const PRUint8 ssl_hello_retry_random[] = {
80
    0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
81
    0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
82
    0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
83
    0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
84
};
85
PR_STATIC_ASSERT(PR_ARRAY_SIZE(ssl_hello_retry_random) == SSL3_RANDOM_LENGTH);
86
87
/* This list of SSL3 cipher suites is sorted in descending order of
88
 * precedence (desirability).  It only includes cipher suites we implement.
89
 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
90
 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
91
 *
92
 * Important: See bug 946147 before enabling, reordering, or adding any cipher
93
 * suites to this list.
94
 */
95
/* clang-format off */
96
static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
97
   /*      cipher_suite                     policy       enabled   isPresent */
98
 /* Special TLS 1.3 suites. */
99
 { TLS_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE },
100
 { TLS_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE },
101
 { TLS_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE },
102
103
 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
104
 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,   SSL_ALLOWED, PR_TRUE, PR_FALSE},
105
 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
106
 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,   SSL_ALLOWED, PR_TRUE, PR_FALSE},
107
 { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE},
108
 { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,   SSL_ALLOWED, PR_TRUE, PR_FALSE},
109
   /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around
110
    * bug 946147.
111
    */
112
 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,    SSL_ALLOWED, PR_TRUE, PR_FALSE},
113
 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,    SSL_ALLOWED, PR_TRUE, PR_FALSE},
114
 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,      SSL_ALLOWED, PR_TRUE, PR_FALSE},
115
 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
116
 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,   SSL_ALLOWED, PR_TRUE, PR_FALSE},
117
 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,      SSL_ALLOWED, PR_TRUE, PR_FALSE},
118
 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE},
119
 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
120
 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
121
 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
122
 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,        SSL_ALLOWED, PR_FALSE, PR_FALSE},
123
 { TLS_ECDHE_RSA_WITH_RC4_128_SHA,          SSL_ALLOWED, PR_FALSE, PR_FALSE},
124
125
 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
126
 { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,SSL_ALLOWED,PR_TRUE,  PR_FALSE},
127
 { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
128
 { TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
129
 { TLS_DHE_DSS_WITH_AES_256_GCM_SHA384,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
130
 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
131
 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
132
 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
133
 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
134
 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
135
 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
136
 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
137
 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
138
 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
139
 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
140
 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
141
 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
142
 { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,       SSL_ALLOWED, PR_TRUE,  PR_FALSE},
143
 { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,       SSL_ALLOWED, PR_TRUE,  PR_FALSE},
144
 { TLS_DHE_DSS_WITH_RC4_128_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
145
146
 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
147
 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
148
 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
149
 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
150
 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,    SSL_ALLOWED, PR_FALSE, PR_FALSE},
151
 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
152
 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA,         SSL_ALLOWED, PR_FALSE, PR_FALSE},
153
 { TLS_ECDH_RSA_WITH_RC4_128_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
154
155
 /* RSA */
156
 { TLS_RSA_WITH_AES_128_GCM_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
157
 { TLS_RSA_WITH_AES_256_GCM_SHA384,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
158
 { TLS_RSA_WITH_AES_128_CBC_SHA,            SSL_ALLOWED, PR_TRUE,  PR_FALSE},
159
 { TLS_RSA_WITH_AES_128_CBC_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
160
 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
161
 { TLS_RSA_WITH_AES_256_CBC_SHA,            SSL_ALLOWED, PR_TRUE,  PR_FALSE},
162
 { TLS_RSA_WITH_AES_256_CBC_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
163
 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
164
 { TLS_RSA_WITH_SEED_CBC_SHA,               SSL_ALLOWED, PR_FALSE, PR_FALSE},
165
 { TLS_RSA_WITH_3DES_EDE_CBC_SHA,           SSL_ALLOWED, PR_TRUE,  PR_FALSE},
166
 { TLS_RSA_WITH_RC4_128_SHA,                SSL_ALLOWED, PR_TRUE,  PR_FALSE},
167
 { TLS_RSA_WITH_RC4_128_MD5,                SSL_ALLOWED, PR_TRUE,  PR_FALSE},
168
169
 /* 56-bit DES "domestic" cipher suites */
170
 { TLS_DHE_RSA_WITH_DES_CBC_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
171
 { TLS_DHE_DSS_WITH_DES_CBC_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
172
 { TLS_RSA_WITH_DES_CBC_SHA,                SSL_ALLOWED, PR_FALSE, PR_FALSE},
173
174
 /* ciphersuites with no encryption */
175
 { TLS_ECDHE_ECDSA_WITH_NULL_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
176
 { TLS_ECDHE_RSA_WITH_NULL_SHA,             SSL_ALLOWED, PR_FALSE, PR_FALSE},
177
 { TLS_ECDH_RSA_WITH_NULL_SHA,              SSL_ALLOWED, PR_FALSE, PR_FALSE},
178
 { TLS_ECDH_ECDSA_WITH_NULL_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
179
 { TLS_RSA_WITH_NULL_SHA,                   SSL_ALLOWED, PR_FALSE, PR_FALSE},
180
 { TLS_RSA_WITH_NULL_SHA256,                SSL_ALLOWED, PR_FALSE, PR_FALSE},
181
 { TLS_RSA_WITH_NULL_MD5,                   SSL_ALLOWED, PR_FALSE, PR_FALSE},
182
};
183
/* clang-format on */
184
185
/* This is the default supported set of signature schemes.  The order of the
186
 * hashes here is all that is important, since that will (sometimes) determine
187
 * which hash we use.  The key pair (i.e., cert) is the primary thing that
188
 * determines what we use and this doesn't affect how we select key pairs.  The
189
 * order of signature types is based on the same rules for ordering we use for
190
 * cipher suites just for consistency.
191
 */
192
static const SSLSignatureScheme defaultSignatureSchemes[] = {
193
    ssl_sig_ecdsa_secp256r1_sha256,
194
    ssl_sig_ecdsa_secp384r1_sha384,
195
    ssl_sig_ecdsa_secp521r1_sha512,
196
    ssl_sig_ecdsa_sha1,
197
    ssl_sig_rsa_pss_rsae_sha256,
198
    ssl_sig_rsa_pss_rsae_sha384,
199
    ssl_sig_rsa_pss_rsae_sha512,
200
    ssl_sig_rsa_pkcs1_sha256,
201
    ssl_sig_rsa_pkcs1_sha384,
202
    ssl_sig_rsa_pkcs1_sha512,
203
    ssl_sig_rsa_pkcs1_sha1,
204
    ssl_sig_dsa_sha256,
205
    ssl_sig_dsa_sha384,
206
    ssl_sig_dsa_sha512,
207
    ssl_sig_dsa_sha1
208
};
209
PR_STATIC_ASSERT(PR_ARRAY_SIZE(defaultSignatureSchemes) <=
210
                 MAX_SIGNATURE_SCHEMES);
211
212
/* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order.
213
 */
214
#ifdef DEBUG
215
void
216
ssl3_CheckCipherSuiteOrderConsistency()
217
1
{
218
1
    unsigned int i;
219
220
1
    PORT_Assert(SSL_NumImplementedCiphers == PR_ARRAY_SIZE(cipherSuites));
221
222
72
    for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) {
223
71
        PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite);
224
71
    }
225
1
}
226
#endif
227
228
static const /*SSL3ClientCertificateType */ PRUint8 certificate_types[] = {
229
    ct_RSA_sign,
230
    ct_ECDSA_sign,
231
    ct_DSS_sign,
232
};
233
234
static SSL3Statistics ssl3stats;
235
236
static const ssl3KEADef kea_defs[] = {
237
    /* indexed by SSL3KeyExchangeAlgorithm */
238
    /* kea            exchKeyType signKeyType authKeyType ephemeral  oid */
239
    { kea_null, ssl_kea_null, nullKey, ssl_auth_null, PR_FALSE, 0 },
240
    { kea_rsa, ssl_kea_rsa, nullKey, ssl_auth_rsa_decrypt, PR_FALSE, SEC_OID_TLS_RSA },
241
    { kea_dh_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_FALSE, SEC_OID_TLS_DH_DSS },
242
    { kea_dh_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_FALSE, SEC_OID_TLS_DH_RSA },
243
    { kea_dhe_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_TRUE, SEC_OID_TLS_DHE_DSS },
244
    { kea_dhe_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_DHE_RSA },
245
    { kea_dh_anon, ssl_kea_dh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_DH_ANON },
246
    { kea_ecdh_ecdsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_ecdsa, PR_FALSE, SEC_OID_TLS_ECDH_ECDSA },
247
    { kea_ecdhe_ecdsa, ssl_kea_ecdh, ecKey, ssl_auth_ecdsa, PR_TRUE, SEC_OID_TLS_ECDHE_ECDSA },
248
    { kea_ecdh_rsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_rsa, PR_FALSE, SEC_OID_TLS_ECDH_RSA },
249
    { kea_ecdhe_rsa, ssl_kea_ecdh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_ECDHE_RSA },
250
    { kea_ecdh_anon, ssl_kea_ecdh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_ECDH_ANON },
251
    { kea_ecdhe_psk, ssl_kea_ecdh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_ECDHE_PSK },
252
    { kea_dhe_psk, ssl_kea_dh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_DHE_PSK },
253
    { kea_tls13_any, ssl_kea_tls13_any, nullKey, ssl_auth_tls13_any, PR_TRUE, SEC_OID_TLS13_KEA_ANY },
254
};
255
256
/* must use ssl_LookupCipherSuiteDef to access */
257
static const ssl3CipherSuiteDef cipher_suite_defs[] = {
258
    /*  cipher_suite                    bulk_cipher_alg mac_alg key_exchange_alg prf_hash */
259
    /*  Note that the prf_hash_alg is the hash function used by the PRF, see sslimpl.h.  */
260
261
    { TLS_NULL_WITH_NULL_NULL, cipher_null, ssl_mac_null, kea_null, ssl_hash_none },
262
    { TLS_RSA_WITH_NULL_MD5, cipher_null, ssl_mac_md5, kea_rsa, ssl_hash_none },
263
    { TLS_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_rsa, ssl_hash_none },
264
    { TLS_RSA_WITH_NULL_SHA256, cipher_null, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
265
    { TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, ssl_mac_md5, kea_rsa, ssl_hash_none },
266
    { TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_rsa, ssl_hash_none },
267
    { TLS_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_rsa, ssl_hash_none },
268
    { TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_rsa, ssl_hash_none },
269
    { TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
270
    { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
271
      cipher_3des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
272
    { TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
273
    { TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
274
    { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
275
      cipher_3des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
276
277
    /* New TLS cipher suites */
278
    { TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
279
    { TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
280
    { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
281
    { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
282
    { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
283
    { TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
284
    { TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
285
    { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
286
    { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
287
    { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
288
    { TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha384 },
289
290
    { TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, ssl_mac_sha, kea_rsa, ssl_hash_none },
291
292
    { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
293
    { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
294
      cipher_camellia_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
295
    { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
296
      cipher_camellia_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
297
    { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
298
    { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
299
      cipher_camellia_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
300
    { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
301
      cipher_camellia_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
302
303
    { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
304
    { TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha256 },
305
306
    { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
307
    { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
308
    { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha384 },
309
    { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha384 },
310
    { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_ecdsa, ssl_hash_sha384 },
311
    { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_rsa, ssl_hash_sha384 },
312
    { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha256 },
313
    { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
314
    { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
315
    { TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha384 },
316
    { TLS_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha384 },
317
318
    { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
319
320
    { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
321
    { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
322
323
    { TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
324
    { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
325
    { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
326
    { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
327
    { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
328
329
    { TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
330
    { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
331
    { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
332
    { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
333
    { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_ecdsa, ssl_hash_sha256 },
334
    { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
335
336
    { TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
337
    { TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
338
    { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
339
    { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
340
    { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
341
342
    { TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
343
    { TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
344
    { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
345
    { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
346
    { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_rsa, ssl_hash_sha256 },
347
    { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
348
349
    { TLS_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
350
    { TLS_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
351
    { TLS_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha384 },
352
};
353
354
static const CK_MECHANISM_TYPE auth_alg_defs[] = {
355
    CKM_INVALID_MECHANISM, /* ssl_auth_null */
356
    CKM_RSA_PKCS,          /* ssl_auth_rsa_decrypt */
357
    CKM_DSA, /* ? _SHA1 */ /* ssl_auth_dsa */
358
    CKM_INVALID_MECHANISM, /* ssl_auth_kea (unused) */
359
    CKM_ECDSA,             /* ssl_auth_ecdsa */
360
    CKM_ECDH1_DERIVE,      /* ssl_auth_ecdh_rsa */
361
    CKM_ECDH1_DERIVE,      /* ssl_auth_ecdh_ecdsa */
362
    CKM_RSA_PKCS,          /* ssl_auth_rsa_sign */
363
    CKM_RSA_PKCS_PSS,      /* ssl_auth_rsa_pss */
364
    CKM_NSS_HKDF_SHA256,   /* ssl_auth_psk (just check for HKDF) */
365
    CKM_INVALID_MECHANISM  /* ssl_auth_tls13_any */
366
};
367
PR_STATIC_ASSERT(PR_ARRAY_SIZE(auth_alg_defs) == ssl_auth_size);
368
369
static const CK_MECHANISM_TYPE kea_alg_defs[] = {
370
    CKM_INVALID_MECHANISM, /* ssl_kea_null */
371
    CKM_RSA_PKCS,          /* ssl_kea_rsa */
372
    CKM_DH_PKCS_DERIVE,    /* ssl_kea_dh */
373
    CKM_INVALID_MECHANISM, /* ssl_kea_fortezza (unused) */
374
    CKM_ECDH1_DERIVE,      /* ssl_kea_ecdh */
375
    CKM_ECDH1_DERIVE,      /* ssl_kea_ecdh_psk */
376
    CKM_DH_PKCS_DERIVE,    /* ssl_kea_dh_psk */
377
    CKM_INVALID_MECHANISM, /* ssl_kea_tls13_any */
378
    CKM_INVALID_MECHANISM, /* ssl_kea_ecdh_hybrid */
379
    CKM_INVALID_MECHANISM, /* ssl_kea_ecdh_hybrid_psk */
380
};
381
PR_STATIC_ASSERT(PR_ARRAY_SIZE(kea_alg_defs) == ssl_kea_size);
382
383
typedef struct SSLCipher2MechStr {
384
    SSLCipherAlgorithm calg;
385
    CK_MECHANISM_TYPE cmech;
386
} SSLCipher2Mech;
387
388
/* indexed by type SSLCipherAlgorithm */
389
static const SSLCipher2Mech alg2Mech[] = {
390
    /* calg,          cmech  */
391
    { ssl_calg_null, CKM_INVALID_MECHANISM },
392
    { ssl_calg_rc4, CKM_RC4 },
393
    { ssl_calg_rc2, CKM_RC2_CBC },
394
    { ssl_calg_des, CKM_DES_CBC },
395
    { ssl_calg_3des, CKM_DES3_CBC },
396
    { ssl_calg_idea, CKM_IDEA_CBC },
397
    { ssl_calg_fortezza, CKM_SKIPJACK_CBC64 },
398
    { ssl_calg_aes, CKM_AES_CBC },
399
    { ssl_calg_camellia, CKM_CAMELLIA_CBC },
400
    { ssl_calg_seed, CKM_SEED_CBC },
401
    { ssl_calg_aes_gcm, CKM_AES_GCM },
402
    { ssl_calg_chacha20, CKM_CHACHA20_POLY1305 },
403
};
404
405
const PRUint8 tls12_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
406
                                           0x47, 0x52, 0x44, 0x01 };
407
const PRUint8 tls1_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
408
                                          0x47, 0x52, 0x44, 0x00 };
409
PR_STATIC_ASSERT(sizeof(tls12_downgrade_random) ==
410
                 sizeof(tls1_downgrade_random));
411
412
/* The ECCWrappedKeyInfo structure defines how various pieces of
413
 * information are laid out within wrappedSymmetricWrappingkey
414
 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
415
 * a 512-byte buffer (see sslimpl.h), the variable length field
416
 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
417
 *
418
 * XXX For now, NSS only supports named elliptic curves of size 571 bits
419
 * or smaller. The public value will fit within 145 bytes and EC params
420
 * will fit within 12 bytes. We'll need to revisit this when NSS
421
 * supports arbitrary curves.
422
 */
423
0
#define MAX_EC_WRAPPED_KEY_BUFLEN 504
424
425
typedef struct ECCWrappedKeyInfoStr {
426
    PRUint16 size;                          /* EC public key size in bits */
427
    PRUint16 encodedParamLen;               /* length (in bytes) of DER encoded EC params */
428
    PRUint16 pubValueLen;                   /* length (in bytes) of EC public value */
429
    PRUint16 wrappedKeyLen;                 /* length (in bytes) of the wrapped key */
430
    PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
431
    /* EC public-key params, the EC public value and the wrapped key  */
432
} ECCWrappedKeyInfo;
433
434
CK_MECHANISM_TYPE
435
ssl3_Alg2Mech(SSLCipherAlgorithm calg)
436
389k
{
437
389k
    PORT_Assert(alg2Mech[calg].calg == calg);
438
389k
    return alg2Mech[calg].cmech;
439
389k
}
440
441
#if defined(TRACE)
442
443
static char *
444
ssl3_DecodeHandshakeType(int msgType)
445
0
{
446
0
    char *rv;
447
0
    static char line[40];
448
449
0
    switch (msgType) {
450
0
        case ssl_hs_hello_request:
451
0
            rv = "hello_request (0)";
452
0
            break;
453
0
        case ssl_hs_client_hello:
454
0
            rv = "client_hello  (1)";
455
0
            break;
456
0
        case ssl_hs_server_hello:
457
0
            rv = "server_hello  (2)";
458
0
            break;
459
0
        case ssl_hs_hello_verify_request:
460
0
            rv = "hello_verify_request (3)";
461
0
            break;
462
0
        case ssl_hs_new_session_ticket:
463
0
            rv = "new_session_ticket (4)";
464
0
            break;
465
0
        case ssl_hs_end_of_early_data:
466
0
            rv = "end_of_early_data (5)";
467
0
            break;
468
0
        case ssl_hs_hello_retry_request:
469
0
            rv = "hello_retry_request (6)";
470
0
            break;
471
0
        case ssl_hs_encrypted_extensions:
472
0
            rv = "encrypted_extensions (8)";
473
0
            break;
474
0
        case ssl_hs_certificate:
475
0
            rv = "certificate  (11)";
476
0
            break;
477
0
        case ssl_hs_server_key_exchange:
478
0
            rv = "server_key_exchange (12)";
479
0
            break;
480
0
        case ssl_hs_certificate_request:
481
0
            rv = "certificate_request (13)";
482
0
            break;
483
0
        case ssl_hs_server_hello_done:
484
0
            rv = "server_hello_done   (14)";
485
0
            break;
486
0
        case ssl_hs_certificate_verify:
487
0
            rv = "certificate_verify  (15)";
488
0
            break;
489
0
        case ssl_hs_client_key_exchange:
490
0
            rv = "client_key_exchange (16)";
491
0
            break;
492
0
        case ssl_hs_finished:
493
0
            rv = "finished     (20)";
494
0
            break;
495
0
        case ssl_hs_certificate_status:
496
0
            rv = "certificate_status  (22)";
497
0
            break;
498
0
        case ssl_hs_key_update:
499
0
            rv = "key_update   (24)";
500
0
            break;
501
0
        case ssl_hs_compressed_certificate:
502
0
            rv = "compressed certificate (25)";
503
0
            break;
504
0
        default:
505
0
            snprintf(line, sizeof(line), "*UNKNOWN* handshake type! (%d)", msgType);
506
0
            rv = line;
507
0
    }
508
0
    return rv;
509
0
}
510
511
static char *
512
ssl3_DecodeContentType(int msgType)
513
0
{
514
0
    char *rv;
515
0
    static char line[40];
516
517
0
    switch (msgType) {
518
0
        case ssl_ct_change_cipher_spec:
519
0
            rv = "change_cipher_spec (20)";
520
0
            break;
521
0
        case ssl_ct_alert:
522
0
            rv = "alert      (21)";
523
0
            break;
524
0
        case ssl_ct_handshake:
525
0
            rv = "handshake  (22)";
526
0
            break;
527
0
        case ssl_ct_application_data:
528
0
            rv = "application_data (23)";
529
0
            break;
530
0
        case ssl_ct_ack:
531
0
            rv = "ack (26)";
532
0
            break;
533
0
        default:
534
0
            snprintf(line, sizeof(line), "*UNKNOWN* record type! (%d)", msgType);
535
0
            rv = line;
536
0
    }
537
0
    return rv;
538
0
}
539
540
#endif
541
542
SSL3Statistics *
543
SSL_GetStatistics(void)
544
0
{
545
0
    return &ssl3stats;
546
0
}
547
548
typedef struct tooLongStr {
549
#if defined(IS_LITTLE_ENDIAN)
550
    PRInt32 low;
551
    PRInt32 high;
552
#else
553
    PRInt32 high;
554
    PRInt32 low;
555
#endif
556
} tooLong;
557
558
void
559
SSL_AtomicIncrementLong(long *x)
560
6.06k
{
561
6.06k
    if ((sizeof *x) == sizeof(PRInt32)) {
562
0
        PR_ATOMIC_INCREMENT((PRInt32 *)x);
563
6.06k
    } else {
564
6.06k
        tooLong *tl = (tooLong *)x;
565
6.06k
        if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
566
0
            PR_ATOMIC_INCREMENT(&tl->high);
567
6.06k
    }
568
6.06k
}
569
570
PRBool
571
ssl3_CipherSuiteAllowedForVersionRange(ssl3CipherSuite cipherSuite,
572
                                       const SSLVersionRange *vrange)
573
109k
{
574
109k
    switch (cipherSuite) {
575
1.75k
        case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
576
2.98k
        case TLS_RSA_WITH_AES_256_CBC_SHA256:
577
5.03k
        case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
578
7.02k
        case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
579
9.13k
        case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
580
11.1k
        case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
581
12.9k
        case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
582
14.2k
        case TLS_RSA_WITH_AES_128_CBC_SHA256:
583
15.6k
        case TLS_RSA_WITH_AES_128_GCM_SHA256:
584
16.9k
        case TLS_RSA_WITH_AES_256_GCM_SHA384:
585
16.9k
        case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
586
16.9k
        case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
587
17.2k
        case TLS_RSA_WITH_NULL_SHA256:
588
17.2k
        case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
589
17.2k
        case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
590
21.4k
        case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
591
25.4k
        case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
592
31.2k
        case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
593
35.4k
        case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
594
37.6k
        case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
595
39.5k
        case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
596
43.6k
        case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
597
47.9k
        case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
598
50.0k
        case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
599
50.0k
            return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2 &&
600
50.0k
                   vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
601
602
        /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and
603
         * point formats.*/
604
376
        case TLS_ECDH_ECDSA_WITH_NULL_SHA:
605
376
        case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
606
1.77k
        case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
607
3.17k
        case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
608
4.57k
        case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
609
5.00k
        case TLS_ECDHE_ECDSA_WITH_NULL_SHA:
610
5.00k
        case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
611
6.89k
        case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
612
10.8k
        case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
613
14.9k
        case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
614
14.9k
        case TLS_ECDH_RSA_WITH_NULL_SHA:
615
14.9k
        case TLS_ECDH_RSA_WITH_RC4_128_SHA:
616
14.9k
        case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
617
14.9k
        case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
618
14.9k
        case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
619
15.3k
        case TLS_ECDHE_RSA_WITH_NULL_SHA:
620
15.3k
        case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
621
17.3k
        case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
622
21.3k
        case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
623
23.4k
        case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
624
23.4k
            return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0 &&
625
23.4k
                   vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
626
627
6.08k
        case TLS_AES_128_GCM_SHA256:
628
12.1k
        case TLS_AES_256_GCM_SHA384:
629
18.2k
        case TLS_CHACHA20_POLY1305_SHA256:
630
18.2k
            return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_3;
631
632
18.2k
        default:
633
18.2k
            return vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
634
109k
    }
635
109k
}
636
637
/* return pointer to ssl3CipherSuiteDef for suite, or NULL */
638
/* XXX This does a linear search.  A binary search would be better. */
639
const ssl3CipherSuiteDef *
640
ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
641
513k
{
642
513k
    int cipher_suite_def_len =
643
513k
        sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
644
513k
    int i;
645
646
19.9M
    for (i = 0; i < cipher_suite_def_len; i++) {
647
19.9M
        if (cipher_suite_defs[i].cipher_suite == suite)
648
513k
            return &cipher_suite_defs[i];
649
19.9M
    }
650
0
    PORT_Assert(PR_FALSE); /* We should never get here. */
651
0
    PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
652
0
    return NULL;
653
513k
}
654
655
/* Find the cipher configuration struct associate with suite */
656
/* XXX This does a linear search.  A binary search would be better. */
657
static ssl3CipherSuiteCfg *
658
ssl_LookupCipherSuiteCfgMutable(ssl3CipherSuite suite,
659
                                ssl3CipherSuiteCfg *suites)
660
43.7k
{
661
43.7k
    int i;
662
663
1.84M
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
664
1.84M
        if (suites[i].cipher_suite == suite)
665
43.7k
            return &suites[i];
666
1.84M
    }
667
    /* return NULL and let the caller handle it.  */
668
0
    PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
669
0
    return NULL;
670
43.7k
}
671
672
const ssl3CipherSuiteCfg *
673
ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, const ssl3CipherSuiteCfg *suites)
674
1.06k
{
675
1.06k
    return ssl_LookupCipherSuiteCfgMutable(suite,
676
1.06k
                                           CONST_CAST(ssl3CipherSuiteCfg, suites));
677
1.06k
}
678
679
static PRBool
680
ssl_NamedGroupTypeEnabled(const sslSocket *ss, SSLKEAType keaType)
681
79.8k
{
682
79.8k
    unsigned int i;
683
245k
    for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
684
243k
        if (ss->namedGroupPreferences[i] &&
685
243k
            ss->namedGroupPreferences[i]->keaType == keaType) {
686
77.8k
            return PR_TRUE;
687
77.8k
        }
688
243k
    }
689
1.94k
    return PR_FALSE;
690
79.8k
}
691
692
static PRBool
693
ssl_KEAEnabled(const sslSocket *ss, SSLKEAType keaType)
694
111k
{
695
111k
    switch (keaType) {
696
13.7k
        case ssl_kea_rsa:
697
13.7k
            return PR_TRUE;
698
699
19.7k
        case ssl_kea_dh:
700
19.7k
        case ssl_kea_dh_psk: {
701
19.7k
            if (ss->sec.isServer && !ss->opt.enableServerDhe) {
702
0
                return PR_FALSE;
703
0
            }
704
705
19.7k
            if (ss->sec.isServer) {
706
                /* If the server requires named FFDHE groups, then the client
707
                 * must have included an FFDHE group. peerSupportsFfdheGroups
708
                 * is set to true in ssl_HandleSupportedGroupsXtn(). */
709
19.7k
                if (ss->opt.requireDHENamedGroups &&
710
19.7k
                    !ss->xtnData.peerSupportsFfdheGroups) {
711
0
                    return PR_FALSE;
712
0
                }
713
714
                /* We can use the weak DH group if all of these are true:
715
                 * 1. We don't require named groups.
716
                 * 2. The peer doesn't support named groups.
717
                 * 3. This isn't TLS 1.3.
718
                 * 4. The weak group is enabled. */
719
19.7k
                if (!ss->opt.requireDHENamedGroups &&
720
19.7k
                    !ss->xtnData.peerSupportsFfdheGroups &&
721
19.7k
                    ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
722
19.7k
                    ss->ssl3.dheWeakGroupEnabled) {
723
0
                    return PR_TRUE;
724
0
                }
725
19.7k
            } else {
726
0
                if (ss->vrange.min < SSL_LIBRARY_VERSION_TLS_1_3 &&
727
0
                    !ss->opt.requireDHENamedGroups) {
728
                    /* The client enables DHE cipher suites even if no DHE groups
729
                     * are enabled. Only if this isn't TLS 1.3 and named groups
730
                     * are not required. */
731
0
                    return PR_TRUE;
732
0
                }
733
0
            }
734
19.7k
            return ssl_NamedGroupTypeEnabled(ss, ssl_kea_dh);
735
19.7k
        }
736
737
60.1k
        case ssl_kea_ecdh:
738
60.1k
        case ssl_kea_ecdh_psk:
739
60.1k
            return ssl_NamedGroupTypeEnabled(ss, ssl_kea_ecdh);
740
741
0
        case ssl_kea_ecdh_hybrid:
742
0
        case ssl_kea_ecdh_hybrid_psk:
743
0
            if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
744
0
                return PR_FALSE;
745
0
            }
746
0
            return ssl_NamedGroupTypeEnabled(ss, ssl_kea_ecdh_hybrid);
747
748
18.2k
        case ssl_kea_tls13_any:
749
18.2k
            return PR_TRUE;
750
751
0
        case ssl_kea_fortezza:
752
0
        default:
753
0
            PORT_Assert(0);
754
111k
    }
755
0
    return PR_FALSE;
756
111k
}
757
758
static PRBool
759
ssl_HasCert(const sslSocket *ss, PRUint16 maxVersion, SSLAuthType authType)
760
480k
{
761
480k
    PRCList *cursor;
762
480k
    if (authType == ssl_auth_null || authType == ssl_auth_psk || authType == ssl_auth_tls13_any) {
763
18.2k
        return PR_TRUE;
764
18.2k
    }
765
462k
    for (cursor = PR_NEXT_LINK(&ss->serverCerts);
766
948k
         cursor != &ss->serverCerts;
767
839k
         cursor = PR_NEXT_LINK(cursor)) {
768
839k
        sslServerCert *cert = (sslServerCert *)cursor;
769
839k
        if (!cert->serverKeyPair ||
770
839k
            !cert->serverKeyPair->privKey ||
771
839k
            !cert->serverCertChain ||
772
839k
            !SSL_CERT_IS(cert, authType)) {
773
461k
            continue;
774
461k
        }
775
        /* When called from ssl3_config_match_init(), all the EC curves will be
776
         * enabled, so this will essentially do nothing (unless we implement
777
         * curve configuration).  However, once we have seen the
778
         * supported_groups extension and this is called from config_match(),
779
         * this will filter out certificates with an unsupported curve.
780
         *
781
         * If we might negotiate TLS 1.3, skip this test as group configuration
782
         * doesn't affect choices in TLS 1.3.
783
         */
784
377k
        if (maxVersion < SSL_LIBRARY_VERSION_TLS_1_3 &&
785
377k
            (authType == ssl_auth_ecdsa ||
786
377k
             authType == ssl_auth_ecdh_ecdsa ||
787
377k
             authType == ssl_auth_ecdh_rsa) &&
788
377k
            !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
789
24.4k
            continue;
790
24.4k
        }
791
353k
        return PR_TRUE;
792
377k
    }
793
109k
    if (authType == ssl_auth_rsa_sign) {
794
0
        return ssl_HasCert(ss, maxVersion, ssl_auth_rsa_pss);
795
0
    }
796
109k
    return PR_FALSE;
797
109k
}
798
799
/* return true if the scheme is allowed by policy, This prevents
800
 * failures later when our actual signatures are rejected by
801
 * policy by either ssl code, or lower level NSS code */
802
static PRBool
803
ssl_SchemePolicyOK(SSLSignatureScheme scheme, PRUint32 require)
804
224k
{
805
    /* Hash policy. */
806
224k
    PRUint32 policy;
807
224k
    SECOidTag hashOID = ssl3_HashTypeToOID(ssl_SignatureSchemeToHashType(scheme));
808
224k
    SECOidTag sigOID;
809
810
    /* policy bits needed to enable a SignatureScheme */
811
224k
    SECStatus rv = NSS_GetAlgorithmPolicy(hashOID, &policy);
812
224k
    if (rv == SECSuccess &&
813
224k
        (policy & require) != require) {
814
0
        return PR_FALSE;
815
0
    }
816
817
    /* ssl_SignatureSchemeToAuthType reports rsa for rsa_pss_rsae, but we
818
     * actually implement pss signatures when we sign, so just use RSA_PSS
819
     * for all RSA PSS Siganture schemes */
820
224k
    if (ssl_IsRsaPssSignatureScheme(scheme)) {
821
133k
        sigOID = SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
822
133k
    } else {
823
90.2k
        sigOID = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme));
824
90.2k
    }
825
    /* Signature Policy. */
826
224k
    rv = NSS_GetAlgorithmPolicy(sigOID, &policy);
827
224k
    if (rv == SECSuccess &&
828
224k
        (policy & require) != require) {
829
0
        return PR_FALSE;
830
0
    }
831
224k
    return PR_TRUE;
832
224k
}
833
834
/* Check that a signature scheme is accepted.
835
 * Both by policy and by having a token that supports it. */
836
static PRBool
837
ssl_SignatureSchemeAccepted(PRUint16 minVersion,
838
                            SSLSignatureScheme scheme,
839
                            PRBool forCert)
840
218k
{
841
    /* Disable RSA-PSS schemes if there are no tokens to verify them. */
842
218k
    if (ssl_IsRsaPssSignatureScheme(scheme)) {
843
132k
        if (!PK11_TokenExists(auth_alg_defs[ssl_auth_rsa_pss])) {
844
0
            return PR_FALSE;
845
0
        }
846
132k
    } else if (!forCert && ssl_IsRsaPkcs1SignatureScheme(scheme)) {
847
        /* Disable PKCS#1 signatures if we are limited to TLS 1.3.
848
         * We still need to advertise PKCS#1 signatures in CH and CR
849
         * for certificate signatures.
850
         */
851
0
        if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_3) {
852
0
            return PR_FALSE;
853
0
        }
854
86.0k
    } else if (ssl_IsDsaSignatureScheme(scheme)) {
855
        /* DSA: not in TLS 1.3, and check policy. */
856
14.0k
        if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_3) {
857
0
            return PR_FALSE;
858
0
        }
859
14.0k
    }
860
861
218k
    return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy);
862
218k
}
863
864
static SECStatus
865
ssl_CheckSignatureSchemes(sslSocket *ss)
866
6.08k
{
867
6.08k
    if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_2) {
868
0
        return SECSuccess;
869
0
    }
870
871
    /* If this is a server using TLS 1.3, we just need to have one signature
872
     * scheme for which we have a usable certificate.
873
     *
874
     * Note: Certificates for earlier TLS versions are checked along with the
875
     * cipher suite in ssl3_config_match_init. */
876
6.08k
    if (ss->sec.isServer && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
877
0
        PRBool foundCert = PR_FALSE;
878
0
        for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
879
0
            SSLAuthType authType =
880
0
                ssl_SignatureSchemeToAuthType(ss->ssl3.signatureSchemes[i]);
881
0
            if (ssl_HasCert(ss, ss->vrange.max, authType)) {
882
0
                foundCert = PR_TRUE;
883
0
                break;
884
0
            }
885
0
        }
886
0
        if (!foundCert) {
887
0
            PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
888
0
            return SECFailure;
889
0
        }
890
0
    }
891
892
    /* Ensure that there is a signature scheme that can be accepted.*/
893
6.08k
    for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
894
6.08k
        if (ssl_SignatureSchemeAccepted(ss->vrange.min,
895
6.08k
                                        ss->ssl3.signatureSchemes[i],
896
6.08k
                                        PR_FALSE /* forCert */)) {
897
6.08k
            return SECSuccess;
898
6.08k
        }
899
6.08k
    }
900
0
    PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
901
0
    return SECFailure;
902
6.08k
}
903
904
/* For a server, check that a signature scheme that can be used with the
905
 * provided authType is both enabled and usable. */
906
static PRBool
907
ssl_HasSignatureScheme(const sslSocket *ss, SSLAuthType authType)
908
261k
{
909
261k
    PORT_Assert(ss->sec.isServer);
910
261k
    PORT_Assert(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version);
911
261k
    PORT_Assert(authType != ssl_auth_null);
912
261k
    PORT_Assert(authType != ssl_auth_tls13_any);
913
261k
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2 ||
914
261k
        authType == ssl_auth_rsa_decrypt ||
915
261k
        authType == ssl_auth_ecdh_rsa ||
916
261k
        authType == ssl_auth_ecdh_ecdsa) {
917
101k
        return PR_TRUE;
918
101k
    }
919
646k
    for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
920
646k
        SSLSignatureScheme scheme = ss->ssl3.signatureSchemes[i];
921
646k
        SSLAuthType schemeAuthType = ssl_SignatureSchemeToAuthType(scheme);
922
646k
        PRBool acceptable = authType == schemeAuthType ||
923
646k
                            (schemeAuthType == ssl_auth_rsa_pss &&
924
486k
                             authType == ssl_auth_rsa_sign);
925
646k
        if (acceptable && ssl_SignatureSchemeAccepted(ss->version, scheme, PR_FALSE /* forCert */)) {
926
159k
            return PR_TRUE;
927
159k
        }
928
646k
    }
929
0
    return PR_FALSE;
930
159k
}
931
932
/* Initialize the suite->isPresent value for config_match
933
 * Returns count of enabled ciphers supported by extant tokens,
934
 * regardless of policy or user preference.
935
 * If this returns zero, the user cannot do SSL v3.
936
 */
937
unsigned int
938
ssl3_config_match_init(sslSocket *ss)
939
6.08k
{
940
6.08k
    ssl3CipherSuiteCfg *suite;
941
6.08k
    const ssl3CipherSuiteDef *cipher_def;
942
6.08k
    SSLCipherAlgorithm cipher_alg;
943
6.08k
    CK_MECHANISM_TYPE cipher_mech;
944
6.08k
    SSLAuthType authType;
945
6.08k
    SSLKEAType keaType;
946
6.08k
    unsigned int i;
947
6.08k
    unsigned int numPresent = 0;
948
6.08k
    unsigned int numEnabled = 0;
949
950
6.08k
    PORT_Assert(ss);
951
6.08k
    if (!ss) {
952
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
953
0
        return 0;
954
0
    }
955
6.08k
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
956
0
        return 0;
957
0
    }
958
6.08k
    if (ss->sec.isServer && ss->psk &&
959
6.08k
        PR_CLIST_IS_EMPTY(&ss->serverCerts) &&
960
6.08k
        (ss->opt.requestCertificate || ss->opt.requireCertificate)) {
961
        /* PSK and certificate auth cannot be combined. */
962
0
        PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
963
0
        return 0;
964
0
    }
965
6.08k
    if (ssl_CheckSignatureSchemes(ss) != SECSuccess) {
966
0
        return 0; /* Code already set. */
967
0
    }
968
969
6.08k
    ssl_FilterSupportedGroups(ss);
970
437k
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
971
431k
        suite = &ss->cipherSuites[i];
972
431k
        if (suite->enabled) {
973
389k
            ++numEnabled;
974
            /* We need the cipher defs to see if we have a token that can handle
975
             * this cipher.  It isn't part of the static definition.
976
             */
977
389k
            cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
978
389k
            if (!cipher_def) {
979
0
                suite->isPresent = PR_FALSE;
980
0
                continue;
981
0
            }
982
389k
            cipher_alg = ssl_GetBulkCipherDef(cipher_def)->calg;
983
389k
            cipher_mech = ssl3_Alg2Mech(cipher_alg);
984
985
            /* Mark the suites that are backed by real tokens, certs and keys */
986
389k
            suite->isPresent = PR_TRUE;
987
988
389k
            authType = kea_defs[cipher_def->key_exchange_alg].authKeyType;
989
389k
            if (authType != ssl_auth_null && authType != ssl_auth_tls13_any) {
990
371k
                if (ss->sec.isServer &&
991
371k
                    !(ssl_HasCert(ss, ss->vrange.max, authType) &&
992
371k
                      ssl_HasSignatureScheme(ss, authType))) {
993
109k
                    suite->isPresent = PR_FALSE;
994
261k
                } else if (!PK11_TokenExists(auth_alg_defs[authType])) {
995
0
                    suite->isPresent = PR_FALSE;
996
0
                }
997
371k
            }
998
999
389k
            keaType = kea_defs[cipher_def->key_exchange_alg].exchKeyType;
1000
389k
            if (keaType != ssl_kea_null &&
1001
389k
                keaType != ssl_kea_tls13_any &&
1002
389k
                !PK11_TokenExists(kea_alg_defs[keaType])) {
1003
0
                suite->isPresent = PR_FALSE;
1004
0
            }
1005
1006
389k
            if (cipher_alg != ssl_calg_null &&
1007
389k
                !PK11_TokenExists(cipher_mech)) {
1008
0
                suite->isPresent = PR_FALSE;
1009
0
            }
1010
1011
389k
            if (suite->isPresent) {
1012
279k
                ++numPresent;
1013
279k
            }
1014
389k
        }
1015
431k
    }
1016
6.08k
    PORT_AssertArg(numPresent > 0 || numEnabled == 0);
1017
6.08k
    if (numPresent == 0) {
1018
0
        PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
1019
0
    }
1020
6.08k
    return numPresent;
1021
6.08k
}
1022
1023
/* Return PR_TRUE if suite is usable.  This if the suite is permitted by policy,
1024
 * enabled, has a certificate (as needed), has a viable key agreement method, is
1025
 * usable with the negotiated TLS version, and is otherwise usable. */
1026
PRBool
1027
ssl3_config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy,
1028
                  const SSLVersionRange *vrange, const sslSocket *ss)
1029
148k
{
1030
148k
    const ssl3CipherSuiteDef *cipher_def;
1031
148k
    const ssl3KEADef *kea_def;
1032
1033
148k
    if (!suite) {
1034
0
        PORT_Assert(suite);
1035
0
        return PR_FALSE;
1036
0
    }
1037
1038
148k
    PORT_Assert(policy != SSL_NOT_ALLOWED);
1039
148k
    if (policy == SSL_NOT_ALLOWED)
1040
0
        return PR_FALSE;
1041
1042
148k
    if (!suite->enabled || !suite->isPresent)
1043
36.6k
        return PR_FALSE;
1044
1045
111k
    if ((suite->policy == SSL_NOT_ALLOWED) ||
1046
111k
        (suite->policy > policy))
1047
0
        return PR_FALSE;
1048
1049
111k
    PORT_Assert(ss != NULL);
1050
111k
    cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
1051
111k
    PORT_Assert(cipher_def != NULL);
1052
111k
    kea_def = &kea_defs[cipher_def->key_exchange_alg];
1053
111k
    PORT_Assert(kea_def != NULL);
1054
111k
    if (!ssl_KEAEnabled(ss, kea_def->exchKeyType)) {
1055
1.94k
        return PR_FALSE;
1056
1.94k
    }
1057
1058
109k
    if (ss->sec.isServer && !ssl_HasCert(ss, vrange->max, kea_def->authKeyType)) {
1059
0
        return PR_FALSE;
1060
0
    }
1061
1062
    /* If a PSK is selected, disable suites that use a different hash than
1063
     * the PSK. We advertise non-PSK-compatible suites in the CH, as we could
1064
     * fallback to certificate auth. The client handler will check hash
1065
     * compatibility before committing to use the PSK. */
1066
109k
    if (ss->xtnData.selectedPsk) {
1067
0
        if (ss->xtnData.selectedPsk->hash != cipher_def->prf_hash) {
1068
0
            return PR_FALSE;
1069
0
        }
1070
0
    }
1071
1072
109k
    return ssl3_CipherSuiteAllowedForVersionRange(suite->cipher_suite, vrange);
1073
109k
}
1074
1075
/* For TLS 1.3, when resuming, check for a ciphersuite that is both compatible
1076
 * with the identified ciphersuite and enabled. */
1077
static PRBool
1078
tls13_ResumptionCompatible(sslSocket *ss, ssl3CipherSuite suite)
1079
0
{
1080
0
    SSLVersionRange vrange = { SSL_LIBRARY_VERSION_TLS_1_3,
1081
0
                               SSL_LIBRARY_VERSION_TLS_1_3 };
1082
0
    SSLHashType hash = tls13_GetHashForCipherSuite(suite);
1083
0
    for (unsigned int i = 0; i < PR_ARRAY_SIZE(cipher_suite_defs); i++) {
1084
0
        if (cipher_suite_defs[i].prf_hash == hash) {
1085
0
            const ssl3CipherSuiteCfg *suiteCfg =
1086
0
                ssl_LookupCipherSuiteCfg(cipher_suite_defs[i].cipher_suite,
1087
0
                                         ss->cipherSuites);
1088
0
            if (suite && ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) {
1089
0
                return PR_TRUE;
1090
0
            }
1091
0
        }
1092
0
    }
1093
0
    return PR_FALSE;
1094
0
}
1095
1096
/*
1097
 * Null compression, mac and encryption functions
1098
 */
1099
SECStatus
1100
Null_Cipher(void *ctx, unsigned char *output, unsigned int *outputLen, unsigned int maxOutputLen,
1101
            const unsigned char *input, unsigned int inputLen)
1102
52.5k
{
1103
52.5k
    if (inputLen > maxOutputLen) {
1104
0
        *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */
1105
0
        PORT_SetError(SEC_ERROR_OUTPUT_LEN);
1106
0
        return SECFailure;
1107
0
    }
1108
52.5k
    *outputLen = inputLen;
1109
52.5k
    if (inputLen > 0 && input != output) {
1110
26.0k
        PORT_Memcpy(output, input, inputLen);
1111
26.0k
    }
1112
52.5k
    return SECSuccess;
1113
52.5k
}
1114
1115
/*
1116
 * SSL3 Utility functions
1117
 */
1118
1119
static void
1120
ssl_SetSpecVersions(sslSocket *ss, ssl3CipherSpec *spec)
1121
19.4k
{
1122
19.4k
    spec->version = ss->version;
1123
19.4k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
1124
0
        tls13_SetSpecRecordVersion(ss, spec);
1125
19.4k
    } else if (IS_DTLS(ss)) {
1126
19.4k
        spec->recordVersion = dtls_TLSVersionToDTLSVersion(ss->version);
1127
19.4k
    } else {
1128
0
        spec->recordVersion = ss->version;
1129
0
    }
1130
19.4k
}
1131
1132
/* allowLargerPeerVersion controls whether the function will select the
1133
 * highest enabled SSL version or fail when peerVersion is greater than the
1134
 * highest enabled version.
1135
 *
1136
 * If allowLargerPeerVersion is true, peerVersion is the peer's highest
1137
 * enabled version rather than the peer's selected version.
1138
 */
1139
SECStatus
1140
ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
1141
                      PRBool allowLargerPeerVersion)
1142
7.34k
{
1143
7.34k
    SSL3ProtocolVersion negotiated;
1144
1145
    /* Prevent negotiating to a lower version in response to a TLS 1.3 HRR. */
1146
7.34k
    if (ss->ssl3.hs.helloRetry) {
1147
1
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
1148
1
        return SECFailure;
1149
1
    }
1150
1151
7.34k
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
1152
0
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
1153
0
        return SECFailure;
1154
0
    }
1155
1156
7.34k
    if (peerVersion < ss->vrange.min ||
1157
7.34k
        (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
1158
4
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
1159
4
        return SECFailure;
1160
4
    }
1161
1162
7.34k
    negotiated = PR_MIN(peerVersion, ss->vrange.max);
1163
7.34k
    PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, negotiated));
1164
7.34k
    if (ss->firstHsDone && ss->version != negotiated) {
1165
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
1166
0
        return SECFailure;
1167
0
    }
1168
1169
7.34k
    ss->version = negotiated;
1170
7.34k
    return SECSuccess;
1171
7.34k
}
1172
1173
/* Used by the client when the server produces a version number.
1174
 * This reads, validates, and normalizes the value. */
1175
SECStatus
1176
ssl_ClientReadVersion(sslSocket *ss, PRUint8 **b, unsigned int *len,
1177
                      SSL3ProtocolVersion *version)
1178
0
{
1179
0
    SSL3ProtocolVersion v;
1180
0
    PRUint32 temp;
1181
0
    SECStatus rv;
1182
1183
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, b, len);
1184
0
    if (rv != SECSuccess) {
1185
0
        return SECFailure; /* alert has been sent */
1186
0
    }
1187
0
    v = (SSL3ProtocolVersion)temp;
1188
1189
0
    if (IS_DTLS(ss)) {
1190
0
        v = dtls_DTLSVersionToTLSVersion(v);
1191
        /* Check for failure. */
1192
0
        if (!v || v > SSL_LIBRARY_VERSION_MAX_SUPPORTED) {
1193
0
            SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
1194
0
            return SECFailure;
1195
0
        }
1196
0
    }
1197
1198
    /* You can't negotiate TLS 1.3 this way. */
1199
0
    if (v >= SSL_LIBRARY_VERSION_TLS_1_3) {
1200
0
        SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
1201
0
        return SECFailure;
1202
0
    }
1203
0
    *version = v;
1204
0
    return SECSuccess;
1205
0
}
1206
1207
SECStatus
1208
ssl3_GetNewRandom(SSL3Random random)
1209
6.04k
{
1210
6.04k
    SECStatus rv;
1211
1212
6.04k
    rv = PK11_GenerateRandom(random, SSL3_RANDOM_LENGTH);
1213
6.04k
    if (rv != SECSuccess) {
1214
0
        ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
1215
0
    }
1216
6.04k
    return rv;
1217
6.04k
}
1218
1219
SECStatus
1220
ssl3_SignHashesWithPrivKey(SSL3Hashes *hash, SECKEYPrivateKey *key,
1221
                           SSLSignatureScheme scheme, PRBool isTls, SECItem *buf)
1222
5.03k
{
1223
5.03k
    SECStatus rv = SECFailure;
1224
5.03k
    PRBool doDerEncode = PR_FALSE;
1225
5.03k
    PRBool useRsaPss = ssl_IsRsaPssSignatureScheme(scheme);
1226
5.03k
    SECItem hashItem;
1227
1228
5.03k
    buf->data = NULL;
1229
1230
5.03k
    switch (SECKEY_GetPrivateKeyType(key)) {
1231
4.74k
        case rsaKey:
1232
4.74k
            hashItem.data = hash->u.raw;
1233
4.74k
            hashItem.len = hash->len;
1234
4.74k
            break;
1235
0
        case dsaKey:
1236
0
            doDerEncode = isTls;
1237
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1238
             * In that case, we use just the SHA1 part. */
1239
0
            if (hash->hashAlg == ssl_hash_none) {
1240
0
                hashItem.data = hash->u.s.sha;
1241
0
                hashItem.len = sizeof(hash->u.s.sha);
1242
0
            } else {
1243
0
                hashItem.data = hash->u.raw;
1244
0
                hashItem.len = hash->len;
1245
0
            }
1246
0
            break;
1247
283
        case ecKey:
1248
283
            doDerEncode = PR_TRUE;
1249
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1250
             * In that case, we use just the SHA1 part. */
1251
283
            if (hash->hashAlg == ssl_hash_none) {
1252
0
                hashItem.data = hash->u.s.sha;
1253
0
                hashItem.len = sizeof(hash->u.s.sha);
1254
283
            } else {
1255
283
                hashItem.data = hash->u.raw;
1256
283
                hashItem.len = hash->len;
1257
283
            }
1258
283
            break;
1259
0
        default:
1260
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
1261
0
            goto done;
1262
5.03k
    }
1263
5.03k
    PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
1264
1265
5.03k
    if (useRsaPss || hash->hashAlg == ssl_hash_none) {
1266
174
        CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1267
174
        int signatureLen = PK11_SignatureLen(key);
1268
1269
174
        SECItem *params = NULL;
1270
174
        CK_RSA_PKCS_PSS_PARAMS pssParams;
1271
174
        SECItem pssParamsItem = { siBuffer,
1272
174
                                  (unsigned char *)&pssParams,
1273
174
                                  sizeof(pssParams) };
1274
1275
174
        if (signatureLen <= 0) {
1276
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
1277
0
            goto done;
1278
0
        }
1279
1280
174
        buf->len = (unsigned)signatureLen;
1281
174
        buf->data = (unsigned char *)PORT_Alloc(signatureLen);
1282
174
        if (!buf->data)
1283
0
            goto done; /* error code was set. */
1284
1285
174
        if (useRsaPss) {
1286
174
            pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1287
174
            pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1288
174
            pssParams.sLen = hashItem.len;
1289
174
            params = &pssParamsItem;
1290
174
            mech = CKM_RSA_PKCS_PSS;
1291
174
        }
1292
1293
174
        rv = PK11_SignWithMechanism(key, mech, params, buf, &hashItem);
1294
4.85k
    } else {
1295
4.85k
        SECOidTag hashOID = ssl3_HashTypeToOID(hash->hashAlg);
1296
4.85k
        rv = SGN_Digest(key, hashOID, buf, &hashItem);
1297
4.85k
    }
1298
5.03k
    if (rv != SECSuccess) {
1299
0
        ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
1300
5.03k
    } else if (doDerEncode) {
1301
283
        SECItem derSig = { siBuffer, NULL, 0 };
1302
1303
        /* This also works for an ECDSA signature */
1304
283
        rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
1305
283
        if (rv == SECSuccess) {
1306
283
            PORT_Free(buf->data); /* discard unencoded signature. */
1307
283
            *buf = derSig;        /* give caller encoded signature. */
1308
283
        } else if (derSig.data) {
1309
0
            PORT_Free(derSig.data);
1310
0
        }
1311
283
    }
1312
1313
5.03k
    PRINT_BUF(60, (NULL, "signed hashes", (unsigned char *)buf->data, buf->len));
1314
5.03k
done:
1315
5.03k
    if (rv != SECSuccess && buf->data) {
1316
0
        PORT_Free(buf->data);
1317
0
        buf->data = NULL;
1318
0
    }
1319
5.03k
    return rv;
1320
5.03k
}
1321
1322
/* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
1323
SECStatus
1324
ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash, SECKEYPrivateKey *key,
1325
                SECItem *buf)
1326
5.03k
{
1327
5.03k
    SECStatus rv = SECFailure;
1328
5.03k
    PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
1329
5.03k
    SSLSignatureScheme scheme = ss->ssl3.hs.signatureScheme;
1330
1331
5.03k
    rv = ssl3_SignHashesWithPrivKey(hash, key, scheme, isTLS, buf);
1332
5.03k
    if (rv != SECSuccess) {
1333
0
        return SECFailure;
1334
0
    }
1335
1336
5.03k
    if (ss->sec.isServer) {
1337
5.03k
        ss->sec.signatureScheme = scheme;
1338
5.03k
        ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
1339
5.03k
    }
1340
1341
5.03k
    return SECSuccess;
1342
5.03k
}
1343
1344
/* Called from ssl3_VerifySignedHashes and tls13_HandleCertificateVerify. */
1345
SECStatus
1346
ssl_VerifySignedHashesWithPubKey(sslSocket *ss, SECKEYPublicKey *key,
1347
                                 SSLSignatureScheme scheme,
1348
                                 SSL3Hashes *hash, SECItem *buf)
1349
0
{
1350
0
    SECItem *signature = NULL;
1351
0
    SECStatus rv = SECFailure;
1352
0
    SECItem hashItem;
1353
0
    SECOidTag encAlg;
1354
0
    SECOidTag hashAlg;
1355
0
    void *pwArg = ss->pkcs11PinArg;
1356
0
    PRBool isRsaPssScheme = ssl_IsRsaPssSignatureScheme(scheme);
1357
1358
0
    PRINT_BUF(60, (NULL, "check signed hashes", buf->data, buf->len));
1359
1360
0
    hashAlg = ssl3_HashTypeToOID(hash->hashAlg);
1361
0
    switch (SECKEY_GetPublicKeyType(key)) {
1362
0
        case rsaKey:
1363
0
            encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
1364
0
            hashItem.data = hash->u.raw;
1365
0
            hashItem.len = hash->len;
1366
0
            if (scheme == ssl_sig_none) {
1367
0
                scheme = ssl_sig_rsa_pkcs1_sha1md5;
1368
0
            }
1369
0
            break;
1370
0
        case dsaKey:
1371
0
            encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
1372
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1373
             * In that case, we use just the SHA1 part. */
1374
0
            if (hash->hashAlg == ssl_hash_none) {
1375
0
                hashItem.data = hash->u.s.sha;
1376
0
                hashItem.len = sizeof(hash->u.s.sha);
1377
0
            } else {
1378
0
                hashItem.data = hash->u.raw;
1379
0
                hashItem.len = hash->len;
1380
0
            }
1381
            /* Allow DER encoded DSA signatures in SSL 3.0 */
1382
0
            if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0 ||
1383
0
                buf->len != SECKEY_SignatureLen(key)) {
1384
0
                signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key));
1385
0
                if (!signature) {
1386
0
                    PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1387
0
                    goto loser;
1388
0
                }
1389
0
                buf = signature;
1390
0
            }
1391
0
            if (scheme == ssl_sig_none) {
1392
0
                scheme = ssl_sig_dsa_sha1;
1393
0
            }
1394
0
            break;
1395
1396
0
        case ecKey:
1397
0
            encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
1398
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1399
             * In that case, we use just the SHA1 part.
1400
             * ECDSA signatures always encode the integers r and s using ASN.1
1401
             * (unlike DSA where ASN.1 encoding is used with TLS but not with
1402
             * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
1403
             */
1404
0
            if (hash->hashAlg == ssl_hash_none) {
1405
0
                hashAlg = SEC_OID_SHA1;
1406
0
                hashItem.data = hash->u.s.sha;
1407
0
                hashItem.len = sizeof(hash->u.s.sha);
1408
0
            } else {
1409
0
                hashItem.data = hash->u.raw;
1410
0
                hashItem.len = hash->len;
1411
0
            }
1412
0
            if (scheme == ssl_sig_none) {
1413
0
                scheme = ssl_sig_ecdsa_sha1;
1414
0
            }
1415
0
            break;
1416
1417
0
        default:
1418
0
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
1419
0
            goto loser;
1420
0
    }
1421
1422
0
    PRINT_BUF(60, (NULL, "hash(es) to be verified",
1423
0
                   hashItem.data, hashItem.len));
1424
1425
0
    if (isRsaPssScheme ||
1426
0
        hashAlg == SEC_OID_UNKNOWN ||
1427
0
        SECKEY_GetPublicKeyType(key) == dsaKey) {
1428
        /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1429
         * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1430
         * above always removes the DER encoding of DSA signatures when
1431
         * present. Thus DSA signatures are always verified with PK11_Verify.
1432
         */
1433
0
        CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1434
1435
0
        SECItem *params = NULL;
1436
0
        CK_RSA_PKCS_PSS_PARAMS pssParams;
1437
0
        SECItem pssParamsItem = { siBuffer,
1438
0
                                  (unsigned char *)&pssParams,
1439
0
                                  sizeof(pssParams) };
1440
1441
0
        if (isRsaPssScheme) {
1442
0
            pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1443
0
            pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1444
0
            pssParams.sLen = hashItem.len;
1445
0
            params = &pssParamsItem;
1446
0
            mech = CKM_RSA_PKCS_PSS;
1447
0
        }
1448
1449
0
        rv = PK11_VerifyWithMechanism(key, mech, params, buf, &hashItem, pwArg);
1450
0
    } else {
1451
0
        rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
1452
0
                                    pwArg);
1453
0
    }
1454
0
    if (signature) {
1455
0
        SECITEM_FreeItem(signature, PR_TRUE);
1456
0
    }
1457
0
    if (rv != SECSuccess) {
1458
0
        ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1459
0
    }
1460
0
    if (!ss->sec.isServer) {
1461
0
        ss->sec.signatureScheme = scheme;
1462
0
        ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
1463
0
    }
1464
1465
0
loser:
1466
#ifdef UNSAFE_FUZZER_MODE
1467
    rv = SECSuccess;
1468
    PORT_SetError(0);
1469
#endif
1470
0
    return rv;
1471
0
}
1472
1473
/* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
1474
SECStatus
1475
ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme, SSL3Hashes *hash,
1476
                        SECItem *buf)
1477
0
{
1478
0
    SECKEYPublicKey *pubKey =
1479
0
        SECKEY_ExtractPublicKey(&ss->sec.peerCert->subjectPublicKeyInfo);
1480
0
    if (pubKey == NULL) {
1481
0
        ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
1482
0
        return SECFailure;
1483
0
    }
1484
0
    SECStatus rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, scheme,
1485
0
                                                    hash, buf);
1486
0
    SECKEY_DestroyPublicKey(pubKey);
1487
0
    return rv;
1488
0
}
1489
1490
/* Caller must set hiLevel error code. */
1491
/* Called from ssl3_ComputeDHKeyHash
1492
 * which are called from ssl3_HandleServerKeyExchange.
1493
 *
1494
 * hashAlg: ssl_hash_none indicates the pre-1.2, MD5/SHA1 combination hash.
1495
 */
1496
SECStatus
1497
ssl3_ComputeCommonKeyHash(SSLHashType hashAlg,
1498
                          PRUint8 *hashBuf, unsigned int bufLen,
1499
                          SSL3Hashes *hashes)
1500
5.03k
{
1501
5.03k
    SECStatus rv;
1502
5.03k
    SECOidTag hashOID;
1503
5.03k
    PRUint32 policy;
1504
1505
5.03k
    if (hashAlg == ssl_hash_none) {
1506
0
        if ((NSS_GetAlgorithmPolicy(SEC_OID_SHA1, &policy) == SECSuccess) &&
1507
0
            !(policy & NSS_USE_ALG_IN_SSL_KX)) {
1508
0
            ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1509
0
            return SECFailure;
1510
0
        }
1511
0
        rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen);
1512
0
        if (rv != SECSuccess) {
1513
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
1514
0
            return rv;
1515
0
        }
1516
0
        rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen);
1517
0
        if (rv != SECSuccess) {
1518
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
1519
0
            return rv;
1520
0
        }
1521
0
        hashes->len = MD5_LENGTH + SHA1_LENGTH;
1522
5.03k
    } else {
1523
5.03k
        hashOID = ssl3_HashTypeToOID(hashAlg);
1524
5.03k
        if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) &&
1525
5.03k
            !(policy & NSS_USE_ALG_IN_SSL_KX)) {
1526
0
            ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1527
0
            return SECFailure;
1528
0
        }
1529
5.03k
        hashes->len = HASH_ResultLenByOidTag(hashOID);
1530
5.03k
        if (hashes->len == 0 || hashes->len > sizeof(hashes->u.raw)) {
1531
0
            ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1532
0
            return SECFailure;
1533
0
        }
1534
5.03k
        rv = PK11_HashBuf(hashOID, hashes->u.raw, hashBuf, bufLen);
1535
5.03k
        if (rv != SECSuccess) {
1536
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
1537
0
            return rv;
1538
0
        }
1539
5.03k
    }
1540
5.03k
    hashes->hashAlg = hashAlg;
1541
5.03k
    return SECSuccess;
1542
5.03k
}
1543
1544
/* Caller must set hiLevel error code. */
1545
/* Called from ssl3_HandleServerKeyExchange. */
1546
static SECStatus
1547
ssl3_ComputeDHKeyHash(sslSocket *ss, SSLHashType hashAlg, SSL3Hashes *hashes,
1548
                      SECItem dh_p, SECItem dh_g, SECItem dh_Ys, PRBool padY)
1549
1.07k
{
1550
1.07k
    sslBuffer buf = SSL_BUFFER_EMPTY;
1551
1.07k
    SECStatus rv;
1552
1.07k
    unsigned int yLen;
1553
1.07k
    unsigned int i;
1554
1555
1.07k
    PORT_Assert(dh_p.data);
1556
1.07k
    PORT_Assert(dh_g.data);
1557
1.07k
    PORT_Assert(dh_Ys.data);
1558
1559
1.07k
    rv = sslBuffer_Append(&buf, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
1560
1.07k
    if (rv != SECSuccess) {
1561
0
        goto loser;
1562
0
    }
1563
1.07k
    rv = sslBuffer_Append(&buf, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
1564
1.07k
    if (rv != SECSuccess) {
1565
0
        goto loser;
1566
0
    }
1567
    /* p */
1568
1.07k
    rv = sslBuffer_AppendVariable(&buf, dh_p.data, dh_p.len, 2);
1569
1.07k
    if (rv != SECSuccess) {
1570
0
        goto loser;
1571
0
    }
1572
    /* g */
1573
1.07k
    rv = sslBuffer_AppendVariable(&buf, dh_g.data, dh_g.len, 2);
1574
1.07k
    if (rv != SECSuccess) {
1575
0
        goto loser;
1576
0
    }
1577
    /* y - complicated by padding */
1578
1.07k
    yLen = padY ? dh_p.len : dh_Ys.len;
1579
1.07k
    rv = sslBuffer_AppendNumber(&buf, yLen, 2);
1580
1.07k
    if (rv != SECSuccess) {
1581
0
        goto loser;
1582
0
    }
1583
    /* If we're padding Y, dh_Ys can't be longer than dh_p. */
1584
1.07k
    PORT_Assert(!padY || dh_p.len >= dh_Ys.len);
1585
1.07k
    for (i = dh_Ys.len; i < yLen; ++i) {
1586
0
        rv = sslBuffer_AppendNumber(&buf, 0, 1);
1587
0
        if (rv != SECSuccess) {
1588
0
            goto loser;
1589
0
        }
1590
0
    }
1591
1.07k
    rv = sslBuffer_Append(&buf, dh_Ys.data, dh_Ys.len);
1592
1.07k
    if (rv != SECSuccess) {
1593
0
        goto loser;
1594
0
    }
1595
1596
1.07k
    rv = ssl3_ComputeCommonKeyHash(hashAlg, SSL_BUFFER_BASE(&buf),
1597
1.07k
                                   SSL_BUFFER_LEN(&buf), hashes);
1598
1.07k
    if (rv != SECSuccess) {
1599
0
        goto loser;
1600
0
    }
1601
1602
1.07k
    PRINT_BUF(95, (NULL, "DHkey hash: ", SSL_BUFFER_BASE(&buf),
1603
1.07k
                   SSL_BUFFER_LEN(&buf)));
1604
1.07k
    if (hashAlg == ssl_hash_none) {
1605
0
        PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",
1606
0
                       hashes->u.s.md5, MD5_LENGTH));
1607
0
        PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",
1608
0
                       hashes->u.s.sha, SHA1_LENGTH));
1609
1.07k
    } else {
1610
1.07k
        PRINT_BUF(95, (NULL, "DHkey hash: result",
1611
1.07k
                       hashes->u.raw, hashes->len));
1612
1.07k
    }
1613
1614
1.07k
    sslBuffer_Clear(&buf);
1615
1.07k
    return SECSuccess;
1616
1617
0
loser:
1618
0
    sslBuffer_Clear(&buf);
1619
0
    return SECFailure;
1620
1.07k
}
1621
1622
static SECStatus
1623
ssl3_SetupPendingCipherSpec(sslSocket *ss, SSLSecretDirection direction,
1624
                            const ssl3CipherSuiteDef *suiteDef,
1625
                            ssl3CipherSpec **specp)
1626
12.0k
{
1627
12.0k
    ssl3CipherSpec *spec;
1628
12.0k
    const ssl3CipherSpec *prev;
1629
1630
12.0k
    prev = (direction == ssl_secret_write) ? ss->ssl3.cwSpec : ss->ssl3.crSpec;
1631
12.0k
    if (prev->epoch == PR_UINT16_MAX) {
1632
0
        PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
1633
0
        return SECFailure;
1634
0
    }
1635
1636
12.0k
    spec = ssl_CreateCipherSpec(ss, direction);
1637
12.0k
    if (!spec) {
1638
0
        return SECFailure;
1639
0
    }
1640
1641
12.0k
    spec->cipherDef = ssl_GetBulkCipherDef(suiteDef);
1642
12.0k
    spec->macDef = ssl_GetMacDef(ss, suiteDef);
1643
1644
12.0k
    spec->epoch = prev->epoch + 1;
1645
12.0k
    spec->nextSeqNum = 0;
1646
12.0k
    if (IS_DTLS(ss) && direction == ssl_secret_read) {
1647
6.04k
        dtls_InitRecvdRecords(&spec->recvdRecords);
1648
6.04k
    }
1649
12.0k
    ssl_SetSpecVersions(ss, spec);
1650
1651
12.0k
    ssl_SaveCipherSpec(ss, spec);
1652
12.0k
    *specp = spec;
1653
12.0k
    return SECSuccess;
1654
12.0k
}
1655
1656
/* Fill in the pending cipher spec with info from the selected ciphersuite.
1657
** This is as much initialization as we can do without having key material.
1658
** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1659
** Caller must hold the ssl3 handshake lock.
1660
** Acquires & releases SpecWriteLock.
1661
*/
1662
SECStatus
1663
ssl3_SetupBothPendingCipherSpecs(sslSocket *ss)
1664
6.04k
{
1665
6.04k
    ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
1666
6.04k
    SSL3KeyExchangeAlgorithm kea;
1667
6.04k
    const ssl3CipherSuiteDef *suiteDef;
1668
6.04k
    SECStatus rv;
1669
1670
6.04k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1671
6.04k
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
1672
1673
6.04k
    ssl_GetSpecWriteLock(ss); /*******************************/
1674
1675
    /* This hack provides maximal interoperability with SSL 3 servers. */
1676
6.04k
    if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
1677
        /* SSL records are not being MACed. */
1678
6.04k
        ss->ssl3.cwSpec->version = ss->version;
1679
6.04k
    }
1680
1681
6.04k
    SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1682
6.04k
                SSL_GETPID(), ss->fd, suite));
1683
1684
6.04k
    suiteDef = ssl_LookupCipherSuiteDef(suite);
1685
6.04k
    if (suiteDef == NULL) {
1686
0
        goto loser;
1687
0
    }
1688
1689
6.04k
    if (IS_DTLS(ss)) {
1690
        /* Double-check that we did not pick an RC4 suite */
1691
6.04k
        PORT_Assert(suiteDef->bulk_cipher_alg != cipher_rc4);
1692
6.04k
    }
1693
1694
6.04k
    ss->ssl3.hs.suite_def = suiteDef;
1695
1696
6.04k
    kea = suiteDef->key_exchange_alg;
1697
6.04k
    ss->ssl3.hs.kea_def = &kea_defs[kea];
1698
6.04k
    PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
1699
1700
6.04k
    rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_read, suiteDef,
1701
6.04k
                                     &ss->ssl3.prSpec);
1702
6.04k
    if (rv != SECSuccess) {
1703
0
        goto loser;
1704
0
    }
1705
6.04k
    rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_write, suiteDef,
1706
6.04k
                                     &ss->ssl3.pwSpec);
1707
6.04k
    if (rv != SECSuccess) {
1708
0
        goto loser;
1709
0
    }
1710
1711
6.04k
    if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) {
1712
207
        ss->ssl3.prSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,
1713
207
                                                  ss->opt.recordSizeLimit);
1714
207
        ss->ssl3.pwSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,
1715
207
                                                  ss->xtnData.recordSizeLimit);
1716
207
    }
1717
1718
6.04k
    ssl_ReleaseSpecWriteLock(ss); /*******************************/
1719
6.04k
    return SECSuccess;
1720
1721
0
loser:
1722
0
    ssl_ReleaseSpecWriteLock(ss);
1723
0
    return SECFailure;
1724
6.04k
}
1725
1726
/* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data which
1727
 * is included in the MAC or AEAD additional data) to |buf|. See
1728
 * https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the definition of the
1729
 * AEAD additional data.
1730
 *
1731
 * TLS pseudo-header includes the record's version field, SSL's doesn't. Which
1732
 * pseudo-header definition to use should be decided based on the version of
1733
 * the protocol that was negotiated when the cipher spec became current, NOT
1734
 * based on the version value in the record itself, and the decision is passed
1735
 * to this function as the |includesVersion| argument. But, the |version|
1736
 * argument should be the record's version value.
1737
 */
1738
static SECStatus
1739
ssl3_BuildRecordPseudoHeader(DTLSEpoch epoch,
1740
                             sslSequenceNumber seqNum,
1741
                             SSLContentType ct,
1742
                             PRBool includesVersion,
1743
                             SSL3ProtocolVersion version,
1744
                             PRBool isDTLS,
1745
                             int length,
1746
                             sslBuffer *buf, SSL3ProtocolVersion v)
1747
52.8k
{
1748
52.8k
    SECStatus rv;
1749
52.8k
    if (isDTLS && v < SSL_LIBRARY_VERSION_TLS_1_3) {
1750
52.8k
        rv = sslBuffer_AppendNumber(buf, epoch, 2);
1751
52.8k
        if (rv != SECSuccess) {
1752
0
            return SECFailure;
1753
0
        }
1754
52.8k
        rv = sslBuffer_AppendNumber(buf, seqNum, 6);
1755
52.8k
    } else {
1756
0
        rv = sslBuffer_AppendNumber(buf, seqNum, 8);
1757
0
    }
1758
52.8k
    if (rv != SECSuccess) {
1759
0
        return SECFailure;
1760
0
    }
1761
52.8k
    rv = sslBuffer_AppendNumber(buf, ct, 1);
1762
52.8k
    if (rv != SECSuccess) {
1763
0
        return SECFailure;
1764
0
    }
1765
1766
    /* SSL3 MAC doesn't include the record's version field. */
1767
52.8k
    if (includesVersion) {
1768
        /* TLS MAC and AEAD additional data include version. */
1769
52.8k
        rv = sslBuffer_AppendNumber(buf, version, 2);
1770
52.8k
        if (rv != SECSuccess) {
1771
0
            return SECFailure;
1772
0
        }
1773
52.8k
    }
1774
52.8k
    rv = sslBuffer_AppendNumber(buf, length, 2);
1775
52.8k
    if (rv != SECSuccess) {
1776
0
        return SECFailure;
1777
0
    }
1778
1779
52.8k
    return SECSuccess;
1780
52.8k
}
1781
1782
/* Initialize encryption and MAC contexts for pending spec.
1783
 * Master Secret already is derived.
1784
 * Caller holds Spec write lock.
1785
 */
1786
static SECStatus
1787
ssl3_InitPendingContexts(sslSocket *ss, ssl3CipherSpec *spec)
1788
30
{
1789
30
    CK_MECHANISM_TYPE encMechanism;
1790
30
    CK_ATTRIBUTE_TYPE encMode;
1791
30
    SECItem macParam;
1792
30
    CK_ULONG macLength;
1793
30
    SECItem iv;
1794
30
    SSLCipherAlgorithm calg;
1795
1796
30
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1797
30
    PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1798
1799
30
    calg = spec->cipherDef->calg;
1800
30
    PORT_Assert(alg2Mech[calg].calg == calg);
1801
1802
30
    if (spec->cipherDef->type != type_aead) {
1803
8
        macLength = spec->macDef->mac_size;
1804
1805
        /*
1806
        ** Now setup the MAC contexts,
1807
        **   crypto contexts are setup below.
1808
        */
1809
8
        macParam.data = (unsigned char *)&macLength;
1810
8
        macParam.len = sizeof(macLength);
1811
8
        macParam.type = siBuffer;
1812
1813
8
        spec->keyMaterial.macContext = PK11_CreateContextBySymKey(
1814
8
            spec->macDef->mmech, CKA_SIGN, spec->keyMaterial.macKey, &macParam);
1815
8
        if (!spec->keyMaterial.macContext) {
1816
0
            ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1817
0
            return SECFailure;
1818
0
        }
1819
8
    }
1820
1821
    /*
1822
    ** Now setup the crypto contexts.
1823
    */
1824
30
    if (calg == ssl_calg_null) {
1825
0
        spec->cipher = Null_Cipher;
1826
0
        return SECSuccess;
1827
0
    }
1828
1829
30
    encMechanism = ssl3_Alg2Mech(calg);
1830
30
    encMode = (spec->direction == ssl_secret_write) ? CKA_ENCRYPT : CKA_DECRYPT;
1831
30
    if (spec->cipherDef->type == type_aead) {
1832
22
        encMode |= CKA_NSS_MESSAGE;
1833
22
        iv.data = NULL;
1834
22
        iv.len = 0;
1835
22
    } else {
1836
8
        spec->cipher = (SSLCipher)PK11_CipherOp;
1837
8
        iv.data = spec->keyMaterial.iv;
1838
8
        iv.len = spec->cipherDef->iv_size;
1839
8
    }
1840
1841
    /*
1842
     * build the context
1843
     */
1844
30
    spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode,
1845
30
                                                     spec->keyMaterial.key,
1846
30
                                                     &iv);
1847
30
    if (!spec->cipherContext) {
1848
0
        ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1849
0
        return SECFailure;
1850
0
    }
1851
1852
30
    return SECSuccess;
1853
30
}
1854
1855
/* Complete the initialization of all keys, ciphers, MACs and their contexts
1856
 * for the pending Cipher Spec.
1857
 * Called from: ssl3_SendClientKeyExchange  (for Full handshake)
1858
 *              ssl3_HandleRSAClientKeyExchange (for Full handshake)
1859
 *              ssl3_HandleServerHello      (for session restart)
1860
 *              ssl3_HandleClientHello      (for session restart)
1861
 * Sets error code, but caller probably should override to disambiguate.
1862
 *
1863
 * If |secret| is a master secret from a previous connection is reused, |derive|
1864
 * is PR_FALSE.  If the secret is a pre-master secret, then |derive| is PR_TRUE
1865
 * and the master secret is derived from |secret|.
1866
 */
1867
SECStatus
1868
ssl3_InitPendingCipherSpecs(sslSocket *ss, PK11SymKey *secret, PRBool derive)
1869
15
{
1870
15
    PK11SymKey *masterSecret;
1871
15
    ssl3CipherSpec *pwSpec;
1872
15
    ssl3CipherSpec *prSpec;
1873
15
    SECStatus rv;
1874
1875
15
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1876
15
    PORT_Assert(secret);
1877
1878
15
    ssl_GetSpecWriteLock(ss); /**************************************/
1879
1880
15
    PORT_Assert(ss->ssl3.pwSpec);
1881
15
    PORT_Assert(ss->ssl3.cwSpec->epoch == ss->ssl3.crSpec->epoch);
1882
15
    prSpec = ss->ssl3.prSpec;
1883
15
    pwSpec = ss->ssl3.pwSpec;
1884
1885
15
    if (ss->ssl3.cwSpec->epoch == PR_UINT16_MAX) {
1886
        /* The problem here is that we have rehandshaked too many
1887
         * times (you are not allowed to wrap the epoch). The
1888
         * spec says you should be discarding the connection
1889
         * and start over, so not much we can do here. */
1890
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1891
0
        goto loser;
1892
0
    }
1893
1894
15
    if (derive) {
1895
15
        rv = ssl3_ComputeMasterSecret(ss, secret, &masterSecret);
1896
15
        if (rv != SECSuccess) {
1897
0
            goto loser;
1898
0
        }
1899
15
    } else {
1900
0
        masterSecret = secret;
1901
0
    }
1902
1903
15
    PORT_Assert(masterSecret);
1904
15
    rv = ssl3_DeriveConnectionKeys(ss, masterSecret);
1905
15
    if (rv != SECSuccess) {
1906
0
        if (derive) {
1907
            /* masterSecret was created here. */
1908
0
            PK11_FreeSymKey(masterSecret);
1909
0
        }
1910
0
        goto loser;
1911
0
    }
1912
1913
    /* Both cipher specs maintain a reference to the master secret, since each
1914
     * is managed and freed independently. */
1915
15
    prSpec->masterSecret = masterSecret;
1916
15
    pwSpec->masterSecret = PK11_ReferenceSymKey(masterSecret);
1917
15
    rv = ssl3_InitPendingContexts(ss, ss->ssl3.prSpec);
1918
15
    if (rv != SECSuccess) {
1919
0
        goto loser;
1920
0
    }
1921
1922
15
    rv = ssl3_InitPendingContexts(ss, ss->ssl3.pwSpec);
1923
15
    if (rv != SECSuccess) {
1924
0
        goto loser;
1925
0
    }
1926
1927
15
    ssl_ReleaseSpecWriteLock(ss); /******************************/
1928
15
    return SECSuccess;
1929
1930
0
loser:
1931
0
    ssl_ReleaseSpecWriteLock(ss); /******************************/
1932
0
    ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
1933
0
    return SECFailure;
1934
15
}
1935
1936
/*
1937
 * 60 bytes is 3 times the maximum length MAC size that is supported.
1938
 */
1939
static const unsigned char mac_pad_1[60] = {
1940
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1941
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1942
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1943
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1944
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1945
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1946
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1947
    0x36, 0x36, 0x36, 0x36
1948
};
1949
static const unsigned char mac_pad_2[60] = {
1950
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1951
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1952
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1953
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1954
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1955
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1956
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1957
    0x5c, 0x5c, 0x5c, 0x5c
1958
};
1959
1960
/* Called from: ssl3_SendRecord()
1961
** Caller must already hold the SpecReadLock. (wish we could assert that!)
1962
*/
1963
static SECStatus
1964
ssl3_ComputeRecordMAC(
1965
    ssl3CipherSpec *spec,
1966
    const unsigned char *header,
1967
    unsigned int headerLen,
1968
    const PRUint8 *input,
1969
    int inputLen,
1970
    unsigned char *outbuf,
1971
    unsigned int *outLen)
1972
52.5k
{
1973
52.5k
    PK11Context *context;
1974
52.5k
    int macSize = spec->macDef->mac_size;
1975
52.5k
    SECStatus rv;
1976
1977
52.5k
    PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen));
1978
52.5k
    PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLen));
1979
1980
52.5k
    if (spec->macDef->mac == ssl_mac_null) {
1981
52.5k
        *outLen = 0;
1982
52.5k
        return SECSuccess;
1983
52.5k
    }
1984
1985
0
    context = spec->keyMaterial.macContext;
1986
0
    rv = PK11_DigestBegin(context);
1987
0
    rv |= PK11_DigestOp(context, header, headerLen);
1988
0
    rv |= PK11_DigestOp(context, input, inputLen);
1989
0
    rv |= PK11_DigestFinal(context, outbuf, outLen, macSize);
1990
0
    PORT_Assert(rv != SECSuccess || *outLen == (unsigned)macSize);
1991
1992
0
    PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLen));
1993
1994
0
    if (rv != SECSuccess) {
1995
0
        rv = SECFailure;
1996
0
        ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
1997
0
    }
1998
0
    return rv;
1999
52.5k
}
2000
2001
/* Called from: ssl3_HandleRecord()
2002
 * Caller must already hold the SpecReadLock. (wish we could assert that!)
2003
 *
2004
 * On entry:
2005
 *   originalLen >= inputLen >= MAC size
2006
 */
2007
static SECStatus
2008
ssl3_ComputeRecordMACConstantTime(
2009
    ssl3CipherSpec *spec,
2010
    const unsigned char *header,
2011
    unsigned int headerLen,
2012
    const PRUint8 *input,
2013
    int inputLen,
2014
    int originalLen,
2015
    unsigned char *outbuf,
2016
    unsigned int *outLen)
2017
54
{
2018
54
    CK_MECHANISM_TYPE macType;
2019
54
    CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
2020
54
    SECItem param, inputItem, outputItem;
2021
54
    int macSize = spec->macDef->mac_size;
2022
54
    SECStatus rv;
2023
2024
54
    PORT_Assert(inputLen >= spec->macDef->mac_size);
2025
54
    PORT_Assert(originalLen >= inputLen);
2026
2027
54
    if (spec->macDef->mac == ssl_mac_null) {
2028
0
        *outLen = 0;
2029
0
        return SECSuccess;
2030
0
    }
2031
2032
54
    macType = CKM_NSS_HMAC_CONSTANT_TIME;
2033
54
    if (spec->version == SSL_LIBRARY_VERSION_3_0) {
2034
0
        macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME;
2035
0
    }
2036
2037
54
    params.macAlg = spec->macDef->mmech;
2038
54
    params.ulBodyTotalLen = originalLen;
2039
54
    params.pHeader = (unsigned char *)header; /* const cast */
2040
54
    params.ulHeaderLen = headerLen;
2041
2042
54
    param.data = (unsigned char *)&params;
2043
54
    param.len = sizeof(params);
2044
54
    param.type = 0;
2045
2046
54
    inputItem.data = (unsigned char *)input;
2047
54
    inputItem.len = inputLen;
2048
54
    inputItem.type = 0;
2049
2050
54
    outputItem.data = outbuf;
2051
54
    outputItem.len = *outLen;
2052
54
    outputItem.type = 0;
2053
2054
54
    rv = PK11_SignWithSymKey(spec->keyMaterial.macKey, macType, &param,
2055
54
                             &outputItem, &inputItem);
2056
54
    if (rv != SECSuccess) {
2057
0
        if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) {
2058
            /* ssl3_ComputeRecordMAC() expects the MAC to have been removed
2059
             * from the input length already. */
2060
0
            return ssl3_ComputeRecordMAC(spec, header, headerLen,
2061
0
                                         input, inputLen - macSize,
2062
0
                                         outbuf, outLen);
2063
0
        }
2064
2065
0
        *outLen = 0;
2066
0
        rv = SECFailure;
2067
0
        ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2068
0
        return rv;
2069
0
    }
2070
2071
54
    PORT_Assert(outputItem.len == (unsigned)macSize);
2072
54
    *outLen = outputItem.len;
2073
2074
54
    return rv;
2075
54
}
2076
2077
static PRBool
2078
ssl3_ClientAuthTokenPresent(sslSessionID *sid)
2079
77.3k
{
2080
77.3k
    PK11SlotInfo *slot = NULL;
2081
77.3k
    PRBool isPresent = PR_TRUE;
2082
2083
    /* we only care if we are doing client auth */
2084
77.3k
    if (!sid || !sid->u.ssl3.clAuthValid) {
2085
77.3k
        return PR_TRUE;
2086
77.3k
    }
2087
2088
    /* get the slot */
2089
0
    slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
2090
0
                             sid->u.ssl3.clAuthSlotID);
2091
0
    if (slot == NULL ||
2092
0
        !PK11_IsPresent(slot) ||
2093
0
        sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) ||
2094
0
        sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) ||
2095
0
        sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) ||
2096
0
        (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
2097
0
        isPresent = PR_FALSE;
2098
0
    }
2099
0
    if (slot) {
2100
0
        PK11_FreeSlot(slot);
2101
0
    }
2102
0
    return isPresent;
2103
77.3k
}
2104
2105
/* Caller must hold the spec read lock. */
2106
SECStatus
2107
ssl3_MACEncryptRecord(ssl3CipherSpec *cwSpec,
2108
                      PRBool isServer,
2109
                      PRBool isDTLS,
2110
                      SSLContentType ct,
2111
                      const PRUint8 *pIn,
2112
                      PRUint32 contentLen,
2113
                      sslBuffer *wrBuf)
2114
38.4k
{
2115
38.4k
    SECStatus rv;
2116
38.4k
    PRUint32 macLen = 0;
2117
38.4k
    PRUint32 fragLen;
2118
38.4k
    PRUint32 p1Len, p2Len, oddLen = 0;
2119
38.4k
    unsigned int ivLen = 0;
2120
38.4k
    unsigned char pseudoHeaderBuf[13];
2121
38.4k
    sslBuffer pseudoHeader = SSL_BUFFER(pseudoHeaderBuf);
2122
38.4k
    unsigned int len;
2123
2124
38.4k
    if (cwSpec->cipherDef->type == type_block &&
2125
38.4k
        cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
2126
        /* Prepend the per-record explicit IV using technique 2b from
2127
         * RFC 4346 section 6.2.3.2: The IV is a cryptographically
2128
         * strong random number XORed with the CBC residue from the previous
2129
         * record.
2130
         */
2131
0
        ivLen = cwSpec->cipherDef->iv_size;
2132
0
        if (ivLen > SSL_BUFFER_SPACE(wrBuf)) {
2133
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2134
0
            return SECFailure;
2135
0
        }
2136
0
        rv = PK11_GenerateRandom(SSL_BUFFER_NEXT(wrBuf), ivLen);
2137
0
        if (rv != SECSuccess) {
2138
0
            ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
2139
0
            return rv;
2140
0
        }
2141
0
        rv = cwSpec->cipher(cwSpec->cipherContext,
2142
0
                            SSL_BUFFER_NEXT(wrBuf), /* output */
2143
0
                            &len,                   /* outlen */
2144
0
                            ivLen,                  /* max outlen */
2145
0
                            SSL_BUFFER_NEXT(wrBuf), /* input */
2146
0
                            ivLen);                 /* input len */
2147
0
        if (rv != SECSuccess || len != ivLen) {
2148
0
            PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2149
0
            return SECFailure;
2150
0
        }
2151
2152
0
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2153
0
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2154
0
    }
2155
38.4k
    rv = ssl3_BuildRecordPseudoHeader(
2156
38.4k
        cwSpec->epoch, cwSpec->nextSeqNum, ct,
2157
38.4k
        cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->recordVersion,
2158
38.4k
        isDTLS, contentLen, &pseudoHeader, cwSpec->version);
2159
38.4k
    PORT_Assert(rv == SECSuccess);
2160
38.4k
    if (cwSpec->cipherDef->type == type_aead) {
2161
0
        const unsigned int nonceLen = cwSpec->cipherDef->explicit_nonce_size;
2162
0
        const unsigned int tagLen = cwSpec->cipherDef->tag_size;
2163
0
        unsigned int ivOffset = 0;
2164
0
        CK_GENERATOR_FUNCTION gen;
2165
        /* ivOut includes the iv and the nonce and is the internal iv/nonce
2166
         * for the AEAD function. On Encrypt, this is an in/out parameter */
2167
0
        unsigned char ivOut[MAX_IV_LENGTH];
2168
0
        ivLen = cwSpec->cipherDef->iv_size;
2169
2170
0
        PORT_Assert((ivLen + nonceLen) <= MAX_IV_LENGTH);
2171
0
        PORT_Assert((ivLen + nonceLen) >= sizeof(sslSequenceNumber));
2172
2173
0
        if (nonceLen + contentLen + tagLen > SSL_BUFFER_SPACE(wrBuf)) {
2174
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2175
0
            return SECFailure;
2176
0
        }
2177
2178
0
        if (nonceLen == 0) {
2179
0
            ivOffset = ivLen - sizeof(sslSequenceNumber);
2180
0
            gen = CKG_GENERATE_COUNTER_XOR;
2181
0
        } else {
2182
0
            ivOffset = ivLen;
2183
0
            gen = CKG_GENERATE_COUNTER;
2184
0
        }
2185
0
        ivOffset = tls13_SetupAeadIv(isDTLS, cwSpec->version, ivOut, cwSpec->keyMaterial.iv,
2186
0
                                     ivOffset, ivLen, cwSpec->epoch);
2187
0
        rv = tls13_AEAD(cwSpec->cipherContext,
2188
0
                        PR_FALSE,
2189
0
                        gen, ivOffset * BPB,                /* iv generator params */
2190
0
                        ivOut,                              /* iv in  */
2191
0
                        ivOut,                              /* iv out */
2192
0
                        ivLen + nonceLen,                   /* full iv length */
2193
0
                        NULL, 0,                            /* nonce is generated*/
2194
0
                        SSL_BUFFER_BASE(&pseudoHeader),     /* aad */
2195
0
                        SSL_BUFFER_LEN(&pseudoHeader),      /* aadlen */
2196
0
                        SSL_BUFFER_NEXT(wrBuf) + nonceLen,  /* output  */
2197
0
                        &len,                               /* out len */
2198
0
                        SSL_BUFFER_SPACE(wrBuf) - nonceLen, /* max out */
2199
0
                        tagLen,
2200
0
                        pIn, contentLen); /* input   */
2201
0
        if (rv != SECSuccess) {
2202
0
            PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2203
0
            return SECFailure;
2204
0
        }
2205
0
        len += nonceLen; /* include the nonce at the beginning */
2206
        /* copy out the generated iv if we are using explict nonces */
2207
0
        if (nonceLen) {
2208
0
            PORT_Memcpy(SSL_BUFFER_NEXT(wrBuf), ivOut + ivLen, nonceLen);
2209
0
        }
2210
2211
0
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2212
0
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2213
38.4k
    } else {
2214
38.4k
        int blockSize = cwSpec->cipherDef->block_size;
2215
2216
        /*
2217
         * Add the MAC
2218
         */
2219
38.4k
        rv = ssl3_ComputeRecordMAC(cwSpec, SSL_BUFFER_BASE(&pseudoHeader),
2220
38.4k
                                   SSL_BUFFER_LEN(&pseudoHeader),
2221
38.4k
                                   pIn, contentLen,
2222
38.4k
                                   SSL_BUFFER_NEXT(wrBuf) + contentLen, &macLen);
2223
38.4k
        if (rv != SECSuccess) {
2224
0
            ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2225
0
            return SECFailure;
2226
0
        }
2227
38.4k
        p1Len = contentLen;
2228
38.4k
        p2Len = macLen;
2229
38.4k
        fragLen = contentLen + macLen; /* needs to be encrypted */
2230
38.4k
        PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
2231
2232
        /*
2233
         * Pad the text (if we're doing a block cipher)
2234
         * then Encrypt it
2235
         */
2236
38.4k
        if (cwSpec->cipherDef->type == type_block) {
2237
0
            unsigned char *pBuf;
2238
0
            int padding_length;
2239
0
            int i;
2240
2241
0
            oddLen = contentLen % blockSize;
2242
            /* Assume blockSize is a power of two */
2243
0
            padding_length = blockSize - 1 - ((fragLen) & (blockSize - 1));
2244
0
            fragLen += padding_length + 1;
2245
0
            PORT_Assert((fragLen % blockSize) == 0);
2246
2247
            /* Pad according to TLS rules (also acceptable to SSL3). */
2248
0
            pBuf = SSL_BUFFER_NEXT(wrBuf) + fragLen - 1;
2249
0
            for (i = padding_length + 1; i > 0; --i) {
2250
0
                *pBuf-- = padding_length;
2251
0
            }
2252
            /* now, if contentLen is not a multiple of block size, fix it */
2253
0
            p2Len = fragLen - p1Len;
2254
0
        }
2255
38.4k
        if (p1Len < 256) {
2256
26.5k
            oddLen = p1Len;
2257
26.5k
            p1Len = 0;
2258
26.5k
        } else {
2259
11.9k
            p1Len -= oddLen;
2260
11.9k
        }
2261
38.4k
        if (oddLen) {
2262
26.5k
            p2Len += oddLen;
2263
26.5k
            PORT_Assert((blockSize < 2) ||
2264
26.5k
                        (p2Len % blockSize) == 0);
2265
26.5k
            memmove(SSL_BUFFER_NEXT(wrBuf) + p1Len, pIn + p1Len, oddLen);
2266
26.5k
        }
2267
38.4k
        if (p1Len > 0) {
2268
11.9k
            unsigned int cipherBytesPart1 = 0;
2269
11.9k
            rv = cwSpec->cipher(cwSpec->cipherContext,
2270
11.9k
                                SSL_BUFFER_NEXT(wrBuf), /* output */
2271
11.9k
                                &cipherBytesPart1,      /* actual outlen */
2272
11.9k
                                p1Len,                  /* max outlen */
2273
11.9k
                                pIn,
2274
11.9k
                                p1Len); /* input, and inputlen */
2275
11.9k
            PORT_Assert(rv == SECSuccess && cipherBytesPart1 == p1Len);
2276
11.9k
            if (rv != SECSuccess || cipherBytesPart1 != p1Len) {
2277
0
                PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2278
0
                return SECFailure;
2279
0
            }
2280
11.9k
            rv = sslBuffer_Skip(wrBuf, p1Len, NULL);
2281
11.9k
            PORT_Assert(rv == SECSuccess);
2282
11.9k
        }
2283
38.4k
        if (p2Len > 0) {
2284
26.5k
            unsigned int cipherBytesPart2 = 0;
2285
26.5k
            rv = cwSpec->cipher(cwSpec->cipherContext,
2286
26.5k
                                SSL_BUFFER_NEXT(wrBuf),
2287
26.5k
                                &cipherBytesPart2, /* output and actual outLen */
2288
26.5k
                                p2Len,             /* max outlen */
2289
26.5k
                                SSL_BUFFER_NEXT(wrBuf),
2290
26.5k
                                p2Len); /* input and inputLen*/
2291
26.5k
            PORT_Assert(rv == SECSuccess && cipherBytesPart2 == p2Len);
2292
26.5k
            if (rv != SECSuccess || cipherBytesPart2 != p2Len) {
2293
0
                PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2294
0
                return SECFailure;
2295
0
            }
2296
26.5k
            rv = sslBuffer_Skip(wrBuf, p2Len, NULL);
2297
26.5k
            PORT_Assert(rv == SECSuccess);
2298
26.5k
        }
2299
38.4k
    }
2300
2301
38.4k
    return SECSuccess;
2302
38.4k
}
2303
2304
/* Note: though this can report failure, it shouldn't. */
2305
SECStatus
2306
ssl_InsertRecordHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec,
2307
                       SSLContentType contentType, sslBuffer *wrBuf,
2308
                       PRBool *needsLength)
2309
38.4k
{
2310
38.4k
    SECStatus rv;
2311
2312
38.4k
#ifndef UNSAFE_FUZZER_MODE
2313
38.4k
    if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
2314
38.4k
        cwSpec->epoch > TrafficKeyClearText) {
2315
0
        if (IS_DTLS(ss)) {
2316
0
            return dtls13_InsertCipherTextHeader(ss, cwSpec, wrBuf,
2317
0
                                                 needsLength);
2318
0
        }
2319
0
        contentType = ssl_ct_application_data;
2320
0
    }
2321
38.4k
#endif
2322
38.4k
    rv = sslBuffer_AppendNumber(wrBuf, contentType, 1);
2323
38.4k
    if (rv != SECSuccess) {
2324
0
        return SECFailure;
2325
0
    }
2326
2327
38.4k
    rv = sslBuffer_AppendNumber(wrBuf, cwSpec->recordVersion, 2);
2328
38.4k
    if (rv != SECSuccess) {
2329
0
        return SECFailure;
2330
0
    }
2331
38.4k
    if (IS_DTLS(ss)) {
2332
38.4k
        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->epoch, 2);
2333
38.4k
        if (rv != SECSuccess) {
2334
0
            return SECFailure;
2335
0
        }
2336
38.4k
        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->nextSeqNum, 6);
2337
38.4k
        if (rv != SECSuccess) {
2338
0
            return SECFailure;
2339
0
        }
2340
38.4k
    }
2341
38.4k
    *needsLength = PR_TRUE;
2342
38.4k
    return SECSuccess;
2343
38.4k
}
2344
2345
SECStatus
2346
ssl_ProtectRecord(sslSocket *ss, ssl3CipherSpec *cwSpec, SSLContentType ct,
2347
                  const PRUint8 *pIn, PRUint32 contentLen, sslBuffer *wrBuf)
2348
38.4k
{
2349
38.4k
    PRBool needsLength;
2350
38.4k
    unsigned int lenOffset;
2351
38.4k
    SECStatus rv;
2352
2353
38.4k
    PORT_Assert(cwSpec->direction == ssl_secret_write);
2354
38.4k
    PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
2355
38.4k
    PORT_Assert(cwSpec->cipherDef->max_records <= RECORD_SEQ_MAX);
2356
2357
38.4k
    if (cwSpec->nextSeqNum >= cwSpec->cipherDef->max_records) {
2358
0
        SSL_TRC(3, ("%d: SSL[-]: write sequence number at limit 0x%0llx",
2359
0
                    SSL_GETPID(), cwSpec->nextSeqNum));
2360
0
        PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
2361
0
        return SECFailure;
2362
0
    }
2363
2364
38.4k
    rv = ssl_InsertRecordHeader(ss, cwSpec, ct, wrBuf, &needsLength);
2365
38.4k
    if (rv != SECSuccess) {
2366
0
        return SECFailure;
2367
0
    }
2368
38.4k
    if (needsLength) {
2369
38.4k
        rv = sslBuffer_Skip(wrBuf, 2, &lenOffset);
2370
38.4k
        if (rv != SECSuccess) {
2371
0
            return SECFailure;
2372
0
        }
2373
38.4k
    }
2374
2375
#ifdef UNSAFE_FUZZER_MODE
2376
    {
2377
        unsigned int len;
2378
        rv = Null_Cipher(NULL, SSL_BUFFER_NEXT(wrBuf), &len,
2379
                         SSL_BUFFER_SPACE(wrBuf), pIn, contentLen);
2380
        if (rv != SECSuccess) {
2381
            return SECFailure; /* error was set */
2382
        }
2383
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2384
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2385
    }
2386
#else
2387
38.4k
    if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
2388
0
        PRUint8 *cipherText = SSL_BUFFER_NEXT(wrBuf);
2389
0
        unsigned int bufLen = SSL_BUFFER_LEN(wrBuf);
2390
0
        rv = tls13_ProtectRecord(ss, cwSpec, ct, pIn, contentLen, wrBuf);
2391
0
        if (rv != SECSuccess) {
2392
0
            return SECFailure;
2393
0
        }
2394
0
        if (IS_DTLS(ss)) {
2395
0
            bufLen = SSL_BUFFER_LEN(wrBuf) - bufLen;
2396
0
            rv = dtls13_MaskSequenceNumber(ss, cwSpec,
2397
0
                                           SSL_BUFFER_BASE(wrBuf),
2398
0
                                           cipherText, bufLen);
2399
0
        }
2400
38.4k
    } else {
2401
38.4k
        rv = ssl3_MACEncryptRecord(cwSpec, ss->sec.isServer, IS_DTLS(ss), ct,
2402
38.4k
                                   pIn, contentLen, wrBuf);
2403
38.4k
    }
2404
38.4k
#endif
2405
38.4k
    if (rv != SECSuccess) {
2406
0
        return SECFailure; /* error was set */
2407
0
    }
2408
2409
38.4k
    if (needsLength) {
2410
        /* Insert the length. */
2411
38.4k
        rv = sslBuffer_InsertLength(wrBuf, lenOffset, 2);
2412
38.4k
        if (rv != SECSuccess) {
2413
0
            PORT_Assert(0); /* Can't fail. */
2414
0
            return SECFailure;
2415
0
        }
2416
38.4k
    }
2417
2418
38.4k
    ++cwSpec->nextSeqNum;
2419
38.4k
    return SECSuccess;
2420
38.4k
}
2421
2422
SECStatus
2423
ssl_ProtectNextRecord(sslSocket *ss, ssl3CipherSpec *spec, SSLContentType ct,
2424
                      const PRUint8 *pIn, unsigned int nIn,
2425
                      unsigned int *written)
2426
38.4k
{
2427
38.4k
    sslBuffer *wrBuf = &ss->sec.writeBuf;
2428
38.4k
    unsigned int contentLen;
2429
38.4k
    unsigned int spaceNeeded;
2430
38.4k
    SECStatus rv;
2431
2432
38.4k
    contentLen = PR_MIN(nIn, spec->recordSizeLimit);
2433
38.4k
    spaceNeeded = contentLen + SSL3_BUFFER_FUDGE;
2434
38.4k
    if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
2435
38.4k
        spec->cipherDef->type == type_block) {
2436
0
        spaceNeeded += spec->cipherDef->iv_size;
2437
0
    }
2438
38.4k
    if (spaceNeeded > SSL_BUFFER_SPACE(wrBuf)) {
2439
0
        rv = sslBuffer_Grow(wrBuf, spaceNeeded);
2440
0
        if (rv != SECSuccess) {
2441
0
            SSL_DBG(("%d: SSL3[%d]: failed to expand write buffer to %d",
2442
0
                     SSL_GETPID(), ss->fd, spaceNeeded));
2443
0
            return SECFailure;
2444
0
        }
2445
0
    }
2446
2447
38.4k
    rv = ssl_ProtectRecord(ss, spec, ct, pIn, contentLen, wrBuf);
2448
38.4k
    if (rv != SECSuccess) {
2449
0
        return SECFailure;
2450
0
    }
2451
38.4k
    PRINT_BUF(50, (ss, "send (encrypted) record data:",
2452
38.4k
                   SSL_BUFFER_BASE(wrBuf), SSL_BUFFER_LEN(wrBuf)));
2453
38.4k
    *written = contentLen;
2454
38.4k
    return SECSuccess;
2455
38.4k
}
2456
2457
/* Process the plain text before sending it.
2458
 * Returns the number of bytes of plaintext that were successfully sent
2459
 *  plus the number of bytes of plaintext that were copied into the
2460
 *  output (write) buffer.
2461
 * Returns -1 on an error.  PR_WOULD_BLOCK_ERROR is set if the error is blocking
2462
 *  and not terminal.
2463
 *
2464
 * Notes on the use of the private ssl flags:
2465
 * (no private SSL flags)
2466
 *    Attempt to make and send SSL records for all plaintext
2467
 *    If non-blocking and a send gets WOULD_BLOCK,
2468
 *    or if the pending (ciphertext) buffer is not empty,
2469
 *    then buffer remaining bytes of ciphertext into pending buf,
2470
 *    and continue to do that for all succssive records until all
2471
 *    bytes are used.
2472
 * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2473
 *    As above, except this suppresses all write attempts, and forces
2474
 *    all ciphertext into the pending ciphertext buffer.
2475
 * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
2476
 *    Forces the use of the provided epoch
2477
 */
2478
PRInt32
2479
ssl3_SendRecord(sslSocket *ss,
2480
                ssl3CipherSpec *cwSpec, /* non-NULL for DTLS retransmits */
2481
                SSLContentType ct,
2482
                const PRUint8 *pIn, /* input buffer */
2483
                PRInt32 nIn,        /* bytes of input */
2484
                PRInt32 flags)
2485
38.5k
{
2486
38.5k
    sslBuffer *wrBuf = &ss->sec.writeBuf;
2487
38.5k
    ssl3CipherSpec *spec;
2488
38.5k
    SECStatus rv;
2489
38.5k
    PRInt32 totalSent = 0;
2490
2491
38.5k
    SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
2492
38.5k
                SSL_GETPID(), ss->fd, ssl3_DecodeContentType(ct),
2493
38.5k
                nIn));
2494
38.5k
    PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn));
2495
2496
38.5k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2497
38.5k
    PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
2498
2499
38.5k
    if (ss->ssl3.fatalAlertSent) {
2500
26
        SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent",
2501
26
                    SSL_GETPID(), ss->fd));
2502
26
        if (ct != ssl_ct_alert) {
2503
            /* If we are sending an alert, then we already have an
2504
             * error, so don't overwrite. */
2505
0
            PORT_SetError(SSL_ERROR_HANDSHAKE_FAILED);
2506
0
        }
2507
26
        return -1;
2508
26
    }
2509
2510
    /* check for Token Presence */
2511
38.4k
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
2512
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
2513
0
        return -1;
2514
0
    }
2515
2516
38.4k
    if (ss->recordWriteCallback) {
2517
0
        PRUint16 epoch;
2518
0
        ssl_GetSpecReadLock(ss);
2519
0
        epoch = ss->ssl3.cwSpec->epoch;
2520
0
        ssl_ReleaseSpecReadLock(ss);
2521
0
        rv = ss->recordWriteCallback(ss->fd, epoch, ct, pIn, nIn,
2522
0
                                     ss->recordWriteCallbackArg);
2523
0
        if (rv != SECSuccess) {
2524
0
            return -1;
2525
0
        }
2526
0
        return nIn;
2527
0
    }
2528
2529
38.4k
    if (cwSpec) {
2530
        /* cwSpec can only be set for retransmissions of the DTLS handshake. */
2531
31.5k
        PORT_Assert(IS_DTLS(ss) &&
2532
31.5k
                    (ct == ssl_ct_handshake ||
2533
31.5k
                     ct == ssl_ct_change_cipher_spec));
2534
31.5k
        spec = cwSpec;
2535
31.5k
    } else {
2536
6.93k
        spec = ss->ssl3.cwSpec;
2537
6.93k
    }
2538
2539
76.9k
    while (nIn > 0) {
2540
38.4k
        unsigned int written = 0;
2541
38.4k
        PRInt32 sent;
2542
2543
38.4k
        ssl_GetSpecReadLock(ss);
2544
38.4k
        rv = ssl_ProtectNextRecord(ss, spec, ct, pIn, nIn, &written);
2545
38.4k
        ssl_ReleaseSpecReadLock(ss);
2546
38.4k
        if (rv != SECSuccess) {
2547
0
            goto loser;
2548
0
        }
2549
2550
38.4k
        PORT_Assert(written > 0);
2551
        /* DTLS should not fragment non-application data here. */
2552
38.4k
        if (IS_DTLS(ss) && ct != ssl_ct_application_data) {
2553
38.4k
            PORT_Assert(written == nIn);
2554
38.4k
        }
2555
2556
38.4k
        pIn += written;
2557
38.4k
        nIn -= written;
2558
38.4k
        PORT_Assert(nIn >= 0);
2559
2560
        /* If there's still some previously saved ciphertext,
2561
         * or the caller doesn't want us to send the data yet,
2562
         * then add all our new ciphertext to the amount previously saved.
2563
         */
2564
38.4k
        if ((ss->pendingBuf.len > 0) ||
2565
38.4k
            (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2566
2567
31.5k
            rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf),
2568
31.5k
                                   SSL_BUFFER_LEN(wrBuf));
2569
31.5k
            if (rv != SECSuccess) {
2570
                /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2571
0
                goto loser;
2572
0
            }
2573
2574
31.5k
            if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2575
0
                ss->handshakeBegun = 1;
2576
0
                sent = ssl_SendSavedWriteData(ss);
2577
0
                if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2578
0
                    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2579
0
                    goto loser;
2580
0
                }
2581
0
                if (ss->pendingBuf.len) {
2582
0
                    flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2583
0
                }
2584
0
            }
2585
31.5k
        } else {
2586
6.93k
            PORT_Assert(SSL_BUFFER_LEN(wrBuf) > 0);
2587
6.93k
            ss->handshakeBegun = 1;
2588
6.93k
            sent = ssl_DefSend(ss, SSL_BUFFER_BASE(wrBuf),
2589
6.93k
                               SSL_BUFFER_LEN(wrBuf),
2590
6.93k
                               flags & ~ssl_SEND_FLAG_MASK);
2591
6.93k
            if (sent < 0) {
2592
0
                if (PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
2593
0
                    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2594
0
                    goto loser;
2595
0
                }
2596
                /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
2597
0
                sent = 0;
2598
0
            }
2599
6.93k
            if (SSL_BUFFER_LEN(wrBuf) > (unsigned int)sent) {
2600
0
                if (IS_DTLS(ss)) {
2601
                    /* DTLS just says no in this case. No buffering */
2602
0
                    PORT_SetError(PR_WOULD_BLOCK_ERROR);
2603
0
                    goto loser;
2604
0
                }
2605
                /* now take all the remaining unsent new ciphertext and
2606
                 * append it to the buffer of previously unsent ciphertext.
2607
                 */
2608
0
                rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf) + sent,
2609
0
                                       SSL_BUFFER_LEN(wrBuf) - sent);
2610
0
                if (rv != SECSuccess) {
2611
                    /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2612
0
                    goto loser;
2613
0
                }
2614
0
            }
2615
6.93k
        }
2616
38.4k
        wrBuf->len = 0;
2617
38.4k
        totalSent += written;
2618
38.4k
    }
2619
38.4k
    return totalSent;
2620
2621
0
loser:
2622
    /* Don't leave bits of buffer lying around. */
2623
0
    wrBuf->len = 0;
2624
0
    return -1;
2625
38.4k
}
2626
2627
0
#define SSL3_PENDING_HIGH_WATER 1024
2628
2629
/* Attempt to send the content of "in" in an SSL application_data record.
2630
 * Returns "len" or -1 on failure.
2631
 */
2632
int
2633
ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
2634
                         PRInt32 len, PRInt32 flags)
2635
0
{
2636
0
    PRInt32 totalSent = 0;
2637
0
    PRInt32 discarded = 0;
2638
0
    PRBool splitNeeded = PR_FALSE;
2639
2640
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2641
    /* These flags for internal use only */
2642
0
    PORT_Assert(!(flags & ssl_SEND_FLAG_NO_RETRANSMIT));
2643
0
    if (len < 0 || !in) {
2644
0
        PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2645
0
        return -1;
2646
0
    }
2647
2648
0
    if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
2649
0
        !ssl_SocketIsBlocking(ss)) {
2650
0
        PORT_Assert(!ssl_SocketIsBlocking(ss));
2651
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
2652
0
        return -1;
2653
0
    }
2654
2655
0
    if (ss->appDataBuffered && len) {
2656
0
        PORT_Assert(in[0] == (unsigned char)(ss->appDataBuffered));
2657
0
        if (in[0] != (unsigned char)(ss->appDataBuffered)) {
2658
0
            PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2659
0
            return -1;
2660
0
        }
2661
0
        in++;
2662
0
        len--;
2663
0
        discarded = 1;
2664
0
    }
2665
2666
    /* We will split the first byte of the record into its own record, as
2667
     * explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h.
2668
     */
2669
0
    if (len > 1 && ss->opt.cbcRandomIV &&
2670
0
        ss->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
2671
0
        ss->ssl3.cwSpec->cipherDef->type == type_block /* CBC */) {
2672
0
        splitNeeded = PR_TRUE;
2673
0
    }
2674
2675
0
    while (len > totalSent) {
2676
0
        PRInt32 sent, toSend;
2677
2678
0
        if (totalSent > 0) {
2679
            /*
2680
             * The thread yield is intended to give the reader thread a
2681
             * chance to get some cycles while the writer thread is in
2682
             * the middle of a large application data write.  (See
2683
             * Bugzilla bug 127740, comment #1.)
2684
             */
2685
0
            ssl_ReleaseXmitBufLock(ss);
2686
0
            PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */
2687
0
            ssl_GetXmitBufLock(ss);
2688
0
        }
2689
2690
0
        if (splitNeeded) {
2691
0
            toSend = 1;
2692
0
            splitNeeded = PR_FALSE;
2693
0
        } else {
2694
0
            toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
2695
0
        }
2696
2697
        /*
2698
         * Note that the 0 epoch is OK because flags will never require
2699
         * its use, as guaranteed by the PORT_Assert above.
2700
         */
2701
0
        sent = ssl3_SendRecord(ss, NULL, ssl_ct_application_data,
2702
0
                               in + totalSent, toSend, flags);
2703
0
        if (sent < 0) {
2704
0
            if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
2705
0
                PORT_Assert(ss->lastWriteBlocked);
2706
0
                break;
2707
0
            }
2708
0
            return -1; /* error code set by ssl3_SendRecord */
2709
0
        }
2710
0
        totalSent += sent;
2711
0
        if (ss->pendingBuf.len) {
2712
            /* must be a non-blocking socket */
2713
0
            PORT_Assert(!ssl_SocketIsBlocking(ss));
2714
0
            PORT_Assert(ss->lastWriteBlocked);
2715
0
            break;
2716
0
        }
2717
0
    }
2718
0
    if (ss->pendingBuf.len) {
2719
        /* Must be non-blocking. */
2720
0
        PORT_Assert(!ssl_SocketIsBlocking(ss));
2721
0
        if (totalSent > 0) {
2722
0
            ss->appDataBuffered = 0x100 | in[totalSent - 1];
2723
0
        }
2724
2725
0
        totalSent = totalSent + discarded - 1;
2726
0
        if (totalSent <= 0) {
2727
0
            PORT_SetError(PR_WOULD_BLOCK_ERROR);
2728
0
            totalSent = SECFailure;
2729
0
        }
2730
0
        return totalSent;
2731
0
    }
2732
0
    ss->appDataBuffered = 0;
2733
0
    return totalSent + discarded;
2734
0
}
2735
2736
/* Attempt to send buffered handshake messages.
2737
 * Always set sendBuf.len to 0, even when returning SECFailure.
2738
 *
2739
 * Depending on whether we are doing DTLS or not, this either calls
2740
 *
2741
 * - ssl3_FlushHandshakeMessages if non-DTLS
2742
 * - dtls_FlushHandshakeMessages if DTLS
2743
 *
2744
 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
2745
 *             ssl3_AppendHandshake(), ssl3_SendClientHello(),
2746
 *             ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
2747
 *             ssl3_SendFinished(),
2748
 */
2749
SECStatus
2750
ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
2751
13.0k
{
2752
13.0k
    if (IS_DTLS(ss)) {
2753
13.0k
        return dtls_FlushHandshakeMessages(ss, flags);
2754
13.0k
    }
2755
0
    return ssl3_FlushHandshakeMessages(ss, flags);
2756
13.0k
}
2757
2758
/* Attempt to send the content of sendBuf buffer in an SSL handshake record.
2759
 * Always set sendBuf.len to 0, even when returning SECFailure.
2760
 *
2761
 * Called from ssl3_FlushHandshake
2762
 */
2763
static SECStatus
2764
ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
2765
0
{
2766
0
    static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2767
0
    PRInt32 count = -1;
2768
0
    SECStatus rv;
2769
2770
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2771
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2772
2773
0
    if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
2774
0
        return SECSuccess;
2775
2776
    /* only these flags are allowed */
2777
0
    PORT_Assert(!(flags & ~allowedFlags));
2778
0
    if ((flags & ~allowedFlags) != 0) {
2779
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
2780
0
        return SECFailure;
2781
0
    }
2782
0
    count = ssl3_SendRecord(ss, NULL, ssl_ct_handshake,
2783
0
                            ss->sec.ci.sendBuf.buf,
2784
0
                            ss->sec.ci.sendBuf.len, flags);
2785
0
    if (count < 0) {
2786
0
        int err = PORT_GetError();
2787
0
        PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
2788
0
        if (err == PR_WOULD_BLOCK_ERROR) {
2789
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2790
0
        }
2791
0
        rv = SECFailure;
2792
0
    } else if ((unsigned int)count < ss->sec.ci.sendBuf.len) {
2793
        /* short write should never happen */
2794
0
        PORT_Assert((unsigned int)count >= ss->sec.ci.sendBuf.len);
2795
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2796
0
        rv = SECFailure;
2797
0
    } else {
2798
0
        rv = SECSuccess;
2799
0
    }
2800
2801
    /* Whether we succeeded or failed, toss the old handshake data. */
2802
0
    ss->sec.ci.sendBuf.len = 0;
2803
0
    return rv;
2804
0
}
2805
2806
/*
2807
 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
2808
 * the remote client sends a negative response to our certificate request.
2809
 * Returns SECFailure if the application has required client auth.
2810
 *         SECSuccess otherwise.
2811
 */
2812
SECStatus
2813
ssl3_HandleNoCertificate(sslSocket *ss)
2814
3
{
2815
3
    ssl3_CleanupPeerCerts(ss);
2816
2817
    /* If the server has required client-auth blindly but doesn't
2818
     * actually look at the certificate it won't know that no
2819
     * certificate was presented so we shutdown the socket to ensure
2820
     * an error.  We only do this if we haven't already completed the
2821
     * first handshake because if we're redoing the handshake we
2822
     * know the server is paying attention to the certificate.
2823
     */
2824
3
    if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
2825
3
        (!ss->firstHsDone &&
2826
2
         (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
2827
1
        PRFileDesc *lower;
2828
2829
1
        ssl_UncacheSessionID(ss);
2830
2831
1
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
2832
0
            SSL3_SendAlert(ss, alert_fatal, certificate_required);
2833
1
        } else {
2834
1
            SSL3_SendAlert(ss, alert_fatal, bad_certificate);
2835
1
        }
2836
2837
1
        lower = ss->fd->lower;
2838
#ifdef _WIN32
2839
        lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
2840
#else
2841
1
        lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
2842
1
#endif
2843
1
        PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
2844
1
        return SECFailure;
2845
1
    }
2846
2
    return SECSuccess;
2847
3
}
2848
2849
/************************************************************************
2850
 * Alerts
2851
 */
2852
2853
/*
2854
** Acquires both handshake and XmitBuf locks.
2855
** Called from: ssl3_IllegalParameter   <-
2856
**              ssl3_HandshakeFailure   <-
2857
**              ssl3_HandleAlert    <- ssl3_HandleRecord.
2858
**              ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
2859
**              ssl3_ConsumeHandshakeVariable <-
2860
**              ssl3_HandleHelloRequest <-
2861
**              ssl3_HandleServerHello  <-
2862
**              ssl3_HandleServerKeyExchange <-
2863
**              ssl3_HandleCertificateRequest <-
2864
**              ssl3_HandleServerHelloDone <-
2865
**              ssl3_HandleClientHello  <-
2866
**              ssl3_HandleV2ClientHello <-
2867
**              ssl3_HandleCertificateVerify <-
2868
**              ssl3_HandleClientKeyExchange <-
2869
**              ssl3_HandleCertificate  <-
2870
**              ssl3_HandleFinished <-
2871
**              ssl3_HandleHandshakeMessage <-
2872
**              ssl3_HandlePostHelloHandshakeMessage <-
2873
**              ssl3_HandleRecord   <-
2874
**
2875
*/
2876
SECStatus
2877
SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
2878
6.96k
{
2879
6.96k
    PRUint8 bytes[2];
2880
6.96k
    SECStatus rv;
2881
6.96k
    PRBool needHsLock = !ssl_HaveSSL3HandshakeLock(ss);
2882
2883
    /* Check that if I need the HS lock I also need the Xmit lock */
2884
6.96k
    PORT_Assert(!needHsLock || !ssl_HaveXmitBufLock(ss));
2885
2886
6.96k
    SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
2887
6.96k
                SSL_GETPID(), ss->fd, level, desc));
2888
2889
6.96k
    bytes[0] = level;
2890
6.96k
    bytes[1] = desc;
2891
2892
6.96k
    if (needHsLock) {
2893
0
        ssl_GetSSL3HandshakeLock(ss);
2894
0
    }
2895
6.96k
    if (level == alert_fatal) {
2896
6.96k
        if (ss->sec.ci.sid) {
2897
5.38k
            ssl_UncacheSessionID(ss);
2898
5.38k
        }
2899
6.96k
    }
2900
2901
6.96k
    rv = tls13_SetAlertCipherSpec(ss);
2902
6.96k
    if (rv != SECSuccess) {
2903
0
        if (needHsLock) {
2904
0
            ssl_ReleaseSSL3HandshakeLock(ss);
2905
0
        }
2906
0
        return rv;
2907
0
    }
2908
2909
6.96k
    ssl_GetXmitBufLock(ss);
2910
6.96k
    rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
2911
6.96k
    if (rv == SECSuccess) {
2912
6.96k
        PRInt32 sent;
2913
6.96k
        sent = ssl3_SendRecord(ss, NULL, ssl_ct_alert, bytes, 2,
2914
6.96k
                               (desc == no_certificate) ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
2915
6.96k
        rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
2916
6.96k
    }
2917
6.96k
    if (level == alert_fatal) {
2918
6.96k
        ss->ssl3.fatalAlertSent = PR_TRUE;
2919
6.96k
    }
2920
6.96k
    ssl_ReleaseXmitBufLock(ss);
2921
6.96k
    if (needHsLock) {
2922
0
        ssl_ReleaseSSL3HandshakeLock(ss);
2923
0
    }
2924
6.96k
    if (rv == SECSuccess && ss->alertSentCallback) {
2925
0
        SSLAlert alert = { level, desc };
2926
0
        ss->alertSentCallback(ss->fd, ss->alertSentCallbackArg, &alert);
2927
0
    }
2928
6.96k
    return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
2929
6.96k
}
2930
2931
/*
2932
 * Send illegal_parameter alert.  Set generic error number.
2933
 */
2934
static SECStatus
2935
ssl3_IllegalParameter(sslSocket *ss)
2936
0
{
2937
0
    (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
2938
0
    PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2939
0
                                   : SSL_ERROR_BAD_SERVER);
2940
0
    return SECFailure;
2941
0
}
2942
2943
/*
2944
 * Send handshake_Failure alert.  Set generic error number.
2945
 */
2946
static SECStatus
2947
ssl3_HandshakeFailure(sslSocket *ss)
2948
0
{
2949
0
    (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
2950
0
    PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2951
0
                                   : SSL_ERROR_BAD_SERVER);
2952
0
    return SECFailure;
2953
0
}
2954
2955
void
2956
ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode)
2957
2
{
2958
2
    SSL3AlertDescription desc = bad_certificate;
2959
2
    PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
2960
2961
2
    switch (errCode) {
2962
0
        case SEC_ERROR_LIBRARY_FAILURE:
2963
0
            desc = unsupported_certificate;
2964
0
            break;
2965
0
        case SEC_ERROR_EXPIRED_CERTIFICATE:
2966
0
            desc = certificate_expired;
2967
0
            break;
2968
0
        case SEC_ERROR_REVOKED_CERTIFICATE:
2969
0
            desc = certificate_revoked;
2970
0
            break;
2971
0
        case SEC_ERROR_INADEQUATE_KEY_USAGE:
2972
0
        case SEC_ERROR_INADEQUATE_CERT_TYPE:
2973
0
            desc = certificate_unknown;
2974
0
            break;
2975
0
        case SEC_ERROR_UNTRUSTED_CERT:
2976
0
            desc = isTLS ? access_denied : certificate_unknown;
2977
0
            break;
2978
0
        case SEC_ERROR_UNKNOWN_ISSUER:
2979
0
        case SEC_ERROR_UNTRUSTED_ISSUER:
2980
0
            desc = isTLS ? unknown_ca : certificate_unknown;
2981
0
            break;
2982
0
        case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
2983
0
            desc = isTLS ? unknown_ca : certificate_expired;
2984
0
            break;
2985
2986
0
        case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
2987
0
        case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
2988
0
        case SEC_ERROR_CA_CERT_INVALID:
2989
1
        case SEC_ERROR_BAD_SIGNATURE:
2990
2
        default:
2991
2
            desc = bad_certificate;
2992
2
            break;
2993
2
    }
2994
2
    SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
2995
2
             SSL_GETPID(), ss->fd, errCode));
2996
2997
2
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
2998
2
}
2999
3000
/*
3001
 * Send decode_error alert.  Set generic error number.
3002
 */
3003
SECStatus
3004
ssl3_DecodeError(sslSocket *ss)
3005
212
{
3006
212
    (void)SSL3_SendAlert(ss, alert_fatal,
3007
212
                         ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error
3008
212
                                                               : illegal_parameter);
3009
212
    PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3010
212
                                   : SSL_ERROR_BAD_SERVER);
3011
212
    return SECFailure;
3012
212
}
3013
3014
/* Called from ssl3_HandleRecord.
3015
** Caller must hold both RecvBuf and Handshake locks.
3016
*/
3017
static SECStatus
3018
ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
3019
636
{
3020
636
    SSL3AlertLevel level;
3021
636
    SSL3AlertDescription desc;
3022
636
    int error;
3023
3024
636
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3025
636
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3026
3027
636
    SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
3028
3029
636
    if (buf->len != 2) {
3030
39
        (void)ssl3_DecodeError(ss);
3031
39
        PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
3032
39
        return SECFailure;
3033
39
    }
3034
597
    level = (SSL3AlertLevel)buf->buf[0];
3035
597
    desc = (SSL3AlertDescription)buf->buf[1];
3036
597
    buf->len = 0;
3037
597
    SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
3038
597
                SSL_GETPID(), ss->fd, level, desc));
3039
3040
597
    if (ss->alertReceivedCallback) {
3041
0
        SSLAlert alert = { level, desc };
3042
0
        ss->alertReceivedCallback(ss->fd, ss->alertReceivedCallbackArg, &alert);
3043
0
    }
3044
3045
597
    switch (desc) {
3046
2
        case close_notify:
3047
2
            ss->recvdCloseNotify = 1;
3048
2
            error = SSL_ERROR_CLOSE_NOTIFY_ALERT;
3049
2
            break;
3050
22
        case unexpected_message:
3051
22
            error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
3052
22
            break;
3053
18
        case bad_record_mac:
3054
18
            error = SSL_ERROR_BAD_MAC_ALERT;
3055
18
            break;
3056
25
        case decryption_failed_RESERVED:
3057
25
            error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
3058
25
            break;
3059
12
        case record_overflow:
3060
12
            error = SSL_ERROR_RECORD_OVERFLOW_ALERT;
3061
12
            break;
3062
19
        case decompression_failure:
3063
19
            error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
3064
19
            break;
3065
26
        case handshake_failure:
3066
26
            error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
3067
26
            break;
3068
24
        case no_certificate:
3069
24
            error = SSL_ERROR_NO_CERTIFICATE;
3070
24
            break;
3071
10
        case certificate_required:
3072
10
            error = SSL_ERROR_RX_CERTIFICATE_REQUIRED_ALERT;
3073
10
            break;
3074
18
        case bad_certificate:
3075
18
            error = SSL_ERROR_BAD_CERT_ALERT;
3076
18
            break;
3077
20
        case unsupported_certificate:
3078
20
            error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;
3079
20
            break;
3080
10
        case certificate_revoked:
3081
10
            error = SSL_ERROR_REVOKED_CERT_ALERT;
3082
10
            break;
3083
11
        case certificate_expired:
3084
11
            error = SSL_ERROR_EXPIRED_CERT_ALERT;
3085
11
            break;
3086
18
        case certificate_unknown:
3087
18
            error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
3088
18
            break;
3089
18
        case illegal_parameter:
3090
18
            error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;
3091
18
            break;
3092
11
        case inappropriate_fallback:
3093
11
            error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
3094
11
            break;
3095
3096
        /* All alerts below are TLS only. */
3097
18
        case unknown_ca:
3098
18
            error = SSL_ERROR_UNKNOWN_CA_ALERT;
3099
18
            break;
3100
12
        case access_denied:
3101
12
            error = SSL_ERROR_ACCESS_DENIED_ALERT;
3102
12
            break;
3103
23
        case decode_error:
3104
23
            error = SSL_ERROR_DECODE_ERROR_ALERT;
3105
23
            break;
3106
18
        case decrypt_error:
3107
18
            error = SSL_ERROR_DECRYPT_ERROR_ALERT;
3108
18
            break;
3109
19
        case export_restriction:
3110
19
            error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
3111
19
            break;
3112
18
        case protocol_version:
3113
18
            error = SSL_ERROR_PROTOCOL_VERSION_ALERT;
3114
18
            break;
3115
10
        case insufficient_security:
3116
10
            error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
3117
10
            break;
3118
21
        case internal_error:
3119
21
            error = SSL_ERROR_INTERNAL_ERROR_ALERT;
3120
21
            break;
3121
19
        case user_canceled:
3122
19
            error = SSL_ERROR_USER_CANCELED_ALERT;
3123
19
            break;
3124
20
        case no_renegotiation:
3125
20
            error = SSL_ERROR_NO_RENEGOTIATION_ALERT;
3126
20
            break;
3127
3128
        /* Alerts for TLS client hello extensions */
3129
18
        case missing_extension:
3130
18
            error = SSL_ERROR_MISSING_EXTENSION_ALERT;
3131
18
            break;
3132
23
        case unsupported_extension:
3133
23
            error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT;
3134
23
            break;
3135
20
        case certificate_unobtainable:
3136
20
            error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT;
3137
20
            break;
3138
19
        case unrecognized_name:
3139
19
            error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
3140
19
            break;
3141
11
        case bad_certificate_status_response:
3142
11
            error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT;
3143
11
            break;
3144
18
        case bad_certificate_hash_value:
3145
18
            error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT;
3146
18
            break;
3147
10
        case no_application_protocol:
3148
10
            error = SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL;
3149
10
            break;
3150
10
        case ech_required:
3151
10
            error = SSL_ERROR_ECH_REQUIRED_ALERT;
3152
10
            break;
3153
26
        default:
3154
26
            error = SSL_ERROR_RX_UNKNOWN_ALERT;
3155
26
            break;
3156
597
    }
3157
597
    if ((ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) &&
3158
597
        (ss->ssl3.hs.ws != wait_server_hello)) {
3159
        /* TLS 1.3 requires all but "end of data" alerts to be
3160
         * treated as fatal. */
3161
0
        switch (desc) {
3162
0
            case close_notify:
3163
0
            case user_canceled:
3164
0
                break;
3165
0
            default:
3166
0
                level = alert_fatal;
3167
0
        }
3168
0
    }
3169
597
    if (level == alert_fatal) {
3170
14
        ssl_UncacheSessionID(ss);
3171
14
        if ((ss->ssl3.hs.ws == wait_server_hello) &&
3172
14
            (desc == handshake_failure)) {
3173
            /* XXX This is a hack.  We're assuming that any handshake failure
3174
             * XXX on the client hello is a failure to match ciphers.
3175
             */
3176
0
            error = SSL_ERROR_NO_CYPHER_OVERLAP;
3177
0
        }
3178
14
        PORT_SetError(error);
3179
14
        return SECFailure;
3180
14
    }
3181
583
    if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
3182
        /* I'm a server. I've requested a client cert. He hasn't got one. */
3183
3
        SECStatus rv;
3184
3185
3
        PORT_Assert(ss->sec.isServer);
3186
3
        ss->ssl3.hs.ws = wait_client_key;
3187
3
        rv = ssl3_HandleNoCertificate(ss);
3188
3
        return rv;
3189
3
    }
3190
580
    return SECSuccess;
3191
583
}
3192
3193
/*
3194
 * Change Cipher Specs
3195
 * Called from ssl3_HandleServerHelloDone,
3196
 *             ssl3_HandleClientHello,
3197
 * and         ssl3_HandleFinished
3198
 *
3199
 * Acquires and releases spec write lock, to protect switching the current
3200
 * and pending write spec pointers.
3201
 */
3202
3203
SECStatus
3204
ssl3_SendChangeCipherSpecsInt(sslSocket *ss)
3205
0
{
3206
0
    PRUint8 change = change_cipher_spec_choice;
3207
0
    SECStatus rv;
3208
3209
0
    SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
3210
0
                SSL_GETPID(), ss->fd));
3211
3212
0
    rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3213
0
    if (rv != SECSuccess) {
3214
0
        return SECFailure; /* error code set by ssl3_FlushHandshake */
3215
0
    }
3216
3217
0
    if (!IS_DTLS(ss)) {
3218
0
        PRInt32 sent;
3219
0
        sent = ssl3_SendRecord(ss, NULL, ssl_ct_change_cipher_spec,
3220
0
                               &change, 1, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3221
0
        if (sent < 0) {
3222
0
            return SECFailure; /* error code set by ssl3_SendRecord */
3223
0
        }
3224
0
    } else {
3225
0
        rv = dtls_QueueMessage(ss, ssl_ct_change_cipher_spec, &change, 1);
3226
0
        if (rv != SECSuccess) {
3227
0
            return SECFailure;
3228
0
        }
3229
0
    }
3230
0
    return SECSuccess;
3231
0
}
3232
3233
static SECStatus
3234
ssl3_SendChangeCipherSpecs(sslSocket *ss)
3235
0
{
3236
0
    SECStatus rv;
3237
3238
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3239
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3240
3241
0
    rv = ssl3_SendChangeCipherSpecsInt(ss);
3242
0
    if (rv != SECSuccess) {
3243
0
        return rv; /* Error code set. */
3244
0
    }
3245
3246
    /* swap the pending and current write specs. */
3247
0
    ssl_GetSpecWriteLock(ss); /**************************************/
3248
3249
0
    ssl_CipherSpecRelease(ss->ssl3.cwSpec);
3250
0
    ss->ssl3.cwSpec = ss->ssl3.pwSpec;
3251
0
    ss->ssl3.pwSpec = NULL;
3252
3253
0
    SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
3254
0
                SSL_GETPID(), ss->fd));
3255
3256
    /* With DTLS, we need to set a holddown timer in case the final
3257
     * message got lost */
3258
0
    if (IS_DTLS(ss) && ss->ssl3.crSpec->epoch == ss->ssl3.cwSpec->epoch) {
3259
0
        rv = dtls_StartHolddownTimer(ss);
3260
0
    }
3261
0
    ssl_ReleaseSpecWriteLock(ss); /**************************************/
3262
3263
0
    return rv;
3264
0
}
3265
3266
/* Called from ssl3_HandleRecord.
3267
** Caller must hold both RecvBuf and Handshake locks.
3268
*
3269
* Acquires and releases spec write lock, to protect switching the current
3270
* and pending write spec pointers.
3271
*/
3272
static SECStatus
3273
ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
3274
94
{
3275
94
    SSL3WaitState ws = ss->ssl3.hs.ws;
3276
94
    SSL3ChangeCipherSpecChoice change;
3277
3278
94
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3279
94
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3280
3281
94
    SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
3282
94
                SSL_GETPID(), ss->fd));
3283
3284
    /* For DTLS: Ignore this if we aren't expecting it.  Don't kill a connection
3285
     *           as a result of receiving trash.
3286
     * For TLS: Maybe ignore, but only after checking format. */
3287
94
    if (ws != wait_change_cipher && IS_DTLS(ss)) {
3288
        /* Ignore this because it's out of order. */
3289
90
        SSL_TRC(3, ("%d: SSL3[%d]: discard out of order "
3290
90
                    "DTLS change_cipher_spec",
3291
90
                    SSL_GETPID(), ss->fd));
3292
90
        buf->len = 0;
3293
90
        return SECSuccess;
3294
90
    }
3295
3296
    /* Handshake messages should not span ChangeCipherSpec. */
3297
4
    if (ss->ssl3.hs.header_bytes) {
3298
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3299
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3300
0
        return SECFailure;
3301
0
    }
3302
4
    if (buf->len != 1) {
3303
0
        (void)ssl3_DecodeError(ss);
3304
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3305
0
        return SECFailure;
3306
0
    }
3307
4
    change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
3308
4
    if (change != change_cipher_spec_choice) {
3309
        /* illegal_parameter is correct here for both SSL3 and TLS. */
3310
0
        (void)ssl3_IllegalParameter(ss);
3311
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3312
0
        return SECFailure;
3313
0
    }
3314
3315
4
    buf->len = 0;
3316
4
    if (ws != wait_change_cipher) {
3317
        /* Ignore a CCS for TLS 1.3. This only happens if the server sends a
3318
         * HelloRetryRequest.  In other cases, the CCS will fail decryption and
3319
         * will be discarded by ssl3_HandleRecord(). */
3320
0
        if (ws == wait_server_hello &&
3321
0
            ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
3322
0
            ss->ssl3.hs.helloRetry) {
3323
0
            PORT_Assert(!ss->sec.isServer);
3324
0
            return SECSuccess;
3325
0
        }
3326
        /* Note: For a server, we can't test ss->ssl3.hs.helloRetry or
3327
         * ss->version because the server might be stateless (and so it won't
3328
         * have set either value yet). Set a flag so that at least we will
3329
         * guarantee that the server will treat any ClientHello properly. */
3330
0
        if (ws == wait_client_hello &&
3331
0
            ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3 &&
3332
0
            !ss->ssl3.hs.receivedCcs) {
3333
0
            PORT_Assert(ss->sec.isServer);
3334
0
            ss->ssl3.hs.receivedCcs = PR_TRUE;
3335
0
            return SECSuccess;
3336
0
        }
3337
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3338
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3339
0
        return SECFailure;
3340
0
    }
3341
3342
4
    SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
3343
4
                SSL_GETPID(), ss->fd));
3344
4
    ssl_GetSpecWriteLock(ss); /*************************************/
3345
4
    PORT_Assert(ss->ssl3.prSpec);
3346
4
    ssl_CipherSpecRelease(ss->ssl3.crSpec);
3347
4
    ss->ssl3.crSpec = ss->ssl3.prSpec;
3348
4
    ss->ssl3.prSpec = NULL;
3349
4
    ssl_ReleaseSpecWriteLock(ss); /*************************************/
3350
3351
4
    ss->ssl3.hs.ws = wait_finished;
3352
4
    return SECSuccess;
3353
4
}
3354
3355
static CK_MECHANISM_TYPE
3356
ssl3_GetMgfMechanismByHashType(SSLHashType hash)
3357
174
{
3358
174
    switch (hash) {
3359
54
        case ssl_hash_sha256:
3360
54
            return CKG_MGF1_SHA256;
3361
60
        case ssl_hash_sha384:
3362
60
            return CKG_MGF1_SHA384;
3363
60
        case ssl_hash_sha512:
3364
60
            return CKG_MGF1_SHA512;
3365
0
        default:
3366
0
            PORT_Assert(0);
3367
174
    }
3368
0
    return CKG_MGF1_SHA256;
3369
174
}
3370
3371
/* Function valid for >= TLS 1.2, only. */
3372
static CK_MECHANISM_TYPE
3373
ssl3_GetHashMechanismByHashType(SSLHashType hashType)
3374
206
{
3375
206
    switch (hashType) {
3376
60
        case ssl_hash_sha512:
3377
60
            return CKM_SHA512;
3378
66
        case ssl_hash_sha384:
3379
66
            return CKM_SHA384;
3380
75
        case ssl_hash_sha256:
3381
80
        case ssl_hash_none:
3382
            /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
3383
80
            return CKM_SHA256;
3384
0
        case ssl_hash_sha1:
3385
0
            return CKM_SHA_1;
3386
0
        default:
3387
0
            PORT_Assert(0);
3388
206
    }
3389
0
    return CKM_SHA256;
3390
206
}
3391
3392
/* Function valid for >= TLS 1.2, only. */
3393
static CK_MECHANISM_TYPE
3394
ssl3_GetPrfHashMechanism(sslSocket *ss)
3395
32
{
3396
32
    return ssl3_GetHashMechanismByHashType(ss->ssl3.hs.suite_def->prf_hash);
3397
32
}
3398
3399
static SSLHashType
3400
ssl3_GetSuitePrfHash(sslSocket *ss)
3401
2
{
3402
    /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
3403
2
    if (ss->ssl3.hs.suite_def->prf_hash == ssl_hash_none) {
3404
0
        return ssl_hash_sha256;
3405
0
    }
3406
2
    return ss->ssl3.hs.suite_def->prf_hash;
3407
2
}
3408
3409
/* This method completes the derivation of the MS from the PMS.
3410
**
3411
** 1. Derive the MS, if possible, else return an error.
3412
**
3413
** 2. Check the version if |pms_version| is non-zero and if wrong,
3414
**    return an error.
3415
**
3416
** 3. If |msp| is nonzero, return MS in |*msp|.
3417
3418
** Called from:
3419
**   ssl3_ComputeMasterSecretInt
3420
**   tls_ComputeExtendedMasterSecretInt
3421
*/
3422
static SECStatus
3423
ssl3_ComputeMasterSecretFinish(sslSocket *ss,
3424
                               CK_MECHANISM_TYPE master_derive,
3425
                               CK_MECHANISM_TYPE key_derive,
3426
                               CK_VERSION *pms_version,
3427
                               SECItem *params, CK_FLAGS keyFlags,
3428
                               PK11SymKey *pms, PK11SymKey **msp)
3429
17
{
3430
17
    PK11SymKey *ms = NULL;
3431
3432
17
    ms = PK11_DeriveWithFlags(pms, master_derive,
3433
17
                              params, key_derive,
3434
17
                              CKA_DERIVE, 0, keyFlags);
3435
17
    if (!ms) {
3436
0
        ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3437
0
        return SECFailure;
3438
0
    }
3439
3440
17
    if (pms_version && ss->opt.detectRollBack) {
3441
4
        SSL3ProtocolVersion client_version;
3442
4
        client_version = pms_version->major << 8 | pms_version->minor;
3443
3444
4
        if (IS_DTLS(ss)) {
3445
4
            client_version = dtls_DTLSVersionToTLSVersion(client_version);
3446
4
        }
3447
3448
4
        if (client_version != ss->clientHelloVersion) {
3449
            /* Destroy MS.  Version roll-back detected. */
3450
0
            PK11_FreeSymKey(ms);
3451
0
            ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3452
0
            return SECFailure;
3453
0
        }
3454
4
    }
3455
3456
17
    if (msp) {
3457
15
        *msp = ms;
3458
15
    } else {
3459
2
        PK11_FreeSymKey(ms);
3460
2
    }
3461
3462
17
    return SECSuccess;
3463
17
}
3464
3465
/*  Compute the ordinary (pre draft-ietf-tls-session-hash) master
3466
 ** secret and return it in |*msp|.
3467
 **
3468
 ** Called from: ssl3_ComputeMasterSecret
3469
 */
3470
static SECStatus
3471
ssl3_ComputeMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3472
                            PK11SymKey **msp)
3473
15
{
3474
15
    PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
3475
15
    PRBool isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3476
    /*
3477
     * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
3478
     * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
3479
     * data into a 48-byte value, and does not expect to return the version.
3480
     */
3481
15
    PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
3482
15
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh) ||
3483
15
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh_hybrid));
3484
15
    CK_MECHANISM_TYPE master_derive;
3485
15
    CK_MECHANISM_TYPE key_derive;
3486
15
    SECItem params;
3487
15
    CK_FLAGS keyFlags;
3488
15
    CK_VERSION pms_version;
3489
15
    CK_VERSION *pms_version_ptr = NULL;
3490
    /* master_params may be used as a CK_SSL3_MASTER_KEY_DERIVE_PARAMS */
3491
15
    CK_TLS12_MASTER_KEY_DERIVE_PARAMS master_params;
3492
15
    unsigned int master_params_len;
3493
3494
15
    if (isTLS12) {
3495
15
        if (isDH)
3496
11
            master_derive = CKM_TLS12_MASTER_KEY_DERIVE_DH;
3497
4
        else
3498
4
            master_derive = CKM_TLS12_MASTER_KEY_DERIVE;
3499
15
        key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3500
15
        keyFlags = CKF_SIGN | CKF_VERIFY;
3501
15
    } else if (isTLS) {
3502
0
        if (isDH)
3503
0
            master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
3504
0
        else
3505
0
            master_derive = CKM_TLS_MASTER_KEY_DERIVE;
3506
0
        key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3507
0
        keyFlags = CKF_SIGN | CKF_VERIFY;
3508
0
    } else {
3509
0
        if (isDH)
3510
0
            master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
3511
0
        else
3512
0
            master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
3513
0
        key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3514
0
        keyFlags = 0;
3515
0
    }
3516
3517
15
    if (!isDH) {
3518
4
        pms_version_ptr = &pms_version;
3519
4
    }
3520
3521
15
    master_params.pVersion = pms_version_ptr;
3522
15
    master_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
3523
15
    master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3524
15
    master_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
3525
15
    master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3526
15
    if (isTLS12) {
3527
15
        master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3528
15
        master_params_len = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS);
3529
15
    } else {
3530
        /* prfHashMechanism is not relevant with this PRF */
3531
0
        master_params_len = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS);
3532
0
    }
3533
3534
15
    params.data = (unsigned char *)&master_params;
3535
15
    params.len = master_params_len;
3536
3537
15
    return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3538
15
                                          pms_version_ptr, &params,
3539
15
                                          keyFlags, pms, msp);
3540
15
}
3541
3542
/* Compute the draft-ietf-tls-session-hash master
3543
** secret and return it in |*msp|.
3544
**
3545
** Called from: ssl3_ComputeMasterSecret
3546
*/
3547
static SECStatus
3548
tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3549
                                   PK11SymKey **msp)
3550
2
{
3551
2
    ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3552
2
    CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS extended_master_params;
3553
2
    SSL3Hashes hashes;
3554
    /*
3555
     * Determine whether to use the DH/ECDH or RSA derivation modes.
3556
     */
3557
    /*
3558
     * TODO(ekr@rtfm.com): Verify that the slot can handle this key expansion
3559
     * mode. Bug 1198298 */
3560
2
    PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
3561
2
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh) ||
3562
2
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh_hybrid));
3563
2
    CK_MECHANISM_TYPE master_derive;
3564
2
    CK_MECHANISM_TYPE key_derive;
3565
2
    SECItem params;
3566
2
    const CK_FLAGS keyFlags = CKF_SIGN | CKF_VERIFY;
3567
2
    CK_VERSION pms_version;
3568
2
    CK_VERSION *pms_version_ptr = NULL;
3569
2
    SECStatus rv;
3570
3571
2
    rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0);
3572
2
    if (rv != SECSuccess) {
3573
0
        PORT_Assert(0); /* Should never fail */
3574
0
        ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3575
0
        return SECFailure;
3576
0
    }
3577
3578
2
    if (isDH) {
3579
2
        master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH;
3580
2
    } else {
3581
0
        master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE;
3582
0
        pms_version_ptr = &pms_version;
3583
0
    }
3584
3585
2
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
3586
        /* TLS 1.2+ */
3587
2
        extended_master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3588
2
        key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3589
2
    } else {
3590
        /* TLS < 1.2 */
3591
0
        extended_master_params.prfHashMechanism = CKM_TLS_PRF;
3592
0
        key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3593
0
    }
3594
3595
2
    extended_master_params.pVersion = pms_version_ptr;
3596
2
    extended_master_params.pSessionHash = hashes.u.raw;
3597
2
    extended_master_params.ulSessionHashLen = hashes.len;
3598
3599
2
    params.data = (unsigned char *)&extended_master_params;
3600
2
    params.len = sizeof extended_master_params;
3601
3602
2
    return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3603
2
                                          pms_version_ptr, &params,
3604
2
                                          keyFlags, pms, msp);
3605
2
}
3606
3607
/* Wrapper method to compute the master secret and return it in |*msp|.
3608
**
3609
** Called from ssl3_ComputeMasterSecret
3610
*/
3611
static SECStatus
3612
ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
3613
                         PK11SymKey **msp)
3614
17
{
3615
17
    PORT_Assert(pms != NULL);
3616
17
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3617
3618
17
    if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
3619
2
        return tls_ComputeExtendedMasterSecretInt(ss, pms, msp);
3620
15
    } else {
3621
15
        return ssl3_ComputeMasterSecretInt(ss, pms, msp);
3622
15
    }
3623
17
}
3624
3625
/*
3626
 * Derive encryption and MAC Keys (and IVs) from master secret
3627
 * Sets a useful error code when returning SECFailure.
3628
 *
3629
 * Called only from ssl3_InitPendingCipherSpec(),
3630
 * which in turn is called from
3631
 *              ssl3_SendRSAClientKeyExchange    (for Full handshake)
3632
 *              ssl3_SendDHClientKeyExchange     (for Full handshake)
3633
 *              ssl3_HandleClientKeyExchange    (for Full handshake)
3634
 *              ssl3_HandleServerHello          (for session restart)
3635
 *              ssl3_HandleClientHello          (for session restart)
3636
 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
3637
 * ssl3_InitPendingCipherSpec does that.
3638
 *
3639
 */
3640
static SECStatus
3641
ssl3_DeriveConnectionKeys(sslSocket *ss, PK11SymKey *masterSecret)
3642
15
{
3643
15
    ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3644
15
    ssl3CipherSpec *prSpec = ss->ssl3.prSpec;
3645
15
    ssl3CipherSpec *clientSpec;
3646
15
    ssl3CipherSpec *serverSpec;
3647
15
    PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
3648
15
    PRBool isTLS12 =
3649
15
        (PRBool)(isTLS && ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3650
15
    const ssl3BulkCipherDef *cipher_def = pwSpec->cipherDef;
3651
15
    PK11SlotInfo *slot = NULL;
3652
15
    PK11SymKey *derivedKeyHandle = NULL;
3653
15
    void *pwArg = ss->pkcs11PinArg;
3654
15
    int keySize;
3655
15
    CK_TLS12_KEY_MAT_PARAMS key_material_params; /* may be used as a
3656
                                                  * CK_SSL3_KEY_MAT_PARAMS */
3657
15
    unsigned int key_material_params_len;
3658
15
    CK_SSL3_KEY_MAT_OUT returnedKeys;
3659
15
    CK_MECHANISM_TYPE key_derive;
3660
15
    CK_MECHANISM_TYPE bulk_mechanism;
3661
15
    SSLCipherAlgorithm calg;
3662
15
    SECItem params;
3663
15
    PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == ssl_calg_null);
3664
3665
15
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3666
15
    PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3667
15
    PORT_Assert(masterSecret);
3668
3669
    /* These functions operate in terms of who is writing specs. */
3670
15
    if (ss->sec.isServer) {
3671
15
        clientSpec = prSpec;
3672
15
        serverSpec = pwSpec;
3673
15
    } else {
3674
0
        clientSpec = pwSpec;
3675
0
        serverSpec = prSpec;
3676
0
    }
3677
3678
    /*
3679
     * generate the key material
3680
     */
3681
15
    if (cipher_def->type == type_block &&
3682
15
        ss->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
3683
        /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
3684
4
        key_material_params.ulIVSizeInBits = 0;
3685
4
        PORT_Memset(clientSpec->keyMaterial.iv, 0, cipher_def->iv_size);
3686
4
        PORT_Memset(serverSpec->keyMaterial.iv, 0, cipher_def->iv_size);
3687
4
    }
3688
3689
15
    key_material_params.bIsExport = PR_FALSE;
3690
15
    key_material_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
3691
15
    key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3692
15
    key_material_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
3693
15
    key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3694
15
    key_material_params.pReturnedKeyMaterial = &returnedKeys;
3695
3696
15
    if (skipKeysAndIVs) {
3697
0
        keySize = 0;
3698
0
        returnedKeys.pIVClient = NULL;
3699
0
        returnedKeys.pIVServer = NULL;
3700
0
        key_material_params.ulKeySizeInBits = 0;
3701
0
        key_material_params.ulIVSizeInBits = 0;
3702
15
    } else {
3703
15
        keySize = cipher_def->key_size;
3704
15
        returnedKeys.pIVClient = clientSpec->keyMaterial.iv;
3705
15
        returnedKeys.pIVServer = serverSpec->keyMaterial.iv;
3706
15
        key_material_params.ulKeySizeInBits = cipher_def->secret_key_size * BPB;
3707
15
        key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB;
3708
15
    }
3709
15
    key_material_params.ulMacSizeInBits = pwSpec->macDef->mac_size * BPB;
3710
3711
15
    calg = cipher_def->calg;
3712
15
    bulk_mechanism = ssl3_Alg2Mech(calg);
3713
3714
15
    if (isTLS12) {
3715
15
        key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3716
15
        key_material_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3717
15
        key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS);
3718
15
    } else if (isTLS) {
3719
0
        key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3720
0
        key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
3721
0
    } else {
3722
0
        key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3723
0
        key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
3724
0
    }
3725
3726
15
    params.data = (unsigned char *)&key_material_params;
3727
15
    params.len = key_material_params_len;
3728
3729
    /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
3730
     * DERIVE by DEFAULT */
3731
15
    derivedKeyHandle = PK11_Derive(masterSecret, key_derive, &params,
3732
15
                                   bulk_mechanism, CKA_ENCRYPT, keySize);
3733
15
    if (!derivedKeyHandle) {
3734
0
        ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3735
0
        return SECFailure;
3736
0
    }
3737
    /* we really should use the actual mac'ing mechanism here, but we
3738
     * don't because these types are used to map keytype anyway and both
3739
     * mac's map to the same keytype.
3740
     */
3741
15
    slot = PK11_GetSlotFromKey(derivedKeyHandle);
3742
3743
15
    PK11_FreeSlot(slot); /* slot is held until the key is freed */
3744
15
    clientSpec->keyMaterial.macKey =
3745
15
        PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3746
15
                              CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret,
3747
15
                              PR_TRUE, pwArg);
3748
15
    if (clientSpec->keyMaterial.macKey == NULL) {
3749
0
        goto loser; /* loser sets err */
3750
0
    }
3751
15
    serverSpec->keyMaterial.macKey =
3752
15
        PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3753
15
                              CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret,
3754
15
                              PR_TRUE, pwArg);
3755
15
    if (serverSpec->keyMaterial.macKey == NULL) {
3756
0
        goto loser; /* loser sets err */
3757
0
    }
3758
15
    if (!skipKeysAndIVs) {
3759
15
        clientSpec->keyMaterial.key =
3760
15
            PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3761
15
                                  bulk_mechanism, returnedKeys.hClientKey,
3762
15
                                  PR_TRUE, pwArg);
3763
15
        if (clientSpec->keyMaterial.key == NULL) {
3764
0
            goto loser; /* loser sets err */
3765
0
        }
3766
15
        serverSpec->keyMaterial.key =
3767
15
            PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3768
15
                                  bulk_mechanism, returnedKeys.hServerKey,
3769
15
                                  PR_TRUE, pwArg);
3770
15
        if (serverSpec->keyMaterial.key == NULL) {
3771
0
            goto loser; /* loser sets err */
3772
0
        }
3773
15
    }
3774
15
    PK11_FreeSymKey(derivedKeyHandle);
3775
15
    return SECSuccess;
3776
3777
0
loser:
3778
0
    PK11_FreeSymKey(derivedKeyHandle);
3779
0
    ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3780
0
    return SECFailure;
3781
15
}
3782
3783
void
3784
ssl3_CoalesceEchHandshakeHashes(sslSocket *ss)
3785
0
{
3786
    /* |sha| contains the CHOuter transcript, which is the singular
3787
     * transcript if not doing ECH. If the server responded with 1.2,
3788
     * contexts are not yet initialized. */
3789
0
    if (ss->ssl3.hs.echAccepted) {
3790
0
        if (ss->ssl3.hs.sha) {
3791
0
            PORT_Assert(ss->ssl3.hs.shaEchInner);
3792
0
            PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
3793
0
            ss->ssl3.hs.sha = ss->ssl3.hs.shaEchInner;
3794
0
            ss->ssl3.hs.shaEchInner = NULL;
3795
0
        }
3796
0
    } else {
3797
0
        if (ss->ssl3.hs.shaEchInner) {
3798
0
            PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
3799
0
            ss->ssl3.hs.shaEchInner = NULL;
3800
0
        }
3801
0
    }
3802
0
}
3803
3804
/* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
3805
 * buffered messages in ss->ssl3.hs.messages. Called from
3806
 * ssl3_NegotiateCipherSuite(), tls13_HandleClientHelloPart2(),
3807
 * and ssl3_HandleServerHello. */
3808
SECStatus
3809
ssl3_InitHandshakeHashes(sslSocket *ss)
3810
6.06k
{
3811
6.06k
    SSL_TRC(30, ("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
3812
3813
6.06k
    PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
3814
6.06k
    if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
3815
6.06k
        ss->ssl3.hs.hashType = handshake_hash_record;
3816
6.06k
    } else {
3817
0
        PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha);
3818
        /*
3819
         * note: We should probably lookup an SSL3 slot for these
3820
         * handshake hashes in hopes that we wind up with the same slots
3821
         * that the master secret will wind up in ...
3822
         */
3823
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
3824
            /* determine the hash from the prf */
3825
0
            const SECOidData *hash_oid =
3826
0
                SECOID_FindOIDByMechanism(ssl3_GetPrfHashMechanism(ss));
3827
3828
            /* Get the PKCS #11 mechanism for the Hash from the cipher suite (prf_hash)
3829
             * Convert that to the OidTag. We can then use that OidTag to create our
3830
             * PK11Context */
3831
0
            PORT_Assert(hash_oid != NULL);
3832
0
            if (hash_oid == NULL) {
3833
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3834
0
                return SECFailure;
3835
0
            }
3836
3837
0
            ss->ssl3.hs.sha = PK11_CreateDigestContext(hash_oid->offset);
3838
0
            if (ss->ssl3.hs.sha == NULL) {
3839
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3840
0
                return SECFailure;
3841
0
            }
3842
0
            ss->ssl3.hs.hashType = handshake_hash_single;
3843
0
            if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3844
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3845
0
                return SECFailure;
3846
0
            }
3847
3848
            /* Transcript hash used on ECH client. */
3849
0
            if (!ss->sec.isServer && ss->ssl3.hs.echHpkeCtx) {
3850
0
                ss->ssl3.hs.shaEchInner = PK11_CreateDigestContext(hash_oid->offset);
3851
0
                if (ss->ssl3.hs.shaEchInner == NULL) {
3852
0
                    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3853
0
                    return SECFailure;
3854
0
                }
3855
0
                if (PK11_DigestBegin(ss->ssl3.hs.shaEchInner) != SECSuccess) {
3856
0
                    ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3857
0
                    return SECFailure;
3858
0
                }
3859
0
            }
3860
0
        } else {
3861
            /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
3862
             * created successfully. */
3863
0
            ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
3864
0
            if (ss->ssl3.hs.md5 == NULL) {
3865
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3866
0
                return SECFailure;
3867
0
            }
3868
0
            ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
3869
0
            if (ss->ssl3.hs.sha == NULL) {
3870
0
                PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
3871
0
                ss->ssl3.hs.md5 = NULL;
3872
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3873
0
                return SECFailure;
3874
0
            }
3875
0
            ss->ssl3.hs.hashType = handshake_hash_combo;
3876
3877
0
            if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
3878
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3879
0
                return SECFailure;
3880
0
            }
3881
0
            if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3882
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3883
0
                return SECFailure;
3884
0
            }
3885
0
        }
3886
0
    }
3887
3888
6.06k
    if (ss->ssl3.hs.hashType != handshake_hash_record &&
3889
6.06k
        ss->ssl3.hs.messages.len > 0) {
3890
        /* When doing ECH, ssl3_UpdateHandshakeHashes will store outer messages
3891
         * into the both the outer and inner transcripts.
3892
         * ssl3_UpdateDefaultHandshakeHashes uses the default context which is
3893
         * the outer when doing client ECH. For ECH shared-mode or backend
3894
         * servers only the hs.messages buffer is used. */
3895
0
        if (ssl3_UpdateDefaultHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
3896
0
                                              ss->ssl3.hs.messages.len) != SECSuccess) {
3897
0
            return SECFailure;
3898
0
        }
3899
        /* When doing ECH, deriving the accept_confirmation value requires all
3900
         * messages up to and including the ServerHello
3901
         * (see draft-ietf-tls-esni-14, Section 7.2).
3902
         *
3903
         * Don't free the transcript buffer until confirmation calculation. */
3904
0
        if (!ss->ssl3.hs.echHpkeCtx && !ss->opt.enableTls13BackendEch) {
3905
0
            sslBuffer_Clear(&ss->ssl3.hs.messages);
3906
0
        }
3907
0
    }
3908
6.06k
    if (ss->ssl3.hs.shaEchInner &&
3909
6.06k
        ss->ssl3.hs.echInnerMessages.len > 0) {
3910
0
        if (PK11_DigestOp(ss->ssl3.hs.shaEchInner, ss->ssl3.hs.echInnerMessages.buf,
3911
0
                          ss->ssl3.hs.echInnerMessages.len) != SECSuccess) {
3912
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3913
0
            return SECFailure;
3914
0
        }
3915
0
        if (!ss->ssl3.hs.echHpkeCtx) {
3916
0
            sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
3917
0
        }
3918
0
    }
3919
3920
6.06k
    return SECSuccess;
3921
6.06k
}
3922
3923
void
3924
ssl3_RestartHandshakeHashes(sslSocket *ss)
3925
7.50k
{
3926
7.50k
    SSL_TRC(30, ("%d: SSL3[%d]: reset handshake hashes",
3927
7.50k
                 SSL_GETPID(), ss->fd));
3928
7.50k
    ss->ssl3.hs.hashType = handshake_hash_unknown;
3929
7.50k
    ss->ssl3.hs.messages.len = 0;
3930
7.50k
    ss->ssl3.hs.echInnerMessages.len = 0;
3931
7.50k
    if (ss->ssl3.hs.md5) {
3932
0
        PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
3933
0
        ss->ssl3.hs.md5 = NULL;
3934
0
    }
3935
7.50k
    if (ss->ssl3.hs.sha) {
3936
0
        PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
3937
0
        ss->ssl3.hs.sha = NULL;
3938
0
    }
3939
7.50k
    if (ss->ssl3.hs.shaEchInner) {
3940
0
        PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
3941
0
        ss->ssl3.hs.shaEchInner = NULL;
3942
0
    }
3943
7.50k
    if (ss->ssl3.hs.shaPostHandshake) {
3944
0
        PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
3945
0
        ss->ssl3.hs.shaPostHandshake = NULL;
3946
0
    }
3947
7.50k
}
3948
3949
/* Add the provided bytes to the handshake hash context. When doing
3950
 * TLS 1.3 ECH, |target| may be provided to specify only the inner/outer
3951
 * transcript, else the input is added to both contexts. This happens
3952
 * only on the client. On the server, only the default context is used. */
3953
SECStatus
3954
ssl3_UpdateHandshakeHashesInt(sslSocket *ss, const unsigned char *b,
3955
                              unsigned int l, sslBuffer *target)
3956
238k
{
3957
3958
238k
    SECStatus rv = SECSuccess;
3959
238k
    PRBool explicit = (target != NULL);
3960
238k
    PRBool appendToEchInner = !ss->sec.isServer &&
3961
238k
                              ss->ssl3.hs.echHpkeCtx &&
3962
238k
                              !explicit;
3963
238k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3964
238k
    PORT_Assert(target != &ss->ssl3.hs.echInnerMessages ||
3965
238k
                !ss->sec.isServer);
3966
3967
238k
    if (target == NULL) {
3968
        /* Default context. */
3969
238k
        target = &ss->ssl3.hs.messages;
3970
238k
    }
3971
    /* With TLS 1.3, and versions TLS.1.1 and older, we keep the hash(es)
3972
     * always up to date. However, we must initially buffer the handshake
3973
     * messages, until we know what to do.
3974
     * If ss->ssl3.hs.hashType != handshake_hash_unknown,
3975
     * it means we know what to do. We calculate (hash our input),
3976
     * and we stop appending to the buffer.
3977
     *
3978
     * With TLS 1.2, we always append all handshake messages,
3979
     * and never update the hash, because the hash function we must use for
3980
     * certificate_verify might be different from the hash function we use
3981
     * when signing other handshake hashes. */
3982
238k
    if (ss->ssl3.hs.hashType == handshake_hash_unknown ||
3983
238k
        ss->ssl3.hs.hashType == handshake_hash_record) {
3984
238k
        rv = sslBuffer_Append(target, b, l);
3985
238k
        if (rv != SECSuccess) {
3986
0
            return SECFailure;
3987
0
        }
3988
238k
        if (appendToEchInner) {
3989
0
            return sslBuffer_Append(&ss->ssl3.hs.echInnerMessages, b, l);
3990
0
        }
3991
238k
        return SECSuccess;
3992
238k
    }
3993
3994
0
    PRINT_BUF(90, (ss, "handshake hash input:", b, l));
3995
3996
0
    if (ss->ssl3.hs.hashType == handshake_hash_single) {
3997
0
        PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
3998
0
        if (target == &ss->ssl3.hs.messages) {
3999
0
            rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
4000
0
            if (rv != SECSuccess) {
4001
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4002
0
                return rv;
4003
0
            }
4004
0
        }
4005
0
        if (ss->ssl3.hs.shaEchInner &&
4006
0
            (target == &ss->ssl3.hs.echInnerMessages || !explicit)) {
4007
0
            rv = PK11_DigestOp(ss->ssl3.hs.shaEchInner, b, l);
4008
0
            if (rv != SECSuccess) {
4009
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4010
0
                return rv;
4011
0
            }
4012
0
        }
4013
0
    } else if (ss->ssl3.hs.hashType == handshake_hash_combo) {
4014
0
        rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
4015
0
        if (rv != SECSuccess) {
4016
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4017
0
            return rv;
4018
0
        }
4019
0
        rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
4020
0
        if (rv != SECSuccess) {
4021
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4022
0
            return rv;
4023
0
        }
4024
0
    }
4025
0
    return rv;
4026
0
}
4027
4028
static SECStatus
4029
ssl3_UpdateDefaultHandshakeHashes(sslSocket *ss, const unsigned char *b,
4030
                                  unsigned int l)
4031
0
{
4032
0
    return ssl3_UpdateHandshakeHashesInt(ss, b, l,
4033
0
                                         &ss->ssl3.hs.messages);
4034
0
}
4035
4036
static SECStatus
4037
ssl3_UpdateInnerHandshakeHashes(sslSocket *ss, const unsigned char *b,
4038
                                unsigned int l)
4039
0
{
4040
0
    return ssl3_UpdateHandshakeHashesInt(ss, b, l,
4041
0
                                         &ss->ssl3.hs.echInnerMessages);
4042
0
}
4043
4044
/*
4045
 * Handshake messages
4046
 */
4047
/* Called from  ssl3_InitHandshakeHashes()
4048
**      ssl3_AppendHandshake()
4049
**      ssl3_HandleV2ClientHello()
4050
**      ssl3_HandleHandshakeMessage()
4051
** Caller must hold the ssl3Handshake lock.
4052
*/
4053
SECStatus
4054
ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l)
4055
238k
{
4056
238k
    return ssl3_UpdateHandshakeHashesInt(ss, b, l, NULL);
4057
238k
}
4058
4059
SECStatus
4060
ssl3_UpdatePostHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l)
4061
0
{
4062
0
    SECStatus rv = SECSuccess;
4063
4064
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4065
4066
0
    PRINT_BUF(90, (ss, "post handshake hash input:", b, l));
4067
4068
0
    PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single);
4069
0
    PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
4070
0
    rv = PK11_DigestOp(ss->ssl3.hs.shaPostHandshake, b, l);
4071
0
    if (rv != SECSuccess) {
4072
0
        PORT_SetError(SSL_ERROR_DIGEST_FAILURE);
4073
0
    }
4074
0
    return rv;
4075
0
}
4076
4077
/* The next two functions serve to append the handshake header.
4078
   The first one additionally writes to seqNumberBuffer
4079
   the sequence number of the message we are generating.
4080
   This function is used when generating the keyUpdate message in dtls13_enqueueKeyUpdateMessage.
4081
*/
4082
SECStatus
4083
ssl3_AppendHandshakeHeaderAndStashSeqNum(sslSocket *ss, SSLHandshakeType t, PRUint32 length, PRUint64 *sendMessageSeqOut)
4084
26.6k
{
4085
26.6k
    PORT_Assert(t != ssl_hs_client_hello);
4086
26.6k
    SECStatus rv;
4087
4088
    /* If we already have a message in place, we need to enqueue it.
4089
     * This empties the buffer. This is a convenient place to call
4090
     * dtls_StageHandshakeMessage to mark the message boundary.
4091
     */
4092
26.6k
    if (IS_DTLS(ss)) {
4093
26.6k
        rv = dtls_StageHandshakeMessage(ss);
4094
26.6k
        if (rv != SECSuccess) {
4095
0
            return rv;
4096
0
        }
4097
26.6k
    }
4098
4099
26.6k
    SSL_TRC(30, ("%d: SSL3[%d]: append handshake header: type %s",
4100
26.6k
                 SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
4101
4102
26.6k
    rv = ssl3_AppendHandshakeNumber(ss, t, 1);
4103
26.6k
    if (rv != SECSuccess) {
4104
0
        return rv; /* error code set by AppendHandshake, if applicable. */
4105
0
    }
4106
26.6k
    rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4107
26.6k
    if (rv != SECSuccess) {
4108
0
        return rv; /* error code set by AppendHandshake, if applicable. */
4109
0
    }
4110
4111
26.6k
    if (IS_DTLS(ss)) {
4112
        /* RFC 9147. 5.2.  DTLS Handshake Message Format.
4113
         * In DTLS 1.3, the message transcript is computed over the original TLS
4114
         * 1.3-style Handshake messages without the message_seq,
4115
         * fragment_offset, and fragment_length values.  Note that this is a
4116
         * change from DTLS 1.2 where those values were included in the transcript. */
4117
26.6k
        PRBool suppressHash = ss->version == SSL_LIBRARY_VERSION_TLS_1_3 ? PR_TRUE : PR_FALSE;
4118
4119
        /* Note that we make an unfragmented message here. We fragment in the
4120
         * transmission code, if necessary */
4121
26.6k
        rv = ssl3_AppendHandshakeNumberSuppressHash(ss, ss->ssl3.hs.sendMessageSeq, 2, suppressHash);
4122
26.6k
        if (rv != SECSuccess) {
4123
0
            return rv; /* error code set by AppendHandshake, if applicable. */
4124
0
        }
4125
        /* In case if we provide a buffer for the sequence message,
4126
        we write down sendMessageSeq to the buffer. */
4127
26.6k
        if (sendMessageSeqOut != NULL) {
4128
0
            *sendMessageSeqOut = ss->ssl3.hs.sendMessageSeq;
4129
0
        }
4130
26.6k
        ss->ssl3.hs.sendMessageSeq++;
4131
4132
        /* 0 is the fragment offset, because it's not fragmented yet */
4133
26.6k
        rv = ssl3_AppendHandshakeNumberSuppressHash(ss, 0, 3, suppressHash);
4134
26.6k
        if (rv != SECSuccess) {
4135
0
            return rv; /* error code set by AppendHandshake, if applicable. */
4136
0
        }
4137
4138
        /* Fragment length -- set to the packet length because not fragmented */
4139
26.6k
        rv = ssl3_AppendHandshakeNumberSuppressHash(ss, length, 3, suppressHash);
4140
26.6k
        if (rv != SECSuccess) {
4141
0
            return rv; /* error code set by AppendHandshake, if applicable. */
4142
0
        }
4143
26.6k
    }
4144
4145
26.6k
    return rv; /* error code set by AppendHandshake, if applicable. */
4146
26.6k
}
4147
4148
/* The function calls the ssl3_AppendHandshakeHeaderAndStashSeqNum implemented above.
4149
   As in the majority of the cases we do not need the last parameter,
4150
   we separate out this function. */
4151
SECStatus
4152
ssl3_AppendHandshakeHeader(sslSocket *ss, SSLHandshakeType t, PRUint32 length)
4153
26.6k
{
4154
26.6k
    return ssl3_AppendHandshakeHeaderAndStashSeqNum(ss, t, length, NULL);
4155
26.6k
}
4156
4157
/**************************************************************************
4158
 * Consume Handshake functions.
4159
 *
4160
 * All data used in these functions is protected by two locks,
4161
 * the RecvBufLock and the SSL3HandshakeLock
4162
 **************************************************************************/
4163
4164
/* Read up the next "bytes" number of bytes from the (decrypted) input
4165
 * stream "b" (which is *length bytes long). Copy them into buffer "v".
4166
 * Reduces *length by bytes.  Advances *b by bytes.
4167
 *
4168
 * If this function returns SECFailure, it has already sent an alert,
4169
 * and has set a generic error code.  The caller should probably
4170
 * override the generic error code by setting another.
4171
 */
4172
SECStatus
4173
ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRUint32 bytes, PRUint8 **b,
4174
                      PRUint32 *length)
4175
7.50k
{
4176
7.50k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4177
7.50k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4178
4179
7.50k
    if ((PRUint32)bytes > *length) {
4180
28
        return ssl3_DecodeError(ss);
4181
28
    }
4182
7.47k
    PORT_Memcpy(v, *b, bytes);
4183
7.47k
    PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4184
7.47k
    *b += bytes;
4185
7.47k
    *length -= bytes;
4186
7.47k
    return SECSuccess;
4187
7.50k
}
4188
4189
/* Read up the next "bytes" number of bytes from the (decrypted) input
4190
 * stream "b" (which is *length bytes long), and interpret them as an
4191
 * integer in network byte order.  Sets *num to the received value.
4192
 * Reduces *length by bytes.  Advances *b by bytes.
4193
 *
4194
 * On error, an alert has been sent, and a generic error code has been set.
4195
 */
4196
SECStatus
4197
ssl3_ConsumeHandshakeNumber64(sslSocket *ss, PRUint64 *num, PRUint32 bytes,
4198
                              PRUint8 **b, PRUint32 *length)
4199
87.4k
{
4200
87.4k
    PRUint8 *buf = *b;
4201
87.4k
    PRUint32 i;
4202
4203
87.4k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4204
87.4k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4205
4206
87.4k
    *num = 0;
4207
87.4k
    if (bytes > sizeof(*num)) {
4208
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4209
0
        return SECFailure;
4210
0
    }
4211
4212
87.4k
    if (bytes > *length) {
4213
18
        return ssl3_DecodeError(ss);
4214
18
    }
4215
87.4k
    PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4216
4217
239k
    for (i = 0; i < bytes; i++) {
4218
152k
        *num = (*num << 8) + buf[i];
4219
152k
    }
4220
87.4k
    *b += bytes;
4221
87.4k
    *length -= bytes;
4222
87.4k
    return SECSuccess;
4223
87.4k
}
4224
4225
SECStatus
4226
ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRUint32 *num, PRUint32 bytes,
4227
                            PRUint8 **b, PRUint32 *length)
4228
87.4k
{
4229
87.4k
    PRUint64 num64;
4230
87.4k
    SECStatus rv;
4231
4232
87.4k
    PORT_Assert(bytes <= sizeof(*num));
4233
87.4k
    if (bytes > sizeof(*num)) {
4234
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4235
0
        return SECFailure;
4236
0
    }
4237
87.4k
    rv = ssl3_ConsumeHandshakeNumber64(ss, &num64, bytes, b, length);
4238
87.4k
    if (rv != SECSuccess) {
4239
18
        return SECFailure;
4240
18
    }
4241
87.4k
    *num = num64 & 0xffffffff;
4242
87.4k
    return SECSuccess;
4243
87.4k
}
4244
4245
/* Read in two values from the incoming decrypted byte stream "b", which is
4246
 * *length bytes long.  The first value is a number whose size is "bytes"
4247
 * bytes long.  The second value is a byte-string whose size is the value
4248
 * of the first number received.  The latter byte-string, and its length,
4249
 * is returned in the SECItem i.
4250
 *
4251
 * Returns SECFailure (-1) on failure.
4252
 * On error, an alert has been sent, and a generic error code has been set.
4253
 *
4254
 * RADICAL CHANGE for NSS 3.11.  All callers of this function make copies
4255
 * of the data returned in the SECItem *i, so making a copy of it here
4256
 * is simply wasteful.  So, This function now just sets SECItem *i to
4257
 * point to the values in the buffer **b.
4258
 */
4259
SECStatus
4260
ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRUint32 bytes,
4261
                              PRUint8 **b, PRUint32 *length)
4262
42.3k
{
4263
42.3k
    PRUint32 count;
4264
42.3k
    SECStatus rv;
4265
4266
42.3k
    PORT_Assert(bytes <= 3);
4267
42.3k
    i->len = 0;
4268
42.3k
    i->data = NULL;
4269
42.3k
    i->type = siBuffer;
4270
42.3k
    rv = ssl3_ConsumeHandshakeNumber(ss, &count, bytes, b, length);
4271
42.3k
    if (rv != SECSuccess) {
4272
9
        return SECFailure;
4273
9
    }
4274
42.3k
    if (count > 0) {
4275
33.1k
        if (count > *length) {
4276
51
            return ssl3_DecodeError(ss);
4277
51
        }
4278
33.1k
        i->data = *b;
4279
33.1k
        i->len = count;
4280
33.1k
        *b += count;
4281
33.1k
        *length -= count;
4282
33.1k
    }
4283
42.3k
    return SECSuccess;
4284
42.3k
}
4285
4286
/* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
4287
 * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
4288
 *
4289
 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4290
SECOidTag
4291
ssl3_HashTypeToOID(SSLHashType hashType)
4292
233k
{
4293
233k
    switch (hashType) {
4294
21.0k
        case ssl_hash_sha1:
4295
21.0k
            return SEC_OID_SHA1;
4296
181k
        case ssl_hash_sha256:
4297
181k
            return SEC_OID_SHA256;
4298
15.7k
        case ssl_hash_sha384:
4299
15.7k
            return SEC_OID_SHA384;
4300
15.6k
        case ssl_hash_sha512:
4301
15.6k
            return SEC_OID_SHA512;
4302
0
        default:
4303
0
            break;
4304
233k
    }
4305
0
    return SEC_OID_UNKNOWN;
4306
233k
}
4307
4308
SECOidTag
4309
ssl3_AuthTypeToOID(SSLAuthType authType)
4310
92.0k
{
4311
92.0k
    switch (authType) {
4312
16.0k
        case ssl_auth_rsa_sign:
4313
16.0k
            return SEC_OID_PKCS1_RSA_ENCRYPTION;
4314
0
        case ssl_auth_rsa_pss:
4315
0
            return SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
4316
61.0k
        case ssl_auth_ecdsa:
4317
61.0k
            return SEC_OID_ANSIX962_EC_PUBLIC_KEY;
4318
14.9k
        case ssl_auth_dsa:
4319
14.9k
            return SEC_OID_ANSIX9_DSA_SIGNATURE;
4320
0
        default:
4321
0
            break;
4322
92.0k
    }
4323
    /* shouldn't ever get there */
4324
0
    PORT_Assert(0);
4325
0
    return SEC_OID_UNKNOWN;
4326
92.0k
}
4327
4328
SSLHashType
4329
ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme)
4330
229k
{
4331
229k
    switch (scheme) {
4332
8.32k
        case ssl_sig_rsa_pkcs1_sha1:
4333
12.0k
        case ssl_sig_dsa_sha1:
4334
16.3k
        case ssl_sig_ecdsa_sha1:
4335
16.3k
            return ssl_hash_sha1;
4336
3.90k
        case ssl_sig_rsa_pkcs1_sha256:
4337
51.9k
        case ssl_sig_ecdsa_secp256r1_sha256:
4338
177k
        case ssl_sig_rsa_pss_rsae_sha256:
4339
178k
        case ssl_sig_rsa_pss_pss_sha256:
4340
181k
        case ssl_sig_dsa_sha256:
4341
181k
            return ssl_hash_sha256;
4342
3.95k
        case ssl_sig_rsa_pkcs1_sha384:
4343
8.02k
        case ssl_sig_ecdsa_secp384r1_sha384:
4344
12.2k
        case ssl_sig_rsa_pss_rsae_sha384:
4345
12.3k
        case ssl_sig_rsa_pss_pss_sha384:
4346
15.9k
        case ssl_sig_dsa_sha384:
4347
15.9k
            return ssl_hash_sha384;
4348
3.89k
        case ssl_sig_rsa_pkcs1_sha512:
4349
7.94k
        case ssl_sig_ecdsa_secp521r1_sha512:
4350
12.1k
        case ssl_sig_rsa_pss_rsae_sha512:
4351
12.1k
        case ssl_sig_rsa_pss_pss_sha512:
4352
15.8k
        case ssl_sig_dsa_sha512:
4353
15.8k
            return ssl_hash_sha512;
4354
0
        case ssl_sig_rsa_pkcs1_sha1md5:
4355
0
            return ssl_hash_none; /* Special for TLS 1.0/1.1. */
4356
0
        case ssl_sig_none:
4357
0
        case ssl_sig_ed25519:
4358
0
        case ssl_sig_ed448:
4359
0
            break;
4360
229k
    }
4361
0
    PORT_Assert(0);
4362
0
    return ssl_hash_none;
4363
229k
}
4364
4365
static PRBool
4366
ssl_SignatureSchemeMatchesSpkiOid(SSLSignatureScheme scheme, SECOidTag spkiOid)
4367
1.82k
{
4368
1.82k
    SECOidTag authOid = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme));
4369
4370
1.82k
    if (spkiOid == authOid) {
4371
770
        return PR_TRUE;
4372
770
    }
4373
1.05k
    if ((authOid == SEC_OID_PKCS1_RSA_ENCRYPTION) &&
4374
1.05k
        (spkiOid == SEC_OID_X500_RSA_ENCRYPTION)) {
4375
0
        return PR_TRUE;
4376
0
    }
4377
1.05k
    return PR_FALSE;
4378
1.05k
}
4379
4380
/* Validate that the signature scheme works for the given key type. */
4381
PRBool
4382
ssl_SignatureSchemeValid(SSLSignatureScheme scheme, SECOidTag spkiOid,
4383
                         PRBool isTls13)
4384
7.55k
{
4385
7.55k
    if (!ssl_IsSupportedSignatureScheme(scheme)) {
4386
2.50k
        return PR_FALSE;
4387
2.50k
    }
4388
    /* if we are purposefully passed SEC_OID_UNKNOWN, it means
4389
     * we not checking the scheme against a potential key, so skip
4390
     * the call */
4391
5.04k
    if ((spkiOid != SEC_OID_UNKNOWN) &&
4392
5.04k
        !ssl_SignatureSchemeMatchesSpkiOid(scheme, spkiOid)) {
4393
1.05k
        return PR_FALSE;
4394
1.05k
    }
4395
3.99k
    if (isTls13) {
4396
0
        if (ssl_SignatureSchemeToHashType(scheme) == ssl_hash_sha1) {
4397
0
            return PR_FALSE;
4398
0
        }
4399
0
        if (ssl_IsRsaPkcs1SignatureScheme(scheme)) {
4400
0
            return PR_FALSE;
4401
0
        }
4402
0
        if (ssl_IsDsaSignatureScheme(scheme)) {
4403
0
            return PR_FALSE;
4404
0
        }
4405
        /* With TLS 1.3, EC keys should have been selected based on calling
4406
         * ssl_SignatureSchemeFromSpki(), reject them otherwise. */
4407
0
        return spkiOid != SEC_OID_ANSIX962_EC_PUBLIC_KEY;
4408
0
    }
4409
3.99k
    return PR_TRUE;
4410
3.99k
}
4411
4412
static SECStatus
4413
ssl_SignatureSchemeFromPssSpki(const CERTSubjectPublicKeyInfo *spki,
4414
                               SSLSignatureScheme *scheme)
4415
0
{
4416
0
    SECKEYRSAPSSParams pssParam = { 0 };
4417
0
    PORTCheapArenaPool arena;
4418
0
    SECStatus rv;
4419
4420
    /* The key doesn't have parameters, boo. */
4421
0
    if (!spki->algorithm.parameters.len) {
4422
0
        *scheme = ssl_sig_none;
4423
0
        return SECSuccess;
4424
0
    }
4425
4426
0
    PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE);
4427
0
    rv = SEC_QuickDERDecodeItem(&arena.arena, &pssParam,
4428
0
                                SEC_ASN1_GET(SECKEY_RSAPSSParamsTemplate),
4429
0
                                &spki->algorithm.parameters);
4430
0
    if (rv != SECSuccess) {
4431
0
        goto loser;
4432
0
    }
4433
    /* Not having hashAlg means SHA-1 and we don't accept that. */
4434
0
    if (!pssParam.hashAlg) {
4435
0
        goto loser;
4436
0
    }
4437
0
    switch (SECOID_GetAlgorithmTag(pssParam.hashAlg)) {
4438
0
        case SEC_OID_SHA256:
4439
0
            *scheme = ssl_sig_rsa_pss_pss_sha256;
4440
0
            break;
4441
0
        case SEC_OID_SHA384:
4442
0
            *scheme = ssl_sig_rsa_pss_pss_sha384;
4443
0
            break;
4444
0
        case SEC_OID_SHA512:
4445
0
            *scheme = ssl_sig_rsa_pss_pss_sha512;
4446
0
            break;
4447
0
        default:
4448
0
            goto loser;
4449
0
    }
4450
4451
0
    PORT_DestroyCheapArena(&arena);
4452
0
    return SECSuccess;
4453
4454
0
loser:
4455
0
    PORT_DestroyCheapArena(&arena);
4456
0
    PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4457
0
    return SECFailure;
4458
0
}
4459
4460
static SECStatus
4461
ssl_SignatureSchemeFromEcSpki(const CERTSubjectPublicKeyInfo *spki,
4462
                              SSLSignatureScheme *scheme)
4463
0
{
4464
0
    const sslNamedGroupDef *group;
4465
0
    SECKEYPublicKey *key;
4466
4467
0
    key = SECKEY_ExtractPublicKey(spki);
4468
0
    if (!key) {
4469
0
        PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4470
0
        return SECFailure;
4471
0
    }
4472
0
    group = ssl_ECPubKey2NamedGroup(key);
4473
0
    SECKEY_DestroyPublicKey(key);
4474
0
    if (!group) {
4475
0
        PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4476
0
        return SECFailure;
4477
0
    }
4478
0
    switch (group->name) {
4479
0
        case ssl_grp_ec_secp256r1:
4480
0
            *scheme = ssl_sig_ecdsa_secp256r1_sha256;
4481
0
            return SECSuccess;
4482
0
        case ssl_grp_ec_secp384r1:
4483
0
            *scheme = ssl_sig_ecdsa_secp384r1_sha384;
4484
0
            return SECSuccess;
4485
0
        case ssl_grp_ec_secp521r1:
4486
0
            *scheme = ssl_sig_ecdsa_secp521r1_sha512;
4487
0
            return SECSuccess;
4488
0
        default:
4489
0
            break;
4490
0
    }
4491
0
    PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4492
0
    return SECFailure;
4493
0
}
4494
4495
/* Newer signature schemes are designed so that a single SPKI can be used with
4496
 * that scheme.  This determines that scheme from the SPKI. If the SPKI doesn't
4497
 * have a single scheme, |*scheme| is set to ssl_sig_none. */
4498
SECStatus
4499
ssl_SignatureSchemeFromSpki(const CERTSubjectPublicKeyInfo *spki,
4500
                            PRBool isTls13, SSLSignatureScheme *scheme)
4501
275
{
4502
275
    SECOidTag spkiOid = SECOID_GetAlgorithmTag(&spki->algorithm);
4503
4504
275
    if (spkiOid == SEC_OID_PKCS1_RSA_PSS_SIGNATURE) {
4505
0
        return ssl_SignatureSchemeFromPssSpki(spki, scheme);
4506
0
    }
4507
4508
    /* Only do this lookup for TLS 1.3, where the scheme can be determined from
4509
     * the SPKI alone because the ECDSA key size determines the hash. Earlier
4510
     * TLS versions allow the same EC key to be used with different hashes. */
4511
275
    if (isTls13 && spkiOid == SEC_OID_ANSIX962_EC_PUBLIC_KEY) {
4512
0
        return ssl_SignatureSchemeFromEcSpki(spki, scheme);
4513
0
    }
4514
4515
275
    *scheme = ssl_sig_none;
4516
275
    return SECSuccess;
4517
275
}
4518
4519
/* Check that a signature scheme is enabled by configuration. */
4520
PRBool
4521
ssl_SignatureSchemeEnabled(const sslSocket *ss, SSLSignatureScheme scheme)
4522
0
{
4523
0
    unsigned int i;
4524
0
    for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
4525
0
        if (scheme == ss->ssl3.signatureSchemes[i]) {
4526
0
            return PR_TRUE;
4527
0
        }
4528
0
    }
4529
0
    return PR_FALSE;
4530
0
}
4531
4532
static PRBool
4533
ssl_SignatureKeyMatchesSpkiOid(const ssl3KEADef *keaDef, SECOidTag spkiOid)
4534
0
{
4535
0
    switch (spkiOid) {
4536
0
        case SEC_OID_X500_RSA_ENCRYPTION:
4537
0
        case SEC_OID_PKCS1_RSA_ENCRYPTION:
4538
0
        case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
4539
0
            return keaDef->signKeyType == rsaKey;
4540
0
        case SEC_OID_ANSIX9_DSA_SIGNATURE:
4541
0
            return keaDef->signKeyType == dsaKey;
4542
0
        case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
4543
0
            return keaDef->signKeyType == ecKey;
4544
0
        default:
4545
0
            break;
4546
0
    }
4547
0
    return PR_FALSE;
4548
0
}
4549
4550
/* ssl3_CheckSignatureSchemeConsistency checks that the signature algorithm
4551
 * identifier in |scheme| is consistent with the public key in |spki|. It also
4552
 * checks the hash algorithm against the configured signature algorithms.  If
4553
 * all the tests pass, SECSuccess is returned. Otherwise, PORT_SetError is
4554
 * called and SECFailure is returned. */
4555
SECStatus
4556
ssl_CheckSignatureSchemeConsistency(sslSocket *ss, SSLSignatureScheme scheme,
4557
                                    CERTSubjectPublicKeyInfo *spki)
4558
0
{
4559
0
    SSLSignatureScheme spkiScheme;
4560
0
    PRBool isTLS13 = ss->version == SSL_LIBRARY_VERSION_TLS_1_3;
4561
0
    SECOidTag spkiOid;
4562
0
    SECStatus rv;
4563
4564
0
    rv = ssl_SignatureSchemeFromSpki(spki, isTLS13, &spkiScheme);
4565
0
    if (rv != SECSuccess) {
4566
0
        return SECFailure;
4567
0
    }
4568
0
    if (spkiScheme != ssl_sig_none) {
4569
        /* The SPKI in the certificate can only be used for a single scheme. */
4570
0
        if (spkiScheme != scheme ||
4571
0
            !ssl_SignatureSchemeEnabled(ss, scheme)) {
4572
0
            PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4573
0
            return SECFailure;
4574
0
        }
4575
0
        return SECSuccess;
4576
0
    }
4577
4578
0
    spkiOid = SECOID_GetAlgorithmTag(&spki->algorithm);
4579
4580
    /* If we're a client, check that the signature algorithm matches the signing
4581
     * key type of the cipher suite. */
4582
0
    if (!isTLS13 && !ss->sec.isServer) {
4583
0
        if (!ssl_SignatureKeyMatchesSpkiOid(ss->ssl3.hs.kea_def, spkiOid)) {
4584
0
            PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4585
0
            return SECFailure;
4586
0
        }
4587
0
    }
4588
4589
    /* Verify that the signature scheme matches the signing key. */
4590
0
    if ((spkiOid == SEC_OID_UNKNOWN) ||
4591
0
        !ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13)) {
4592
0
        PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4593
0
        return SECFailure;
4594
0
    }
4595
4596
0
    if (!ssl_SignatureSchemeEnabled(ss, scheme)) {
4597
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
4598
0
        return SECFailure;
4599
0
    }
4600
4601
0
    return SECSuccess;
4602
0
}
4603
4604
PRBool
4605
ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme)
4606
7.55k
{
4607
7.55k
    switch (scheme) {
4608
227
        case ssl_sig_rsa_pkcs1_sha1:
4609
494
        case ssl_sig_rsa_pkcs1_sha256:
4610
843
        case ssl_sig_rsa_pkcs1_sha384:
4611
1.14k
        case ssl_sig_rsa_pkcs1_sha512:
4612
1.50k
        case ssl_sig_rsa_pss_rsae_sha256:
4613
1.84k
        case ssl_sig_rsa_pss_rsae_sha384:
4614
2.21k
        case ssl_sig_rsa_pss_rsae_sha512:
4615
2.24k
        case ssl_sig_rsa_pss_pss_sha256:
4616
2.26k
        case ssl_sig_rsa_pss_pss_sha384:
4617
2.29k
        case ssl_sig_rsa_pss_pss_sha512:
4618
2.80k
        case ssl_sig_ecdsa_secp256r1_sha256:
4619
3.30k
        case ssl_sig_ecdsa_secp384r1_sha384:
4620
3.80k
        case ssl_sig_ecdsa_secp521r1_sha512:
4621
4.01k
        case ssl_sig_dsa_sha1:
4622
4.22k
        case ssl_sig_dsa_sha256:
4623
4.39k
        case ssl_sig_dsa_sha384:
4624
4.56k
        case ssl_sig_dsa_sha512:
4625
5.04k
        case ssl_sig_ecdsa_sha1:
4626
5.04k
            return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy);
4627
0
            break;
4628
4629
0
        case ssl_sig_rsa_pkcs1_sha1md5:
4630
264
        case ssl_sig_none:
4631
268
        case ssl_sig_ed25519:
4632
272
        case ssl_sig_ed448:
4633
272
            return PR_FALSE;
4634
7.55k
    }
4635
2.23k
    return PR_FALSE;
4636
7.55k
}
4637
4638
PRBool
4639
ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme)
4640
448k
{
4641
448k
    switch (scheme) {
4642
251k
        case ssl_sig_rsa_pss_rsae_sha256:
4643
258k
        case ssl_sig_rsa_pss_rsae_sha384:
4644
266k
        case ssl_sig_rsa_pss_rsae_sha512:
4645
266k
        case ssl_sig_rsa_pss_pss_sha256:
4646
266k
        case ssl_sig_rsa_pss_pss_sha384:
4647
266k
        case ssl_sig_rsa_pss_pss_sha512:
4648
266k
            return PR_TRUE;
4649
4650
181k
        default:
4651
181k
            return PR_FALSE;
4652
448k
    }
4653
0
    return PR_FALSE;
4654
448k
}
4655
4656
PRBool
4657
ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme)
4658
0
{
4659
0
    switch (scheme) {
4660
0
        case ssl_sig_rsa_pss_rsae_sha256:
4661
0
        case ssl_sig_rsa_pss_rsae_sha384:
4662
0
        case ssl_sig_rsa_pss_rsae_sha512:
4663
0
            return PR_TRUE;
4664
4665
0
        default:
4666
0
            return PR_FALSE;
4667
0
    }
4668
0
    return PR_FALSE;
4669
0
}
4670
4671
PRBool
4672
ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme)
4673
43.9k
{
4674
43.9k
    switch (scheme) {
4675
0
        case ssl_sig_rsa_pkcs1_sha256:
4676
0
        case ssl_sig_rsa_pkcs1_sha384:
4677
0
        case ssl_sig_rsa_pkcs1_sha512:
4678
0
        case ssl_sig_rsa_pkcs1_sha1:
4679
0
            return PR_TRUE;
4680
4681
43.9k
        default:
4682
43.9k
            return PR_FALSE;
4683
43.9k
    }
4684
0
    return PR_FALSE;
4685
43.9k
}
4686
4687
PRBool
4688
ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme)
4689
86.0k
{
4690
86.0k
    switch (scheme) {
4691
3.51k
        case ssl_sig_dsa_sha256:
4692
7.02k
        case ssl_sig_dsa_sha384:
4693
10.5k
        case ssl_sig_dsa_sha512:
4694
14.0k
        case ssl_sig_dsa_sha1:
4695
14.0k
            return PR_TRUE;
4696
4697
72.0k
        default:
4698
72.0k
            return PR_FALSE;
4699
86.0k
    }
4700
0
    return PR_FALSE;
4701
86.0k
}
4702
4703
SSLAuthType
4704
ssl_SignatureSchemeToAuthType(SSLSignatureScheme scheme)
4705
748k
{
4706
748k
    switch (scheme) {
4707
12.8k
        case ssl_sig_rsa_pkcs1_sha1:
4708
12.8k
        case ssl_sig_rsa_pkcs1_sha1md5:
4709
16.8k
        case ssl_sig_rsa_pkcs1_sha256:
4710
20.7k
        case ssl_sig_rsa_pkcs1_sha384:
4711
24.6k
        case ssl_sig_rsa_pkcs1_sha512:
4712
        /* We report based on the key type for PSS signatures. */
4713
146k
        case ssl_sig_rsa_pss_rsae_sha256:
4714
146k
        case ssl_sig_rsa_pss_rsae_sha384:
4715
147k
        case ssl_sig_rsa_pss_rsae_sha512:
4716
147k
            return ssl_auth_rsa_sign;
4717
0
        case ssl_sig_rsa_pss_pss_sha256:
4718
0
        case ssl_sig_rsa_pss_pss_sha384:
4719
0
        case ssl_sig_rsa_pss_pss_sha512:
4720
0
            return ssl_auth_rsa_pss;
4721
207k
        case ssl_sig_ecdsa_secp256r1_sha256:
4722
333k
        case ssl_sig_ecdsa_secp384r1_sha384:
4723
459k
        case ssl_sig_ecdsa_secp521r1_sha512:
4724
586k
        case ssl_sig_ecdsa_sha1:
4725
586k
            return ssl_auth_ecdsa;
4726
3.74k
        case ssl_sig_dsa_sha1:
4727
7.49k
        case ssl_sig_dsa_sha256:
4728
11.2k
        case ssl_sig_dsa_sha384:
4729
14.9k
        case ssl_sig_dsa_sha512:
4730
14.9k
            return ssl_auth_dsa;
4731
4732
0
        default:
4733
0
            PORT_Assert(0);
4734
748k
    }
4735
0
    return ssl_auth_null;
4736
748k
}
4737
4738
/* ssl_ConsumeSignatureScheme reads a SSLSignatureScheme (formerly
4739
 * SignatureAndHashAlgorithm) structure from |b| and puts the resulting value
4740
 * into |out|. |b| and |length| are updated accordingly.
4741
 *
4742
 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4743
SECStatus
4744
ssl_ConsumeSignatureScheme(sslSocket *ss, PRUint8 **b,
4745
                           PRUint32 *length, SSLSignatureScheme *out)
4746
0
{
4747
0
    PRUint32 tmp;
4748
0
    SECStatus rv;
4749
4750
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
4751
0
    if (rv != SECSuccess) {
4752
0
        return SECFailure; /* Alert sent, Error code set already. */
4753
0
    }
4754
0
    if (!ssl_IsSupportedSignatureScheme((SSLSignatureScheme)tmp)) {
4755
0
        SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
4756
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
4757
0
        return SECFailure;
4758
0
    }
4759
0
    *out = (SSLSignatureScheme)tmp;
4760
0
    return SECSuccess;
4761
0
}
4762
4763
/**************************************************************************
4764
 * end of Consume Handshake functions.
4765
 **************************************************************************/
4766
4767
static SECStatus
4768
ssl3_ComputeHandshakeHash(unsigned char *buf, unsigned int len,
4769
                          SSLHashType hashAlg, SSL3Hashes *hashes)
4770
2
{
4771
2
    SECStatus rv = SECFailure;
4772
2
    PK11Context *hashContext = PK11_CreateDigestContext(
4773
2
        ssl3_HashTypeToOID(hashAlg));
4774
4775
2
    if (!hashContext) {
4776
0
        return rv;
4777
0
    }
4778
2
    rv = PK11_DigestBegin(hashContext);
4779
2
    if (rv == SECSuccess) {
4780
2
        rv = PK11_DigestOp(hashContext, buf, len);
4781
2
    }
4782
2
    if (rv == SECSuccess) {
4783
2
        rv = PK11_DigestFinal(hashContext, hashes->u.raw, &hashes->len,
4784
2
                              sizeof(hashes->u.raw));
4785
2
    }
4786
2
    if (rv == SECSuccess) {
4787
2
        hashes->hashAlg = hashAlg;
4788
2
    }
4789
2
    PK11_DestroyContext(hashContext, PR_TRUE);
4790
2
    return rv;
4791
2
}
4792
4793
/* Extract the hashes of handshake messages to this point.
4794
 * Called from ssl3_SendCertificateVerify
4795
 *             ssl3_SendFinished
4796
 *             ssl3_HandleHandshakeMessage
4797
 *
4798
 * Caller must hold the SSL3HandshakeLock.
4799
 * Caller must hold a read or write lock on the Spec R/W lock.
4800
 *  (There is presently no way to assert on a Read lock.)
4801
 */
4802
SECStatus
4803
ssl3_ComputeHandshakeHashes(sslSocket *ss,
4804
                            ssl3CipherSpec *spec, /* uses ->master_secret */
4805
                            SSL3Hashes *hashes,   /* output goes here. */
4806
                            PRUint32 sender)
4807
2
{
4808
2
    SECStatus rv = SECSuccess;
4809
2
    PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
4810
2
    unsigned int outLength;
4811
2
    PRUint8 md5_inner[MAX_MAC_LENGTH];
4812
2
    PRUint8 sha_inner[MAX_MAC_LENGTH];
4813
4814
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4815
2
    if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
4816
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4817
0
        return SECFailure;
4818
0
    }
4819
4820
2
    hashes->hashAlg = ssl_hash_none;
4821
4822
2
    if (ss->ssl3.hs.hashType == handshake_hash_single) {
4823
0
        PK11Context *h;
4824
0
        unsigned int stateLen;
4825
0
        unsigned char stackBuf[1024];
4826
0
        unsigned char *stateBuf = NULL;
4827
4828
0
        h = ss->ssl3.hs.sha;
4829
0
        stateBuf = PK11_SaveContextAlloc(h, stackBuf,
4830
0
                                         sizeof(stackBuf), &stateLen);
4831
0
        if (stateBuf == NULL) {
4832
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4833
0
            rv = SECFailure;
4834
0
            goto tls12_loser;
4835
0
        }
4836
0
        rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
4837
0
                               sizeof(hashes->u.raw));
4838
0
        if (rv != SECSuccess) {
4839
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4840
0
            rv = SECFailure;
4841
0
            goto tls12_loser;
4842
0
        }
4843
4844
0
        hashes->hashAlg = ssl3_GetSuitePrfHash(ss);
4845
4846
0
    tls12_loser:
4847
0
        if (stateBuf) {
4848
0
            if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
4849
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4850
0
                rv = SECFailure;
4851
0
            }
4852
0
            if (stateBuf != stackBuf) {
4853
0
                PORT_ZFree(stateBuf, stateLen);
4854
0
            }
4855
0
        }
4856
2
    } else if (ss->ssl3.hs.hashType == handshake_hash_record) {
4857
2
        rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
4858
2
                                       ss->ssl3.hs.messages.len,
4859
2
                                       ssl3_GetSuitePrfHash(ss),
4860
2
                                       hashes);
4861
2
    } else {
4862
0
        PK11Context *md5;
4863
0
        PK11Context *sha = NULL;
4864
0
        unsigned char *md5StateBuf = NULL;
4865
0
        unsigned char *shaStateBuf = NULL;
4866
0
        unsigned int md5StateLen, shaStateLen;
4867
0
        unsigned char md5StackBuf[256];
4868
0
        unsigned char shaStackBuf[512];
4869
0
        const int md5Pad = ssl_GetMacDefByAlg(ssl_mac_md5)->pad_size;
4870
0
        const int shaPad = ssl_GetMacDefByAlg(ssl_mac_sha)->pad_size;
4871
4872
0
        md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
4873
0
                                            sizeof md5StackBuf, &md5StateLen);
4874
0
        if (md5StateBuf == NULL) {
4875
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4876
0
            rv = SECFailure;
4877
0
            goto loser;
4878
0
        }
4879
0
        md5 = ss->ssl3.hs.md5;
4880
4881
0
        shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
4882
0
                                            sizeof shaStackBuf, &shaStateLen);
4883
0
        if (shaStateBuf == NULL) {
4884
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4885
0
            rv = SECFailure;
4886
0
            goto loser;
4887
0
        }
4888
0
        sha = ss->ssl3.hs.sha;
4889
4890
0
        if (!isTLS) {
4891
            /* compute hashes for SSL3. */
4892
0
            unsigned char s[4];
4893
4894
0
            if (!spec->masterSecret) {
4895
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4896
0
                rv = SECFailure;
4897
0
                goto loser;
4898
0
            }
4899
4900
0
            s[0] = (unsigned char)(sender >> 24);
4901
0
            s[1] = (unsigned char)(sender >> 16);
4902
0
            s[2] = (unsigned char)(sender >> 8);
4903
0
            s[3] = (unsigned char)sender;
4904
4905
0
            if (sender != 0) {
4906
0
                rv |= PK11_DigestOp(md5, s, 4);
4907
0
                PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
4908
0
            }
4909
4910
0
            PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, md5Pad));
4911
4912
0
            rv |= PK11_DigestKey(md5, spec->masterSecret);
4913
0
            rv |= PK11_DigestOp(md5, mac_pad_1, md5Pad);
4914
0
            rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
4915
0
            PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4916
0
            if (rv != SECSuccess) {
4917
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4918
0
                rv = SECFailure;
4919
0
                goto loser;
4920
0
            }
4921
4922
0
            PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
4923
4924
0
            if (sender != 0) {
4925
0
                rv |= PK11_DigestOp(sha, s, 4);
4926
0
                PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
4927
0
            }
4928
4929
0
            PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, shaPad));
4930
4931
0
            rv |= PK11_DigestKey(sha, spec->masterSecret);
4932
0
            rv |= PK11_DigestOp(sha, mac_pad_1, shaPad);
4933
0
            rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
4934
0
            PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4935
0
            if (rv != SECSuccess) {
4936
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4937
0
                rv = SECFailure;
4938
0
                goto loser;
4939
0
            }
4940
4941
0
            PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
4942
4943
0
            PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, md5Pad));
4944
0
            PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
4945
4946
0
            rv |= PK11_DigestBegin(md5);
4947
0
            rv |= PK11_DigestKey(md5, spec->masterSecret);
4948
0
            rv |= PK11_DigestOp(md5, mac_pad_2, md5Pad);
4949
0
            rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
4950
0
        }
4951
0
        rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH);
4952
0
        PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4953
0
        if (rv != SECSuccess) {
4954
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4955
0
            rv = SECFailure;
4956
0
            goto loser;
4957
0
        }
4958
4959
0
        PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
4960
4961
0
        if (!isTLS) {
4962
0
            PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, shaPad));
4963
0
            PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
4964
4965
0
            rv |= PK11_DigestBegin(sha);
4966
0
            rv |= PK11_DigestKey(sha, spec->masterSecret);
4967
0
            rv |= PK11_DigestOp(sha, mac_pad_2, shaPad);
4968
0
            rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
4969
0
        }
4970
0
        rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH);
4971
0
        PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4972
0
        if (rv != SECSuccess) {
4973
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4974
0
            rv = SECFailure;
4975
0
            goto loser;
4976
0
        }
4977
4978
0
        PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
4979
4980
0
        hashes->len = MD5_LENGTH + SHA1_LENGTH;
4981
4982
0
    loser:
4983
0
        if (md5StateBuf) {
4984
0
            if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) !=
4985
0
                SECSuccess) {
4986
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4987
0
                rv = SECFailure;
4988
0
            }
4989
0
            if (md5StateBuf != md5StackBuf) {
4990
0
                PORT_ZFree(md5StateBuf, md5StateLen);
4991
0
            }
4992
0
        }
4993
0
        if (shaStateBuf) {
4994
0
            if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) !=
4995
0
                SECSuccess) {
4996
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4997
0
                rv = SECFailure;
4998
0
            }
4999
0
            if (shaStateBuf != shaStackBuf) {
5000
0
                PORT_ZFree(shaStateBuf, shaStateLen);
5001
0
            }
5002
0
        }
5003
0
    }
5004
2
    return rv;
5005
2
}
5006
5007
/**************************************************************************
5008
 * end of Handshake Hash functions.
5009
 * Begin Send and Handle functions for handshakes.
5010
 **************************************************************************/
5011
5012
#ifdef TRACE
5013
#define CHTYPE(t)          \
5014
0
    case client_hello_##t: \
5015
0
        return #t;
5016
5017
static const char *
5018
ssl_ClientHelloTypeName(sslClientHelloType type)
5019
0
{
5020
0
    switch (type) {
5021
0
        CHTYPE(initial);
5022
0
        CHTYPE(retry);
5023
0
        CHTYPE(retransmit);    /* DTLS only */
5024
0
        CHTYPE(renegotiation); /* TLS <= 1.2 only */
5025
0
    }
5026
0
    PORT_Assert(0);
5027
0
    return NULL;
5028
0
}
5029
#undef CHTYPE
5030
#endif
5031
5032
PR_STATIC_ASSERT(SSL3_SESSIONID_BYTES == SSL3_RANDOM_LENGTH);
5033
static void
5034
ssl_MakeFakeSid(sslSocket *ss, PRUint8 *buf)
5035
0
{
5036
0
    PRUint8 x = 0x5a;
5037
0
    int i;
5038
0
    for (i = 0; i < SSL3_SESSIONID_BYTES; ++i) {
5039
0
        x += ss->ssl3.hs.client_random[i];
5040
0
        buf[i] = x;
5041
0
    }
5042
0
}
5043
5044
/* Set the version fields of the cipher spec for a ClientHello. */
5045
static void
5046
ssl_SetClientHelloSpecVersion(sslSocket *ss, ssl3CipherSpec *spec)
5047
0
{
5048
0
    ssl_GetSpecWriteLock(ss);
5049
0
    PORT_Assert(spec->cipherDef->cipher == cipher_null);
5050
    /* This is - a best guess - but it doesn't matter here. */
5051
0
    spec->version = ss->vrange.max;
5052
0
    if (IS_DTLS(ss)) {
5053
0
        spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_0_WIRE;
5054
0
    } else {
5055
        /* For new connections, cap the record layer version number of TLS
5056
         * ClientHello to { 3, 1 } (TLS 1.0). Some TLS 1.0 servers (which seem
5057
         * to use F5 BIG-IP) ignore ClientHello.client_version and use the
5058
         * record layer version number (TLSPlaintext.version) instead when
5059
         * negotiating protocol versions. In addition, if the record layer
5060
         * version number of ClientHello is { 3, 2 } (TLS 1.1) or higher, these
5061
         * servers reset the TCP connections. Lastly, some F5 BIG-IP servers
5062
         * hang if a record containing a ClientHello has a version greater than
5063
         * { 3, 1 } and a length greater than 255. Set this flag to work around
5064
         * such servers.
5065
         *
5066
         * The final version is set when a version is negotiated.
5067
         */
5068
0
        spec->recordVersion = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0,
5069
0
                                     ss->vrange.max);
5070
0
    }
5071
0
    ssl_ReleaseSpecWriteLock(ss);
5072
0
}
5073
5074
SECStatus
5075
ssl3_InsertChHeaderSize(const sslSocket *ss, sslBuffer *preamble, const sslBuffer *extensions)
5076
0
{
5077
0
    SECStatus rv;
5078
0
    unsigned int msgLen = preamble->len;
5079
0
    msgLen += extensions->len ? (2 + extensions->len) : 0;
5080
0
    unsigned int headerLen = IS_DTLS(ss) ? 12 : 4;
5081
5082
    /* Record the message length. */
5083
0
    rv = sslBuffer_InsertNumber(preamble, 1, msgLen - headerLen, 3);
5084
0
    if (rv != SECSuccess) {
5085
0
        return SECFailure; /* code set */
5086
0
    }
5087
0
    if (IS_DTLS(ss)) {
5088
        /* Record the (unfragmented) fragment length. */
5089
0
        unsigned int offset = 1 /* ch */ + 3 /* len */ +
5090
0
                              2 /* seq */ + 3 /* fragment offset */;
5091
0
        rv = sslBuffer_InsertNumber(preamble, offset, msgLen - headerLen, 3);
5092
0
        if (rv != SECSuccess) {
5093
0
            return SECFailure; /* code set */
5094
0
        }
5095
0
    }
5096
5097
0
    return SECSuccess;
5098
0
}
5099
5100
static SECStatus
5101
ssl3_AppendCipherSuites(sslSocket *ss, PRBool fallbackSCSV, sslBuffer *buf)
5102
0
{
5103
0
    SECStatus rv;
5104
0
    unsigned int offset;
5105
0
    unsigned int i;
5106
0
    unsigned int saveLen;
5107
5108
0
    rv = sslBuffer_Skip(buf, 2, &offset);
5109
0
    if (rv != SECSuccess) {
5110
0
        return SECFailure;
5111
0
    }
5112
5113
0
    if (ss->ssl3.hs.sendingSCSV) {
5114
        /* Add the actual SCSV */
5115
0
        rv = sslBuffer_AppendNumber(buf, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
5116
0
                                    sizeof(ssl3CipherSuite));
5117
0
        if (rv != SECSuccess) {
5118
0
            return SECFailure;
5119
0
        }
5120
0
    }
5121
0
    if (fallbackSCSV) {
5122
0
        rv = sslBuffer_AppendNumber(buf, TLS_FALLBACK_SCSV,
5123
0
                                    sizeof(ssl3CipherSuite));
5124
0
        if (rv != SECSuccess) {
5125
0
            return SECFailure;
5126
0
        }
5127
0
    }
5128
5129
0
    saveLen = SSL_BUFFER_LEN(buf);
5130
    /* CipherSuites are appended to Hello message here */
5131
0
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
5132
0
        ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
5133
0
        if (ssl3_config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) {
5134
0
            rv = sslBuffer_AppendNumber(buf, suite->cipher_suite,
5135
0
                                        sizeof(ssl3CipherSuite));
5136
0
            if (rv != SECSuccess) {
5137
0
                return SECFailure;
5138
0
            }
5139
0
        }
5140
0
    }
5141
5142
    /* GREASE CipherSuites:
5143
     * A client MAY select one or more GREASE cipher suite values and advertise
5144
     * them in the "cipher_suites" field [RFC8701, Section 3.1]. */
5145
0
    if (ss->opt.enableGrease && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
5146
0
        rv = sslBuffer_AppendNumber(buf, ss->ssl3.hs.grease->idx[grease_cipher],
5147
0
                                    sizeof(ssl3CipherSuite));
5148
0
        if (rv != SECSuccess) {
5149
0
            return SECFailure;
5150
0
        }
5151
0
    }
5152
5153
0
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange) ||
5154
0
        (SSL_BUFFER_LEN(buf) - saveLen) == 0) {
5155
0
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
5156
0
        return SECFailure;
5157
0
    }
5158
5159
0
    return sslBuffer_InsertLength(buf, offset, 2);
5160
0
}
5161
5162
SECStatus
5163
ssl3_CreateClientHelloPreamble(sslSocket *ss, const sslSessionID *sid,
5164
                               PRBool realSid, PRUint16 version, PRBool isEchInner,
5165
                               const sslBuffer *extensions, sslBuffer *preamble)
5166
0
{
5167
0
    SECStatus rv;
5168
0
    sslBuffer constructed = SSL_BUFFER_EMPTY;
5169
0
    const PRUint8 *client_random = isEchInner ? ss->ssl3.hs.client_inner_random : ss->ssl3.hs.client_random;
5170
0
    PORT_Assert(sid);
5171
0
    PRBool fallbackSCSV = ss->opt.enableFallbackSCSV && !isEchInner &&
5172
0
                          (!realSid || version < sid->version);
5173
5174
0
    rv = sslBuffer_AppendNumber(&constructed, ssl_hs_client_hello, 1);
5175
0
    if (rv != SECSuccess) {
5176
0
        goto loser;
5177
0
    }
5178
5179
0
    rv = sslBuffer_Skip(&constructed, 3, NULL);
5180
0
    if (rv != SECSuccess) {
5181
0
        goto loser;
5182
0
    }
5183
5184
0
    if (IS_DTLS(ss)) {
5185
        /* Note that we make an unfragmented message here. We fragment in the
5186
         * transmission code, if necessary */
5187
0
        rv = sslBuffer_AppendNumber(&constructed, ss->ssl3.hs.sendMessageSeq, 2);
5188
0
        if (rv != SECSuccess) {
5189
0
            goto loser;
5190
0
        }
5191
0
        ss->ssl3.hs.sendMessageSeq++;
5192
5193
        /* 0 is the fragment offset, because it's not fragmented yet */
5194
0
        rv = sslBuffer_AppendNumber(&constructed, 0, 3);
5195
0
        if (rv != SECSuccess) {
5196
0
            goto loser;
5197
0
        }
5198
5199
        /* Fragment length -- set to the packet length because not fragmented */
5200
0
        rv = sslBuffer_Skip(&constructed, 3, NULL);
5201
0
        if (rv != SECSuccess) {
5202
0
            goto loser;
5203
0
        }
5204
0
    }
5205
5206
0
    if (ss->firstHsDone) {
5207
        /* The client hello version must stay unchanged to work around
5208
         * the Windows SChannel bug described in ssl3_SendClientHello. */
5209
0
        PORT_Assert(version == ss->clientHelloVersion);
5210
0
    }
5211
5212
0
    ss->clientHelloVersion = PR_MIN(version, SSL_LIBRARY_VERSION_TLS_1_2);
5213
0
    if (IS_DTLS(ss)) {
5214
0
        PRUint16 dtlsVersion = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
5215
0
        rv = sslBuffer_AppendNumber(&constructed, dtlsVersion, 2);
5216
0
    } else {
5217
0
        rv = sslBuffer_AppendNumber(&constructed, ss->clientHelloVersion, 2);
5218
0
    }
5219
0
    if (rv != SECSuccess) {
5220
0
        goto loser;
5221
0
    }
5222
5223
0
    rv = sslBuffer_Append(&constructed, client_random, SSL3_RANDOM_LENGTH);
5224
0
    if (rv != SECSuccess) {
5225
0
        goto loser;
5226
0
    }
5227
5228
0
    if (sid->version < SSL_LIBRARY_VERSION_TLS_1_3 && !isEchInner) {
5229
0
        rv = sslBuffer_AppendVariable(&constructed, sid->u.ssl3.sessionID,
5230
0
                                      sid->u.ssl3.sessionIDLength, 1);
5231
0
    } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) {
5232
        /* We're faking session resumption, so rather than create new
5233
         * randomness, just mix up the client random a little. */
5234
0
        PRUint8 buf[SSL3_SESSIONID_BYTES];
5235
0
        ssl_MakeFakeSid(ss, buf);
5236
0
        rv = sslBuffer_AppendVariable(&constructed, buf, SSL3_SESSIONID_BYTES, 1);
5237
0
    } else {
5238
0
        rv = sslBuffer_AppendNumber(&constructed, 0, 1);
5239
0
    }
5240
0
    if (rv != SECSuccess) {
5241
0
        goto loser;
5242
0
    }
5243
5244
0
    if (IS_DTLS(ss)) {
5245
        /* This cookieLen applies to the cookie that appears in the DTLS
5246
         * ClientHello, which isn't used in DTLS 1.3. */
5247
0
        rv = sslBuffer_AppendVariable(&constructed, ss->ssl3.hs.cookie.data,
5248
0
                                      ss->ssl3.hs.helloRetry ? 0 : ss->ssl3.hs.cookie.len,
5249
0
                                      1);
5250
0
        if (rv != SECSuccess) {
5251
0
            goto loser;
5252
0
        }
5253
0
    }
5254
5255
0
    rv = ssl3_AppendCipherSuites(ss, fallbackSCSV, &constructed);
5256
0
    if (rv != SECSuccess) {
5257
0
        goto loser;
5258
0
    }
5259
5260
    /* Compression methods: count is always 1, null compression. */
5261
0
    rv = sslBuffer_AppendNumber(&constructed, 1, 1);
5262
0
    if (rv != SECSuccess) {
5263
0
        goto loser;
5264
0
    }
5265
0
    rv = sslBuffer_AppendNumber(&constructed, ssl_compression_null, 1);
5266
0
    if (rv != SECSuccess) {
5267
0
        goto loser;
5268
0
    }
5269
5270
0
    rv = ssl3_InsertChHeaderSize(ss, &constructed, extensions);
5271
0
    if (rv != SECSuccess) {
5272
0
        goto loser;
5273
0
    }
5274
5275
0
    *preamble = constructed;
5276
0
    return SECSuccess;
5277
0
loser:
5278
0
    sslBuffer_Clear(&constructed);
5279
0
    return SECFailure;
5280
0
}
5281
5282
/* Called from ssl3_HandleHelloRequest(),
5283
 *             ssl3_RedoHandshake()
5284
 *             ssl_BeginClientHandshake (when resuming ssl3 session)
5285
 *             dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
5286
 *
5287
 * The |type| argument indicates what is going on here:
5288
 * - client_hello_initial is set for the very first ClientHello
5289
 * - client_hello_retry indicates that this is a second attempt after receiving
5290
 *   a HelloRetryRequest (in TLS 1.3)
5291
 * - client_hello_retransmit is used in DTLS when resending
5292
 * - client_hello_renegotiation is used to renegotiate (in TLS <1.3)
5293
 */
5294
SECStatus
5295
ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type)
5296
0
{
5297
0
    sslSessionID *sid;
5298
0
    SECStatus rv;
5299
0
    PRBool isTLS = PR_FALSE;
5300
0
    PRBool requestingResume = PR_FALSE;
5301
0
    PRBool unlockNeeded = PR_FALSE;
5302
0
    sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
5303
0
    PRUint16 version = ss->vrange.max;
5304
0
    PRInt32 flags;
5305
0
    sslBuffer chBuf = SSL_BUFFER_EMPTY;
5306
5307
0
    SSL_TRC(3, ("%d: SSL3[%d]: send %s ClientHello handshake", SSL_GETPID(),
5308
0
                ss->fd, ssl_ClientHelloTypeName(type)));
5309
5310
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5311
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5312
5313
    /* shouldn't get here if SSL3 is disabled, but ... */
5314
0
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
5315
0
        PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
5316
0
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
5317
0
        return SECFailure;
5318
0
    }
5319
5320
    /* If we are responding to a HelloRetryRequest, don't reinitialize. We need
5321
     * to maintain the handshake hashes. */
5322
0
    if (!ss->ssl3.hs.helloRetry) {
5323
0
        ssl3_RestartHandshakeHashes(ss);
5324
0
    }
5325
0
    PORT_Assert(!ss->ssl3.hs.helloRetry || type == client_hello_retry);
5326
5327
0
    if (type == client_hello_initial) {
5328
0
        ssl_SetClientHelloSpecVersion(ss, ss->ssl3.cwSpec);
5329
0
    }
5330
    /* These must be reset every handshake. */
5331
0
    ssl3_ResetExtensionData(&ss->xtnData, ss);
5332
0
    ss->ssl3.hs.sendingSCSV = PR_FALSE;
5333
0
    ss->ssl3.hs.preliminaryInfo = 0;
5334
0
    PORT_Assert(IS_DTLS(ss) || type != client_hello_retransmit);
5335
0
    SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
5336
0
    ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
5337
5338
    /* How many suites does our PKCS11 support (regardless of policy)? */
5339
0
    if (ssl3_config_match_init(ss) == 0) {
5340
0
        return SECFailure; /* ssl3_config_match_init has set error code. */
5341
0
    }
5342
5343
    /*
5344
     * During a renegotiation, ss->clientHelloVersion will be used again to
5345
     * work around a Windows SChannel bug. Ensure that it is still enabled.
5346
     */
5347
0
    if (ss->firstHsDone) {
5348
0
        PORT_Assert(type != client_hello_initial);
5349
0
        if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
5350
0
            PORT_SetError(SSL_ERROR_SSL_DISABLED);
5351
0
            return SECFailure;
5352
0
        }
5353
5354
0
        if (ss->clientHelloVersion < ss->vrange.min ||
5355
0
            ss->clientHelloVersion > ss->vrange.max) {
5356
0
            PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
5357
0
            return SECFailure;
5358
0
        }
5359
0
    }
5360
5361
    /* Check if we have a ss->sec.ci.sid.
5362
     * Check that it's not expired.
5363
     * If we have an sid and it comes from an external cache, we use it. */
5364
0
    if (ss->sec.ci.sid && ss->sec.ci.sid->cached == in_external_cache) {
5365
0
        PORT_Assert(!ss->sec.isServer);
5366
0
        sid = ssl_ReferenceSID(ss->sec.ci.sid);
5367
0
        SSL_TRC(3, ("%d: SSL3[%d]: using external resumption token in ClientHello",
5368
0
                    SSL_GETPID(), ss->fd));
5369
0
    } else if (ss->sec.ci.sid && ss->statelessResume && type == client_hello_retry) {
5370
        /* If we are sending a second ClientHello, reuse the same SID
5371
         * as the original one. */
5372
0
        sid = ssl_ReferenceSID(ss->sec.ci.sid);
5373
0
    } else if (!ss->opt.noCache) {
5374
        /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
5375
         * handles expired entries and other details.
5376
         * XXX If we've been called from ssl_BeginClientHandshake, then
5377
         * this lookup is duplicative and wasteful.
5378
         */
5379
0
        sid = ssl_LookupSID(ssl_Time(ss), &ss->sec.ci.peer,
5380
0
                            ss->sec.ci.port, ss->peerID, ss->url);
5381
0
    } else {
5382
0
        sid = NULL;
5383
0
    }
5384
5385
    /* We can't resume based on a different token. If the sid exists,
5386
     * make sure the token that holds the master secret still exists ...
5387
     * If we previously did client-auth, make sure that the token that holds
5388
     * the private key still exists, is logged in, hasn't been removed, etc.
5389
     */
5390
0
    if (sid) {
5391
0
        PRBool sidOK = PR_TRUE;
5392
5393
0
        if (sid->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
5394
0
            if (!tls13_ResumptionCompatible(ss, sid->u.ssl3.cipherSuite)) {
5395
0
                sidOK = PR_FALSE;
5396
0
            }
5397
0
        } else {
5398
            /* Check that the cipher suite we need is enabled. */
5399
0
            const ssl3CipherSuiteCfg *suite =
5400
0
                ssl_LookupCipherSuiteCfg(sid->u.ssl3.cipherSuite,
5401
0
                                         ss->cipherSuites);
5402
0
            SSLVersionRange vrange = { sid->version, sid->version };
5403
0
            if (!suite || !ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
5404
0
                sidOK = PR_FALSE;
5405
0
            }
5406
5407
            /* Check that no (valid) ECHConfigs are setup in combination with a
5408
             * (resumable) TLS < 1.3 session id. */
5409
0
            if (!PR_CLIST_IS_EMPTY(&ss->echConfigs)) {
5410
                /* If there are ECH configs, the client must not resume but
5411
                 * offer ECH. */
5412
0
                sidOK = PR_FALSE;
5413
0
            }
5414
0
        }
5415
5416
        /* Check that we can recover the master secret. */
5417
0
        if (sidOK) {
5418
0
            PK11SlotInfo *slot = NULL;
5419
0
            if (sid->u.ssl3.masterValid) {
5420
0
                slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
5421
0
                                         sid->u.ssl3.masterSlotID);
5422
0
            }
5423
0
            if (slot == NULL) {
5424
0
                sidOK = PR_FALSE;
5425
0
            } else {
5426
0
                PK11SymKey *wrapKey = NULL;
5427
0
                if (!PK11_IsPresent(slot) ||
5428
0
                    ((wrapKey = PK11_GetWrapKey(slot,
5429
0
                                                sid->u.ssl3.masterWrapIndex,
5430
0
                                                sid->u.ssl3.masterWrapMech,
5431
0
                                                sid->u.ssl3.masterWrapSeries,
5432
0
                                                ss->pkcs11PinArg)) == NULL)) {
5433
0
                    sidOK = PR_FALSE;
5434
0
                }
5435
0
                if (wrapKey)
5436
0
                    PK11_FreeSymKey(wrapKey);
5437
0
                PK11_FreeSlot(slot);
5438
0
                slot = NULL;
5439
0
            }
5440
0
        }
5441
        /* If we previously did client-auth, make sure that the token that
5442
        ** holds the private key still exists, is logged in, hasn't been
5443
        ** removed, etc.
5444
        */
5445
0
        if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
5446
0
            sidOK = PR_FALSE;
5447
0
        }
5448
5449
0
        if (sidOK) {
5450
            /* Set version based on the sid. */
5451
0
            if (ss->firstHsDone) {
5452
                /*
5453
                 * Windows SChannel compares the client_version inside the RSA
5454
                 * EncryptedPreMasterSecret of a renegotiation with the
5455
                 * client_version of the initial ClientHello rather than the
5456
                 * ClientHello in the renegotiation. To work around this bug, we
5457
                 * continue to use the client_version used in the initial
5458
                 * ClientHello when renegotiating.
5459
                 *
5460
                 * The client_version of the initial ClientHello is still
5461
                 * available in ss->clientHelloVersion. Ensure that
5462
                 * sid->version is bounded within
5463
                 * [ss->vrange.min, ss->clientHelloVersion], otherwise we
5464
                 * can't use sid.
5465
                 */
5466
0
                if (sid->version >= ss->vrange.min &&
5467
0
                    sid->version <= ss->clientHelloVersion) {
5468
0
                    version = ss->clientHelloVersion;
5469
0
                } else {
5470
0
                    sidOK = PR_FALSE;
5471
0
                }
5472
0
            } else {
5473
                /*
5474
                 * Check sid->version is OK first.
5475
                 * Previously, we would cap the version based on sid->version,
5476
                 * but that prevents negotiation of a higher version if the
5477
                 * previous session was reduced (e.g., with version fallback)
5478
                 */
5479
0
                if (sid->version < ss->vrange.min ||
5480
0
                    sid->version > ss->vrange.max) {
5481
0
                    sidOK = PR_FALSE;
5482
0
                }
5483
0
            }
5484
0
        }
5485
5486
0
        if (!sidOK) {
5487
0
            SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_not_ok);
5488
0
            ssl_UncacheSessionID(ss);
5489
0
            ssl_FreeSID(sid);
5490
0
            sid = NULL;
5491
0
        }
5492
0
    }
5493
5494
0
    if (sid) {
5495
0
        requestingResume = PR_TRUE;
5496
0
        SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_hits);
5497
5498
0
        PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
5499
0
                      sid->u.ssl3.sessionIDLength));
5500
5501
0
        ss->ssl3.policy = sid->u.ssl3.policy;
5502
0
    } else {
5503
0
        SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_misses);
5504
5505
        /*
5506
         * Windows SChannel compares the client_version inside the RSA
5507
         * EncryptedPreMasterSecret of a renegotiation with the
5508
         * client_version of the initial ClientHello rather than the
5509
         * ClientHello in the renegotiation. To work around this bug, we
5510
         * continue to use the client_version used in the initial
5511
         * ClientHello when renegotiating.
5512
         */
5513
0
        if (ss->firstHsDone) {
5514
0
            version = ss->clientHelloVersion;
5515
0
        }
5516
5517
0
        sid = ssl3_NewSessionID(ss, PR_FALSE);
5518
0
        if (!sid) {
5519
0
            return SECFailure; /* memory error is set */
5520
0
        }
5521
        /* ss->version isn't set yet, but the sid needs a sane value. */
5522
0
        sid->version = version;
5523
0
    }
5524
5525
0
    isTLS = (version > SSL_LIBRARY_VERSION_3_0);
5526
0
    ssl_GetSpecWriteLock(ss);
5527
0
    if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
5528
        /* SSL records are not being MACed. */
5529
0
        ss->ssl3.cwSpec->version = version;
5530
0
    }
5531
0
    ssl_ReleaseSpecWriteLock(ss);
5532
5533
0
    ssl_FreeSID(ss->sec.ci.sid); /* release the old sid */
5534
0
    ss->sec.ci.sid = sid;
5535
5536
    /* HACK for SCSV in SSL 3.0.  On initial handshake, prepend SCSV,
5537
     * only if TLS is disabled.
5538
     */
5539
0
    if (!ss->firstHsDone && !isTLS) {
5540
        /* Must set this before calling Hello Extension Senders,
5541
         * to suppress sending of empty RI extension.
5542
         */
5543
0
        ss->ssl3.hs.sendingSCSV = PR_TRUE;
5544
0
    }
5545
5546
    /* When we attempt session resumption (only), we must lock the sid to
5547
     * prevent races with other resumption connections that receive a
5548
     * NewSessionTicket that will cause the ticket in the sid to be replaced.
5549
     * Once we've copied the session ticket into our ClientHello message, it
5550
     * is OK for the ticket to change, so we just need to make sure we hold
5551
     * the lock across the calls to ssl_ConstructExtensions.
5552
     */
5553
0
    if (sid->u.ssl3.lock) {
5554
0
        unlockNeeded = PR_TRUE;
5555
0
        PR_RWLock_Rlock(sid->u.ssl3.lock);
5556
0
    }
5557
5558
    /* Generate a new random if this is the first attempt or renegotiation. */
5559
0
    if (type == client_hello_initial ||
5560
0
        type == client_hello_renegotiation) {
5561
0
        rv = ssl3_GetNewRandom(ss->ssl3.hs.client_random);
5562
0
        if (rv != SECSuccess) {
5563
0
            goto loser; /* err set by GetNewRandom. */
5564
0
        }
5565
0
    }
5566
5567
0
    if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
5568
0
        rv = tls13_SetupClientHello(ss, type);
5569
0
        if (rv != SECSuccess) {
5570
0
            goto loser;
5571
0
        }
5572
0
    }
5573
5574
    /* Setup TLS ClientHello Extension Permutation? */
5575
0
    if (type == client_hello_initial &&
5576
0
        ss->vrange.max > SSL_LIBRARY_VERSION_3_0 &&
5577
0
        ss->opt.enableChXtnPermutation) {
5578
0
        rv = tls_ClientHelloExtensionPermutationSetup(ss);
5579
0
        if (rv != SECSuccess) {
5580
0
            goto loser;
5581
0
        }
5582
0
    }
5583
5584
0
    if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
5585
0
        rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_client_hello);
5586
0
        if (rv != SECSuccess) {
5587
0
            goto loser;
5588
0
        }
5589
0
    }
5590
5591
0
    if (IS_DTLS(ss)) {
5592
0
        ssl3_DisableNonDTLSSuites(ss);
5593
0
    }
5594
5595
0
    rv = ssl3_CreateClientHelloPreamble(ss, sid, requestingResume, version,
5596
0
                                        PR_FALSE, &extensionBuf, &chBuf);
5597
0
    if (rv != SECSuccess) {
5598
0
        goto loser; /* err set by ssl3_CreateClientHelloPreamble. */
5599
0
    }
5600
5601
0
    if (!ss->ssl3.hs.echHpkeCtx) {
5602
0
        if (extensionBuf.len) {
5603
0
            rv = tls13_MaybeGreaseEch(ss, &chBuf, &extensionBuf);
5604
0
            if (rv != SECSuccess) {
5605
0
                goto loser; /* err set by tls13_MaybeGreaseEch. */
5606
0
            }
5607
0
            rv = ssl_InsertPaddingExtension(ss, chBuf.len, &extensionBuf);
5608
0
            if (rv != SECSuccess) {
5609
0
                goto loser; /* err set by ssl_InsertPaddingExtension. */
5610
0
            }
5611
5612
0
            rv = ssl3_InsertChHeaderSize(ss, &chBuf, &extensionBuf);
5613
0
            if (rv != SECSuccess) {
5614
0
                goto loser; /* err set by ssl3_InsertChHeaderSize. */
5615
0
            }
5616
5617
            /* If we are sending a PSK binder, replace the dummy value. */
5618
0
            if (ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)) {
5619
0
                rv = tls13_WriteExtensionsWithBinder(ss, &extensionBuf, &chBuf);
5620
0
            } else {
5621
0
                rv = sslBuffer_AppendNumber(&chBuf, extensionBuf.len, 2);
5622
0
                if (rv != SECSuccess) {
5623
0
                    goto loser;
5624
0
                }
5625
0
                rv = sslBuffer_AppendBuffer(&chBuf, &extensionBuf);
5626
0
            }
5627
0
            if (rv != SECSuccess) {
5628
0
                goto loser; /* err set by sslBuffer_Append*. */
5629
0
            }
5630
0
        }
5631
5632
        /* If we already have a message in place, we need to enqueue it.
5633
         * This empties the buffer. This is a convenient place to call
5634
         * dtls_StageHandshakeMessage to mark the message boundary.  */
5635
0
        if (IS_DTLS(ss)) {
5636
0
            rv = dtls_StageHandshakeMessage(ss);
5637
0
            if (rv != SECSuccess) {
5638
0
                goto loser;
5639
0
            }
5640
0
        }
5641
5642
        /* As here the function takes the full message and hashes it in one go,
5643
         * For DTLS1.3, we skip hashing the unnecessary header fields.
5644
         * See ssl3_AppendHandshakeHeader. */
5645
0
        if (IS_DTLS(ss) && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
5646
0
            rv = ssl3_AppendHandshakeSuppressHash(ss, chBuf.buf, chBuf.len);
5647
0
            if (rv != SECSuccess) {
5648
0
                goto loser; /* code set */
5649
0
            }
5650
0
            if (!ss->firstHsDone) {
5651
0
                PORT_Assert(ss->ssl3.hs.dtls13ClientMessageBuffer.len == 0);
5652
0
                sslBuffer_Clear(&ss->ssl3.hs.dtls13ClientMessageBuffer);
5653
                /* Here instead of computing the hash, we copy the data to a buffer.*/
5654
0
                rv = sslBuffer_Append(&ss->ssl3.hs.dtls13ClientMessageBuffer, chBuf.buf, chBuf.len);
5655
0
            }
5656
0
        } else {
5657
0
            rv = ssl3_AppendHandshake(ss, chBuf.buf, chBuf.len);
5658
0
        }
5659
5660
0
    } else {
5661
0
        PORT_Assert(!IS_DTLS(ss));
5662
0
        rv = tls13_ConstructClientHelloWithEch(ss, sid, !requestingResume, &chBuf, &extensionBuf);
5663
0
        if (rv != SECSuccess) {
5664
0
            goto loser; /* code set */
5665
0
        }
5666
0
        rv = ssl3_UpdateDefaultHandshakeHashes(ss, chBuf.buf, chBuf.len);
5667
0
        if (rv != SECSuccess) {
5668
0
            goto loser; /* code set */
5669
0
        }
5670
5671
0
        if (IS_DTLS(ss)) {
5672
0
            rv = dtls_StageHandshakeMessage(ss);
5673
0
            if (rv != SECSuccess) {
5674
0
                goto loser;
5675
0
            }
5676
0
        }
5677
        /* By default, all messagess are added to both the inner and
5678
         * outer transcripts. For CH (or CH2 if HRR), that's problematic. */
5679
0
        rv = ssl3_AppendHandshakeSuppressHash(ss, chBuf.buf, chBuf.len);
5680
0
    }
5681
0
    if (rv != SECSuccess) {
5682
0
        goto loser;
5683
0
    }
5684
5685
0
    if (unlockNeeded) {
5686
        /* Note: goto loser can't be used past this point. */
5687
0
        PR_RWLock_Unlock(sid->u.ssl3.lock);
5688
0
    }
5689
5690
0
    if (ss->xtnData.sentSessionTicketInClientHello) {
5691
0
        SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes);
5692
0
    }
5693
5694
0
    if (ss->ssl3.hs.sendingSCSV) {
5695
        /* Since we sent the SCSV, pretend we sent empty RI extension. */
5696
0
        TLSExtensionData *xtnData = &ss->xtnData;
5697
0
        xtnData->advertised[xtnData->numAdvertised++] =
5698
0
            ssl_renegotiation_info_xtn;
5699
0
    }
5700
5701
0
    flags = 0;
5702
0
    rv = ssl3_FlushHandshake(ss, flags);
5703
0
    if (rv != SECSuccess) {
5704
0
        return rv; /* error code set by ssl3_FlushHandshake */
5705
0
    }
5706
5707
0
    if (version >= SSL_LIBRARY_VERSION_TLS_1_3) {
5708
0
        rv = tls13_MaybeDo0RTTHandshake(ss);
5709
0
        if (rv != SECSuccess) {
5710
0
            return SECFailure; /* error code set already. */
5711
0
        }
5712
0
    }
5713
5714
0
    ss->ssl3.hs.ws = wait_server_hello;
5715
0
    sslBuffer_Clear(&chBuf);
5716
0
    sslBuffer_Clear(&extensionBuf);
5717
0
    return SECSuccess;
5718
5719
0
loser:
5720
0
    if (unlockNeeded) {
5721
0
        PR_RWLock_Unlock(sid->u.ssl3.lock);
5722
0
    }
5723
0
    sslBuffer_Clear(&chBuf);
5724
0
    sslBuffer_Clear(&extensionBuf);
5725
0
    return SECFailure;
5726
0
}
5727
5728
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
5729
 * complete ssl3 Hello Request.
5730
 * Caller must hold Handshake and RecvBuf locks.
5731
 */
5732
static SECStatus
5733
ssl3_HandleHelloRequest(sslSocket *ss)
5734
0
{
5735
0
    sslSessionID *sid = ss->sec.ci.sid;
5736
0
    SECStatus rv;
5737
5738
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
5739
0
                SSL_GETPID(), ss->fd));
5740
5741
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
5742
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5743
0
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
5744
5745
0
    if (ss->ssl3.hs.ws == wait_server_hello)
5746
0
        return SECSuccess;
5747
0
    if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
5748
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
5749
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
5750
0
        return SECFailure;
5751
0
    }
5752
0
    if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
5753
0
        (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation);
5754
0
        PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
5755
0
        return SECFailure;
5756
0
    }
5757
5758
0
    if (sid) {
5759
0
        ssl_UncacheSessionID(ss);
5760
0
        ssl_FreeSID(sid);
5761
0
        ss->sec.ci.sid = NULL;
5762
0
    }
5763
5764
0
    if (IS_DTLS(ss)) {
5765
0
        dtls_RehandshakeCleanup(ss);
5766
0
    }
5767
5768
0
    ssl_GetXmitBufLock(ss);
5769
0
    rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
5770
0
    ssl_ReleaseXmitBufLock(ss);
5771
5772
0
    return rv;
5773
0
}
5774
5775
static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
5776
    CKM_DES3_ECB,
5777
    CKM_CAST5_ECB,
5778
    CKM_DES_ECB,
5779
    CKM_KEY_WRAP_LYNKS,
5780
    CKM_IDEA_ECB,
5781
    CKM_CAST3_ECB,
5782
    CKM_CAST_ECB,
5783
    CKM_RC5_ECB,
5784
    CKM_RC2_ECB,
5785
    CKM_CDMF_ECB,
5786
    CKM_SKIPJACK_WRAP,
5787
    CKM_SKIPJACK_CBC64,
5788
    CKM_AES_ECB,
5789
    CKM_CAMELLIA_ECB,
5790
    CKM_SEED_ECB
5791
};
5792
5793
static SECStatus
5794
ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech, unsigned int *wrapMechIndex)
5795
0
{
5796
0
    unsigned int i;
5797
0
    for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
5798
0
        if (wrapMechanismList[i] == mech) {
5799
0
            *wrapMechIndex = i;
5800
0
            return SECSuccess;
5801
0
        }
5802
0
    }
5803
0
    PORT_Assert(0);
5804
0
    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5805
0
    return SECFailure;
5806
0
}
5807
5808
/* Each process sharing the server session ID cache has its own array of SymKey
5809
 * pointers for the symmetric wrapping keys that are used to wrap the master
5810
 * secrets.  There is one key for each authentication type.  These Symkeys
5811
 * correspond to the wrapped SymKeys kept in the server session cache.
5812
 */
5813
const SSLAuthType ssl_wrap_key_auth_type[SSL_NUM_WRAP_KEYS] = {
5814
    ssl_auth_rsa_decrypt,
5815
    ssl_auth_rsa_sign,
5816
    ssl_auth_rsa_pss,
5817
    ssl_auth_ecdsa,
5818
    ssl_auth_ecdh_rsa,
5819
    ssl_auth_ecdh_ecdsa
5820
};
5821
5822
static SECStatus
5823
ssl_FindIndexByWrapKey(const sslServerCert *serverCert, unsigned int *wrapKeyIndex)
5824
0
{
5825
0
    unsigned int i;
5826
0
    for (i = 0; i < SSL_NUM_WRAP_KEYS; ++i) {
5827
0
        if (SSL_CERT_IS(serverCert, ssl_wrap_key_auth_type[i])) {
5828
0
            *wrapKeyIndex = i;
5829
0
            return SECSuccess;
5830
0
        }
5831
0
    }
5832
    /* Can't assert here because we still get people using DSA certificates. */
5833
0
    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5834
0
    return SECFailure;
5835
0
}
5836
5837
static PK11SymKey *
5838
ssl_UnwrapSymWrappingKey(
5839
    SSLWrappedSymWrappingKey *pWswk,
5840
    SECKEYPrivateKey *svrPrivKey,
5841
    unsigned int wrapKeyIndex,
5842
    CK_MECHANISM_TYPE masterWrapMech,
5843
    void *pwArg)
5844
0
{
5845
0
    PK11SymKey *unwrappedWrappingKey = NULL;
5846
0
    SECItem wrappedKey;
5847
0
    PK11SymKey *Ks;
5848
0
    SECKEYPublicKey pubWrapKey;
5849
0
    ECCWrappedKeyInfo *ecWrapped;
5850
5851
    /* found the wrapping key on disk. */
5852
0
    PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
5853
0
    PORT_Assert(pWswk->wrapKeyIndex == wrapKeyIndex);
5854
0
    if (pWswk->symWrapMechanism != masterWrapMech ||
5855
0
        pWswk->wrapKeyIndex != wrapKeyIndex) {
5856
0
        goto loser;
5857
0
    }
5858
0
    wrappedKey.type = siBuffer;
5859
0
    wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
5860
0
    wrappedKey.len = pWswk->wrappedSymKeyLen;
5861
0
    PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
5862
5863
0
    switch (ssl_wrap_key_auth_type[wrapKeyIndex]) {
5864
5865
0
        case ssl_auth_rsa_decrypt:
5866
0
        case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
5867
0
            unwrappedWrappingKey =
5868
0
                PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
5869
0
                                     masterWrapMech, CKA_UNWRAP, 0);
5870
0
            break;
5871
5872
0
        case ssl_auth_ecdsa:
5873
0
        case ssl_auth_ecdh_rsa:
5874
0
        case ssl_auth_ecdh_ecdsa:
5875
            /*
5876
             * For ssl_auth_ecd*, we first create an EC public key based on
5877
             * data stored with the wrappedSymmetricWrappingkey. Next,
5878
             * we do an ECDH computation involving this public key and
5879
             * the SSL server's (long-term) EC private key. The resulting
5880
             * shared secret is treated the same way as Fortezza's Ks, i.e.,
5881
             * it is used to recover the symmetric wrapping key.
5882
             *
5883
             * The data in wrappedSymmetricWrappingkey is laid out as defined
5884
             * in the ECCWrappedKeyInfo structure.
5885
             */
5886
0
            ecWrapped = (ECCWrappedKeyInfo *)pWswk->wrappedSymmetricWrappingkey;
5887
5888
0
            PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5889
0
                            ecWrapped->wrappedKeyLen <=
5890
0
                        MAX_EC_WRAPPED_KEY_BUFLEN);
5891
5892
0
            if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5893
0
                    ecWrapped->wrappedKeyLen >
5894
0
                MAX_EC_WRAPPED_KEY_BUFLEN) {
5895
0
                PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5896
0
                goto loser;
5897
0
            }
5898
5899
0
            pubWrapKey.keyType = ecKey;
5900
0
            pubWrapKey.u.ec.size = ecWrapped->size;
5901
0
            pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
5902
0
            pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
5903
0
            pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
5904
0
            pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
5905
0
                                               ecWrapped->encodedParamLen;
5906
5907
0
            wrappedKey.len = ecWrapped->wrappedKeyLen;
5908
0
            wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
5909
0
                              ecWrapped->pubValueLen;
5910
5911
            /* Derive Ks using ECDH */
5912
0
            Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
5913
0
                                       NULL, CKM_ECDH1_DERIVE, masterWrapMech,
5914
0
                                       CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5915
0
            if (Ks == NULL) {
5916
0
                goto loser;
5917
0
            }
5918
5919
            /*  Use Ks to unwrap the wrapping key */
5920
0
            unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL,
5921
0
                                                     &wrappedKey, masterWrapMech,
5922
0
                                                     CKA_UNWRAP, 0);
5923
0
            PK11_FreeSymKey(Ks);
5924
5925
0
            break;
5926
5927
0
        default:
5928
0
            PORT_Assert(0);
5929
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5930
0
            goto loser;
5931
0
    }
5932
0
loser:
5933
0
    return unwrappedWrappingKey;
5934
0
}
5935
5936
typedef struct {
5937
    PK11SymKey *symWrapKey[SSL_NUM_WRAP_KEYS];
5938
} ssl3SymWrapKey;
5939
5940
static PZLock *symWrapKeysLock = NULL;
5941
static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS];
5942
5943
SECStatus
5944
ssl_FreeSymWrapKeysLock(void)
5945
1
{
5946
1
    if (symWrapKeysLock) {
5947
1
        PZ_DestroyLock(symWrapKeysLock);
5948
1
        symWrapKeysLock = NULL;
5949
1
        return SECSuccess;
5950
1
    }
5951
0
    PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
5952
0
    return SECFailure;
5953
1
}
5954
5955
SECStatus
5956
SSL3_ShutdownServerCache(void)
5957
1
{
5958
1
    int i, j;
5959
5960
1
    if (!symWrapKeysLock)
5961
0
        return SECSuccess; /* lock was never initialized */
5962
1
    PZ_Lock(symWrapKeysLock);
5963
    /* get rid of all symWrapKeys */
5964
16
    for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
5965
105
        for (j = 0; j < SSL_NUM_WRAP_KEYS; ++j) {
5966
90
            PK11SymKey **pSymWrapKey;
5967
90
            pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
5968
90
            if (*pSymWrapKey) {
5969
0
                PK11_FreeSymKey(*pSymWrapKey);
5970
0
                *pSymWrapKey = NULL;
5971
0
            }
5972
90
        }
5973
15
    }
5974
5975
1
    PZ_Unlock(symWrapKeysLock);
5976
1
    ssl_FreeSessionCacheLocks();
5977
1
    return SECSuccess;
5978
1
}
5979
5980
SECStatus
5981
ssl_InitSymWrapKeysLock(void)
5982
1
{
5983
1
    symWrapKeysLock = PZ_NewLock(nssILockOther);
5984
1
    return symWrapKeysLock ? SECSuccess : SECFailure;
5985
1
}
5986
5987
/* Try to get wrapping key for mechanism from in-memory array.
5988
 * If that fails, look for one on disk.
5989
 * If that fails, generate a new one, put the new one on disk,
5990
 * Put the new key in the in-memory array.
5991
 *
5992
 * Note that this function performs some fairly inadvisable functions with
5993
 * certificate private keys.  ECDSA keys are used with ECDH; similarly, RSA
5994
 * signing keys are used to encrypt.  Bug 1248320.
5995
 */
5996
PK11SymKey *
5997
ssl3_GetWrappingKey(sslSocket *ss,
5998
                    PK11SlotInfo *masterSecretSlot,
5999
                    CK_MECHANISM_TYPE masterWrapMech,
6000
                    void *pwArg)
6001
0
{
6002
0
    SSLAuthType authType;
6003
0
    SECKEYPrivateKey *svrPrivKey;
6004
0
    SECKEYPublicKey *svrPubKey = NULL;
6005
0
    PK11SymKey *unwrappedWrappingKey = NULL;
6006
0
    PK11SymKey **pSymWrapKey;
6007
0
    CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM;
6008
0
    int length;
6009
0
    unsigned int wrapMechIndex;
6010
0
    unsigned int wrapKeyIndex;
6011
0
    SECStatus rv;
6012
0
    SECItem wrappedKey;
6013
0
    SSLWrappedSymWrappingKey wswk;
6014
0
    PK11SymKey *Ks = NULL;
6015
0
    SECKEYPublicKey *pubWrapKey = NULL;
6016
0
    SECKEYPrivateKey *privWrapKey = NULL;
6017
0
    ECCWrappedKeyInfo *ecWrapped;
6018
0
    const sslServerCert *serverCert = ss->sec.serverCert;
6019
6020
0
    PORT_Assert(serverCert);
6021
0
    PORT_Assert(serverCert->serverKeyPair);
6022
0
    PORT_Assert(serverCert->serverKeyPair->privKey);
6023
0
    PORT_Assert(serverCert->serverKeyPair->pubKey);
6024
0
    if (!serverCert || !serverCert->serverKeyPair ||
6025
0
        !serverCert->serverKeyPair->privKey ||
6026
0
        !serverCert->serverKeyPair->pubKey) {
6027
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6028
0
        return NULL; /* hmm */
6029
0
    }
6030
6031
0
    rv = ssl_FindIndexByWrapKey(serverCert, &wrapKeyIndex);
6032
0
    if (rv != SECSuccess)
6033
0
        return NULL; /* unusable wrapping key. */
6034
6035
0
    rv = ssl_FindIndexByWrapMechanism(masterWrapMech, &wrapMechIndex);
6036
0
    if (rv != SECSuccess)
6037
0
        return NULL; /* invalid masterWrapMech. */
6038
6039
0
    authType = ssl_wrap_key_auth_type[wrapKeyIndex];
6040
0
    svrPrivKey = serverCert->serverKeyPair->privKey;
6041
0
    pSymWrapKey = &symWrapKeys[wrapMechIndex].symWrapKey[wrapKeyIndex];
6042
6043
0
    ssl_InitSessionCacheLocks(PR_TRUE);
6044
6045
0
    PZ_Lock(symWrapKeysLock);
6046
6047
0
    unwrappedWrappingKey = *pSymWrapKey;
6048
0
    if (unwrappedWrappingKey != NULL) {
6049
0
        if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
6050
0
            unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
6051
0
            goto done;
6052
0
        }
6053
        /* slot series has changed, so this key is no good any more. */
6054
0
        PK11_FreeSymKey(unwrappedWrappingKey);
6055
0
        *pSymWrapKey = unwrappedWrappingKey = NULL;
6056
0
    }
6057
6058
    /* Try to get wrapped SymWrapping key out of the (disk) cache. */
6059
    /* Following call fills in wswk on success. */
6060
0
    rv = ssl_GetWrappingKey(wrapMechIndex, wrapKeyIndex, &wswk);
6061
0
    if (rv == SECSuccess) {
6062
        /* found the wrapped sym wrapping key on disk. */
6063
0
        unwrappedWrappingKey =
6064
0
            ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
6065
0
                                     masterWrapMech, pwArg);
6066
0
        if (unwrappedWrappingKey) {
6067
0
            goto install;
6068
0
        }
6069
0
    }
6070
6071
0
    if (!masterSecretSlot) /* caller doesn't want to create a new one. */
6072
0
        goto loser;
6073
6074
0
    length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
6075
    /* Zero length means fixed key length algorithm, or error.
6076
     * It's ambiguous.
6077
     */
6078
0
    unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
6079
0
                                       length, pwArg);
6080
0
    if (!unwrappedWrappingKey) {
6081
0
        goto loser;
6082
0
    }
6083
6084
    /* Prepare the buffer to receive the wrappedWrappingKey,
6085
     * the symmetric wrapping key wrapped using the server's pub key.
6086
     */
6087
0
    PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */
6088
6089
0
    svrPubKey = serverCert->serverKeyPair->pubKey;
6090
0
    wrappedKey.type = siBuffer;
6091
0
    wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey);
6092
0
    wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
6093
6094
0
    PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
6095
0
    if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
6096
0
        goto loser;
6097
6098
    /* wrap symmetric wrapping key in server's public key. */
6099
0
    switch (authType) {
6100
0
        case ssl_auth_rsa_decrypt:
6101
0
        case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
6102
0
        case ssl_auth_rsa_pss:
6103
0
            asymWrapMechanism = CKM_RSA_PKCS;
6104
0
            rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
6105
0
                                    unwrappedWrappingKey, &wrappedKey);
6106
0
            break;
6107
6108
0
        case ssl_auth_ecdsa:
6109
0
        case ssl_auth_ecdh_rsa:
6110
0
        case ssl_auth_ecdh_ecdsa:
6111
            /*
6112
             * We generate an ephemeral EC key pair. Perform an ECDH
6113
             * computation involving this ephemeral EC public key and
6114
             * the SSL server's (long-term) EC private key. The resulting
6115
             * shared secret is treated in the same way as Fortezza's Ks,
6116
             * i.e., it is used to wrap the wrapping key. To facilitate
6117
             * unwrapping in ssl_UnwrapWrappingKey, we also store all
6118
             * relevant info about the ephemeral EC public key in
6119
             * wswk.wrappedSymmetricWrappingkey and lay it out as
6120
             * described in the ECCWrappedKeyInfo structure.
6121
             */
6122
0
            PORT_Assert(SECKEY_GetPublicKeyType(svrPubKey) == ecKey);
6123
0
            if (SECKEY_GetPublicKeyType(svrPubKey) != ecKey) {
6124
                /* something is wrong in sslsecur.c if this isn't an ecKey */
6125
0
                PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6126
0
                rv = SECFailure;
6127
0
                goto ec_cleanup;
6128
0
            }
6129
6130
0
            privWrapKey = SECKEY_CreateECPrivateKey(
6131
0
                &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
6132
0
            if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
6133
0
                rv = SECFailure;
6134
0
                goto ec_cleanup;
6135
0
            }
6136
6137
            /* Set the key size in bits */
6138
0
            if (pubWrapKey->u.ec.size == 0) {
6139
0
                pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
6140
0
            }
6141
6142
0
            PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +
6143
0
                            pubWrapKey->u.ec.publicValue.len <
6144
0
                        MAX_EC_WRAPPED_KEY_BUFLEN);
6145
0
            if (pubWrapKey->u.ec.DEREncodedParams.len +
6146
0
                    pubWrapKey->u.ec.publicValue.len >=
6147
0
                MAX_EC_WRAPPED_KEY_BUFLEN) {
6148
0
                PORT_SetError(SEC_ERROR_INVALID_KEY);
6149
0
                rv = SECFailure;
6150
0
                goto ec_cleanup;
6151
0
            }
6152
6153
            /* Derive Ks using ECDH */
6154
0
            Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
6155
0
                                       NULL, CKM_ECDH1_DERIVE, masterWrapMech,
6156
0
                                       CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
6157
0
            if (Ks == NULL) {
6158
0
                rv = SECFailure;
6159
0
                goto ec_cleanup;
6160
0
            }
6161
6162
0
            ecWrapped = (ECCWrappedKeyInfo *)(wswk.wrappedSymmetricWrappingkey);
6163
0
            ecWrapped->size = pubWrapKey->u.ec.size;
6164
0
            ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
6165
0
            PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
6166
0
                        pubWrapKey->u.ec.DEREncodedParams.len);
6167
6168
0
            ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
6169
0
            PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen,
6170
0
                        pubWrapKey->u.ec.publicValue.data,
6171
0
                        pubWrapKey->u.ec.publicValue.len);
6172
6173
0
            wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN -
6174
0
                             (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
6175
0
            wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
6176
0
                              ecWrapped->pubValueLen;
6177
6178
            /* wrap symmetricWrapping key with the local Ks */
6179
0
            rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
6180
0
                                 unwrappedWrappingKey, &wrappedKey);
6181
6182
0
            if (rv != SECSuccess) {
6183
0
                goto ec_cleanup;
6184
0
            }
6185
6186
            /* Write down the length of wrapped key in the buffer
6187
             * wswk.wrappedSymmetricWrappingkey at the appropriate offset
6188
             */
6189
0
            ecWrapped->wrappedKeyLen = wrappedKey.len;
6190
6191
0
        ec_cleanup:
6192
0
            if (privWrapKey)
6193
0
                SECKEY_DestroyPrivateKey(privWrapKey);
6194
0
            if (pubWrapKey)
6195
0
                SECKEY_DestroyPublicKey(pubWrapKey);
6196
0
            if (Ks)
6197
0
                PK11_FreeSymKey(Ks);
6198
0
            asymWrapMechanism = masterWrapMech;
6199
0
            break;
6200
6201
0
        default:
6202
0
            rv = SECFailure;
6203
0
            break;
6204
0
    }
6205
6206
0
    if (rv != SECSuccess) {
6207
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6208
0
        goto loser;
6209
0
    }
6210
6211
0
    PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
6212
6213
0
    wswk.symWrapMechanism = masterWrapMech;
6214
0
    wswk.asymWrapMechanism = asymWrapMechanism;
6215
0
    wswk.wrapMechIndex = wrapMechIndex;
6216
0
    wswk.wrapKeyIndex = wrapKeyIndex;
6217
0
    wswk.wrappedSymKeyLen = wrappedKey.len;
6218
6219
    /* put it on disk. */
6220
    /* If the wrapping key for this KEA type has already been set,
6221
     * then abandon the value we just computed and
6222
     * use the one we got from the disk.
6223
     */
6224
0
    rv = ssl_SetWrappingKey(&wswk);
6225
0
    if (rv == SECSuccess) {
6226
        /* somebody beat us to it.  The original contents of our wswk
6227
         * has been replaced with the content on disk.  Now, discard
6228
         * the key we just created and unwrap this new one.
6229
         */
6230
0
        PK11_FreeSymKey(unwrappedWrappingKey);
6231
6232
0
        unwrappedWrappingKey =
6233
0
            ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
6234
0
                                     masterWrapMech, pwArg);
6235
0
    }
6236
6237
0
install:
6238
0
    if (unwrappedWrappingKey) {
6239
0
        *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
6240
0
    }
6241
6242
0
loser:
6243
0
done:
6244
0
    PZ_Unlock(symWrapKeysLock);
6245
0
    return unwrappedWrappingKey;
6246
0
}
6247
6248
#ifdef NSS_ALLOW_SSLKEYLOGFILE
6249
/* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
6250
 * bytes to |out|. */
6251
static void
6252
hexEncode(char *out, const unsigned char *in, unsigned int length)
6253
0
{
6254
0
    static const char hextable[] = "0123456789abcdef";
6255
0
    unsigned int i;
6256
6257
0
    for (i = 0; i < length; i++) {
6258
0
        *(out++) = hextable[in[i] >> 4];
6259
0
        *(out++) = hextable[in[i] & 15];
6260
0
    }
6261
0
}
6262
#endif
6263
6264
/* Called from ssl3_SendClientKeyExchange(). */
6265
static SECStatus
6266
ssl3_SendRSAClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
6267
0
{
6268
0
    PK11SymKey *pms = NULL;
6269
0
    SECStatus rv = SECFailure;
6270
0
    SECItem enc_pms = { siBuffer, NULL, 0 };
6271
0
    PRBool isTLS;
6272
6273
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6274
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6275
6276
    /* Generate the pre-master secret ...  */
6277
0
    ssl_GetSpecWriteLock(ss);
6278
0
    isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
6279
6280
0
    pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
6281
0
    ssl_ReleaseSpecWriteLock(ss);
6282
0
    if (pms == NULL) {
6283
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6284
0
        goto loser;
6285
0
    }
6286
6287
    /* Get the wrapped (encrypted) pre-master secret, enc_pms */
6288
0
    unsigned int svrPubKeyBits = SECKEY_PublicKeyStrengthInBits(svrPubKey);
6289
0
    enc_pms.len = (svrPubKeyBits + 7) / 8;
6290
    /* Check that the RSA key isn't larger than 8k bit. */
6291
0
    if (svrPubKeyBits > SSL_MAX_RSA_KEY_BITS) {
6292
0
        (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
6293
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6294
0
        goto loser;
6295
0
    }
6296
0
    enc_pms.data = (unsigned char *)PORT_Alloc(enc_pms.len);
6297
0
    if (enc_pms.data == NULL) {
6298
0
        goto loser; /* err set by PORT_Alloc */
6299
0
    }
6300
6301
    /* Wrap pre-master secret in server's public key. */
6302
0
    rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
6303
0
    if (rv != SECSuccess) {
6304
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6305
0
        goto loser;
6306
0
    }
6307
6308
0
#ifdef TRACE
6309
0
    if (ssl_trace >= 100) {
6310
0
        SECStatus extractRV = PK11_ExtractKeyValue(pms);
6311
0
        if (extractRV == SECSuccess) {
6312
0
            SECItem *keyData = PK11_GetKeyData(pms);
6313
0
            if (keyData && keyData->data && keyData->len) {
6314
0
                ssl_PrintBuf(ss, "Pre-Master Secret",
6315
0
                             keyData->data, keyData->len);
6316
0
            }
6317
0
        }
6318
0
    }
6319
0
#endif
6320
6321
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
6322
0
                                    isTLS ? enc_pms.len + 2
6323
0
                                          : enc_pms.len);
6324
0
    if (rv != SECSuccess) {
6325
0
        goto loser; /* err set by ssl3_AppendHandshake* */
6326
0
    }
6327
0
    if (isTLS) {
6328
0
        rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
6329
0
    } else {
6330
0
        rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
6331
0
    }
6332
0
    if (rv != SECSuccess) {
6333
0
        goto loser; /* err set by ssl3_AppendHandshake* */
6334
0
    }
6335
6336
0
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
6337
0
    PK11_FreeSymKey(pms);
6338
0
    pms = NULL;
6339
6340
0
    if (rv != SECSuccess) {
6341
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6342
0
        goto loser;
6343
0
    }
6344
6345
0
    rv = SECSuccess;
6346
6347
0
loser:
6348
0
    if (enc_pms.data != NULL) {
6349
0
        PORT_Free(enc_pms.data);
6350
0
    }
6351
0
    if (pms != NULL) {
6352
0
        PK11_FreeSymKey(pms);
6353
0
    }
6354
0
    return rv;
6355
0
}
6356
6357
/* DH shares need to be padded to the size of their prime.  Some implementations
6358
 * require this.  TLS 1.3 also requires this. */
6359
SECStatus
6360
ssl_AppendPaddedDHKeyShare(sslBuffer *buf, const SECKEYPublicKey *pubKey,
6361
                           PRBool appendLength)
6362
1.07k
{
6363
1.07k
    SECStatus rv;
6364
1.07k
    unsigned int pad = pubKey->u.dh.prime.len - pubKey->u.dh.publicValue.len;
6365
6366
1.07k
    if (appendLength) {
6367
1.07k
        rv = sslBuffer_AppendNumber(buf, pubKey->u.dh.prime.len, 2);
6368
1.07k
        if (rv != SECSuccess) {
6369
0
            return rv;
6370
0
        }
6371
1.07k
    }
6372
1.07k
    while (pad) {
6373
0
        rv = sslBuffer_AppendNumber(buf, 0, 1);
6374
0
        if (rv != SECSuccess) {
6375
0
            return rv;
6376
0
        }
6377
0
        --pad;
6378
0
    }
6379
1.07k
    rv = sslBuffer_Append(buf, pubKey->u.dh.publicValue.data,
6380
1.07k
                          pubKey->u.dh.publicValue.len);
6381
1.07k
    if (rv != SECSuccess) {
6382
0
        return rv;
6383
0
    }
6384
1.07k
    return SECSuccess;
6385
1.07k
}
6386
6387
/* Called from ssl3_SendClientKeyExchange(). */
6388
static SECStatus
6389
ssl3_SendDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
6390
0
{
6391
0
    PK11SymKey *pms = NULL;
6392
0
    SECStatus rv;
6393
0
    PRBool isTLS;
6394
0
    CK_MECHANISM_TYPE target;
6395
6396
0
    const ssl3DHParams *params;
6397
0
    ssl3DHParams customParams;
6398
0
    const sslNamedGroupDef *groupDef;
6399
0
    static const sslNamedGroupDef customGroupDef = {
6400
0
        ssl_grp_ffdhe_custom, 0, ssl_kea_dh, SEC_OID_TLS_DHE_CUSTOM, PR_FALSE
6401
0
    };
6402
0
    sslEphemeralKeyPair *keyPair = NULL;
6403
0
    SECKEYPublicKey *pubKey;
6404
0
    PRUint8 dhData[SSL_MAX_DH_KEY_BITS / 8 + 2];
6405
0
    sslBuffer dhBuf = SSL_BUFFER(dhData);
6406
6407
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6408
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6409
6410
0
    isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
6411
6412
    /* Copy DH parameters from server key */
6413
6414
0
    if (SECKEY_GetPublicKeyType(svrPubKey) != dhKey) {
6415
0
        PORT_SetError(SEC_ERROR_BAD_KEY);
6416
0
        return SECFailure;
6417
0
    }
6418
6419
    /* Work out the parameters. */
6420
0
    rv = ssl_ValidateDHENamedGroup(ss, &svrPubKey->u.dh.prime,
6421
0
                                   &svrPubKey->u.dh.base,
6422
0
                                   &groupDef, &params);
6423
0
    if (rv != SECSuccess) {
6424
        /* If we require named groups, we will have already validated the group
6425
         * in ssl_HandleDHServerKeyExchange() */
6426
0
        PORT_Assert(!ss->opt.requireDHENamedGroups &&
6427
0
                    !ss->xtnData.peerSupportsFfdheGroups);
6428
6429
0
        customParams.name = ssl_grp_ffdhe_custom;
6430
0
        customParams.prime.data = svrPubKey->u.dh.prime.data;
6431
0
        customParams.prime.len = svrPubKey->u.dh.prime.len;
6432
0
        customParams.base.data = svrPubKey->u.dh.base.data;
6433
0
        customParams.base.len = svrPubKey->u.dh.base.len;
6434
0
        params = &customParams;
6435
0
        groupDef = &customGroupDef;
6436
0
    }
6437
0
    ss->sec.keaGroup = groupDef;
6438
6439
0
    rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
6440
0
    if (rv != SECSuccess) {
6441
0
        ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
6442
0
        goto loser;
6443
0
    }
6444
0
    pubKey = keyPair->keys->pubKey;
6445
0
    PRINT_BUF(50, (ss, "DH public value:",
6446
0
                   pubKey->u.dh.publicValue.data,
6447
0
                   pubKey->u.dh.publicValue.len));
6448
6449
0
    if (isTLS)
6450
0
        target = CKM_TLS_MASTER_KEY_DERIVE_DH;
6451
0
    else
6452
0
        target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
6453
6454
    /* Determine the PMS */
6455
0
    pms = PK11_PubDerive(keyPair->keys->privKey, svrPubKey,
6456
0
                         PR_FALSE, NULL, NULL, CKM_DH_PKCS_DERIVE,
6457
0
                         target, CKA_DERIVE, 0, NULL);
6458
6459
0
    if (pms == NULL) {
6460
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6461
0
        goto loser;
6462
0
    }
6463
6464
    /* Note: send the DH share padded to avoid triggering bugs. */
6465
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
6466
0
                                    params->prime.len + 2);
6467
0
    if (rv != SECSuccess) {
6468
0
        goto loser; /* err set by ssl3_AppendHandshake* */
6469
0
    }
6470
0
    rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE);
6471
0
    if (rv != SECSuccess) {
6472
0
        goto loser; /* err set by ssl_AppendPaddedDHKeyShare */
6473
0
    }
6474
0
    rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
6475
0
    if (rv != SECSuccess) {
6476
0
        goto loser; /* err set by ssl3_AppendBufferToHandshake */
6477
0
    }
6478
6479
0
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
6480
0
    if (rv != SECSuccess) {
6481
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6482
0
        goto loser;
6483
0
    }
6484
6485
0
    sslBuffer_Clear(&dhBuf);
6486
0
    PK11_FreeSymKey(pms);
6487
0
    ssl_FreeEphemeralKeyPair(keyPair);
6488
0
    return SECSuccess;
6489
6490
0
loser:
6491
0
    if (pms)
6492
0
        PK11_FreeSymKey(pms);
6493
0
    if (keyPair)
6494
0
        ssl_FreeEphemeralKeyPair(keyPair);
6495
0
    sslBuffer_Clear(&dhBuf);
6496
0
    return SECFailure;
6497
0
}
6498
6499
/* Called from ssl3_HandleServerHelloDone(). */
6500
static SECStatus
6501
ssl3_SendClientKeyExchange(sslSocket *ss)
6502
0
{
6503
0
    SECKEYPublicKey *serverKey = NULL;
6504
0
    SECStatus rv = SECFailure;
6505
6506
0
    SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
6507
0
                SSL_GETPID(), ss->fd));
6508
6509
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6510
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6511
6512
0
    if (ss->sec.peerKey == NULL) {
6513
0
        serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
6514
0
        if (serverKey == NULL) {
6515
0
            ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
6516
0
            return SECFailure;
6517
0
        }
6518
0
    } else {
6519
0
        serverKey = ss->sec.peerKey;
6520
0
        ss->sec.peerKey = NULL; /* we're done with it now */
6521
0
    }
6522
6523
0
    ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
6524
0
    ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
6525
6526
0
    switch (ss->ssl3.hs.kea_def->exchKeyType) {
6527
0
        case ssl_kea_rsa:
6528
0
            rv = ssl3_SendRSAClientKeyExchange(ss, serverKey);
6529
0
            break;
6530
6531
0
        case ssl_kea_dh:
6532
0
            rv = ssl3_SendDHClientKeyExchange(ss, serverKey);
6533
0
            break;
6534
6535
0
        case ssl_kea_ecdh:
6536
0
            rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
6537
0
            break;
6538
6539
0
        default:
6540
0
            PORT_Assert(0);
6541
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6542
0
            break;
6543
0
    }
6544
6545
0
    SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
6546
0
                SSL_GETPID(), ss->fd));
6547
6548
0
    SECKEY_DestroyPublicKey(serverKey);
6549
0
    return rv; /* err code already set. */
6550
0
}
6551
6552
/* Used by ssl_PickSignatureScheme(). */
6553
PRBool
6554
ssl_CanUseSignatureScheme(SSLSignatureScheme scheme,
6555
                          const SSLSignatureScheme *peerSchemes,
6556
                          unsigned int peerSchemeCount,
6557
                          PRBool requireSha1,
6558
                          PRBool slotDoesPss)
6559
770
{
6560
770
    SSLHashType hashType;
6561
770
    unsigned int i;
6562
6563
    /* Skip RSA-PSS schemes when the certificate's private key slot does
6564
     * not support this signature mechanism. */
6565
770
    if (ssl_IsRsaPssSignatureScheme(scheme) && !slotDoesPss) {
6566
0
        return PR_FALSE;
6567
0
    }
6568
6569
770
    hashType = ssl_SignatureSchemeToHashType(scheme);
6570
770
    if (requireSha1 && (hashType != ssl_hash_sha1)) {
6571
0
        return PR_FALSE;
6572
0
    }
6573
6574
770
    if (!ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy)) {
6575
0
        return PR_FALSE;
6576
0
    }
6577
6578
4.47k
    for (i = 0; i < peerSchemeCount; i++) {
6579
3.95k
        if (peerSchemes[i] == scheme) {
6580
253
            return PR_TRUE;
6581
253
        }
6582
3.95k
    }
6583
517
    return PR_FALSE;
6584
770
}
6585
6586
SECStatus
6587
ssl_PrivateKeySupportsRsaPss(SECKEYPrivateKey *privKey, CERTCertificate *cert,
6588
                             void *pwarg, PRBool *supportsRsaPss)
6589
275
{
6590
275
    PK11SlotInfo *slot = NULL;
6591
275
    if (privKey) {
6592
275
        slot = PK11_GetSlotFromPrivateKey(privKey);
6593
275
    } else {
6594
0
        CK_OBJECT_HANDLE certID = PK11_FindObjectForCert(cert, pwarg, &slot);
6595
0
        if (certID == CK_INVALID_HANDLE) {
6596
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6597
0
            return SECFailure;
6598
0
        }
6599
0
    }
6600
275
    if (!slot) {
6601
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6602
0
        return SECFailure;
6603
0
    }
6604
275
    *supportsRsaPss = PK11_DoesMechanism(slot, auth_alg_defs[ssl_auth_rsa_pss]);
6605
275
    PK11_FreeSlot(slot);
6606
275
    return SECSuccess;
6607
275
}
6608
6609
SECStatus
6610
ssl_PickSignatureScheme(sslSocket *ss,
6611
                        CERTCertificate *cert,
6612
                        SECKEYPublicKey *pubKey,
6613
                        SECKEYPrivateKey *privKey,
6614
                        const SSLSignatureScheme *peerSchemes,
6615
                        unsigned int peerSchemeCount,
6616
                        PRBool requireSha1,
6617
                        SSLSignatureScheme *schemePtr)
6618
275
{
6619
275
    unsigned int i;
6620
275
    PRBool doesRsaPss;
6621
275
    PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
6622
275
    SECStatus rv;
6623
275
    SSLSignatureScheme scheme;
6624
275
    SECOidTag spkiOid;
6625
6626
    /* We can't require SHA-1 in TLS 1.3. */
6627
275
    PORT_Assert(!(requireSha1 && isTLS13));
6628
275
    if (!pubKey || !cert) {
6629
0
        PORT_Assert(0);
6630
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6631
0
        return SECFailure;
6632
0
    }
6633
275
    rv = ssl_PrivateKeySupportsRsaPss(privKey, cert, ss->pkcs11PinArg,
6634
275
                                      &doesRsaPss);
6635
275
    if (rv != SECSuccess) {
6636
0
        return SECFailure;
6637
0
    }
6638
6639
    /* If the certificate SPKI indicates a single scheme, don't search. */
6640
275
    rv = ssl_SignatureSchemeFromSpki(&cert->subjectPublicKeyInfo,
6641
275
                                     isTLS13, &scheme);
6642
275
    if (rv != SECSuccess) {
6643
0
        return SECFailure;
6644
0
    }
6645
275
    if (scheme != ssl_sig_none) {
6646
0
        if (!ssl_SignatureSchemeEnabled(ss, scheme) ||
6647
0
            !ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
6648
0
                                       requireSha1, doesRsaPss)) {
6649
0
            PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
6650
0
            return SECFailure;
6651
0
        }
6652
0
        *schemePtr = scheme;
6653
0
        return SECSuccess;
6654
0
    }
6655
6656
275
    spkiOid = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm);
6657
275
    if (spkiOid == SEC_OID_UNKNOWN) {
6658
0
        return SECFailure;
6659
0
    }
6660
6661
    /* Now we have to search based on the key type. Go through our preferred
6662
     * schemes in order and find the first that can be used. */
6663
1.84k
    for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
6664
1.82k
        scheme = ss->ssl3.signatureSchemes[i];
6665
6666
1.82k
        if (ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13) &&
6667
1.82k
            ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
6668
770
                                      requireSha1, doesRsaPss)) {
6669
253
            *schemePtr = scheme;
6670
253
            return SECSuccess;
6671
253
        }
6672
1.82k
    }
6673
6674
22
    PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
6675
22
    return SECFailure;
6676
275
}
6677
6678
static SECStatus
6679
ssl_PickFallbackSignatureScheme(sslSocket *ss, SECKEYPublicKey *pubKey)
6680
4.77k
{
6681
4.77k
    PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
6682
6683
4.77k
    switch (SECKEY_GetPublicKeyType(pubKey)) {
6684
4.53k
        case rsaKey:
6685
4.53k
            if (isTLS12) {
6686
4.53k
                ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1;
6687
4.53k
            } else {
6688
0
                ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1md5;
6689
0
            }
6690
4.53k
            break;
6691
244
        case ecKey:
6692
244
            ss->ssl3.hs.signatureScheme = ssl_sig_ecdsa_sha1;
6693
244
            break;
6694
0
        case dsaKey:
6695
0
            ss->ssl3.hs.signatureScheme = ssl_sig_dsa_sha1;
6696
0
            break;
6697
0
        default:
6698
0
            PORT_Assert(0);
6699
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
6700
0
            return SECFailure;
6701
4.77k
    }
6702
4.77k
    return SECSuccess;
6703
4.77k
}
6704
6705
/* ssl3_PickServerSignatureScheme selects a signature scheme for signing the
6706
 * handshake.  Most of this is determined by the key pair we are using.
6707
 * Prior to TLS 1.2, the MD5/SHA1 combination is always used. With TLS 1.2, a
6708
 * client may advertise its support for signature and hash combinations. */
6709
static SECStatus
6710
ssl3_PickServerSignatureScheme(sslSocket *ss)
6711
5.05k
{
6712
5.05k
    const sslServerCert *cert = ss->sec.serverCert;
6713
5.05k
    PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
6714
6715
5.05k
    if (!isTLS12 || !ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) {
6716
        /* If the client didn't provide any signature_algorithms extension then
6717
         * we can assume that they support SHA-1: RFC5246, Section 7.4.1.4.1. */
6718
4.77k
        return ssl_PickFallbackSignatureScheme(ss, cert->serverKeyPair->pubKey);
6719
4.77k
    }
6720
6721
    /* Sets error code, if needed. */
6722
275
    return ssl_PickSignatureScheme(ss, cert->serverCert,
6723
275
                                   cert->serverKeyPair->pubKey,
6724
275
                                   cert->serverKeyPair->privKey,
6725
275
                                   ss->xtnData.sigSchemes,
6726
275
                                   ss->xtnData.numSigSchemes,
6727
275
                                   PR_FALSE /* requireSha1 */,
6728
275
                                   &ss->ssl3.hs.signatureScheme);
6729
5.05k
}
6730
6731
SECStatus
6732
ssl_PickClientSignatureScheme(sslSocket *ss, CERTCertificate *clientCertificate,
6733
                              SECKEYPrivateKey *privKey,
6734
                              const SSLSignatureScheme *schemes,
6735
                              unsigned int numSchemes,
6736
                              SSLSignatureScheme *schemePtr)
6737
0
{
6738
0
    SECStatus rv;
6739
0
    PRBool isTLS13 = (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
6740
0
    SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(clientCertificate);
6741
6742
0
    PORT_Assert(pubKey);
6743
6744
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
6745
        /* We should have already checked that a signature scheme was
6746
         * listed in the request. */
6747
0
        PORT_Assert(schemes && numSchemes > 0);
6748
0
    }
6749
6750
0
    if (!isTLS13 &&
6751
0
        (SECKEY_GetPublicKeyType(pubKey) == rsaKey ||
6752
0
         SECKEY_GetPublicKeyType(pubKey) == dsaKey) &&
6753
0
        SECKEY_PublicKeyStrengthInBits(pubKey) <= 1024) {
6754
        /* If the key is a 1024-bit RSA or DSA key, assume conservatively that
6755
         * it may be unable to sign SHA-256 hashes. This is the case for older
6756
         * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and
6757
         * older, DSA key size is at most 1024 bits and the hash function must
6758
         * be SHA-1.
6759
         */
6760
0
        rv = ssl_PickSignatureScheme(ss, clientCertificate,
6761
0
                                     pubKey, privKey, schemes, numSchemes,
6762
0
                                     PR_TRUE /* requireSha1 */, schemePtr);
6763
0
        if (rv == SECSuccess) {
6764
0
            SECKEY_DestroyPublicKey(pubKey);
6765
0
            return SECSuccess;
6766
0
        }
6767
        /* If this fails, that's because the peer doesn't advertise SHA-1,
6768
         * so fall back to the full negotiation. */
6769
0
    }
6770
0
    rv = ssl_PickSignatureScheme(ss, clientCertificate,
6771
0
                                 pubKey, privKey, schemes, numSchemes,
6772
0
                                 PR_FALSE /* requireSha1 */, schemePtr);
6773
0
    SECKEY_DestroyPublicKey(pubKey);
6774
0
    return rv;
6775
0
}
6776
6777
/* Called from ssl3_HandleServerHelloDone(). */
6778
static SECStatus
6779
ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
6780
0
{
6781
0
    SECStatus rv = SECFailure;
6782
0
    PRBool isTLS12;
6783
0
    SECItem buf = { siBuffer, NULL, 0 };
6784
0
    SSL3Hashes hashes;
6785
0
    unsigned int len;
6786
0
    SSLHashType hashAlg;
6787
6788
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6789
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6790
6791
0
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
6792
0
                SSL_GETPID(), ss->fd));
6793
6794
0
    ssl_GetSpecReadLock(ss);
6795
6796
0
    if (ss->ssl3.hs.hashType == handshake_hash_record) {
6797
0
        hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
6798
0
    } else {
6799
        /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
6800
0
        hashAlg = ssl_hash_none;
6801
0
    }
6802
0
    if (ss->ssl3.hs.hashType == handshake_hash_record &&
6803
0
        hashAlg != ssl3_GetSuitePrfHash(ss)) {
6804
0
        rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
6805
0
                                       ss->ssl3.hs.messages.len,
6806
0
                                       hashAlg, &hashes);
6807
0
        if (rv != SECSuccess) {
6808
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
6809
0
        }
6810
0
    } else {
6811
0
        rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
6812
0
    }
6813
0
    ssl_ReleaseSpecReadLock(ss);
6814
0
    if (rv != SECSuccess) {
6815
0
        goto done; /* err code was set by ssl3_ComputeHandshakeHash(es) */
6816
0
    }
6817
6818
0
    isTLS12 = (PRBool)(ss->version == SSL_LIBRARY_VERSION_TLS_1_2);
6819
0
    PORT_Assert(ss->version <= SSL_LIBRARY_VERSION_TLS_1_2);
6820
6821
0
    rv = ssl3_SignHashes(ss, &hashes, privKey, &buf);
6822
0
    if (rv == SECSuccess && !ss->sec.isServer) {
6823
        /* Remember the info about the slot that did the signing.
6824
        ** Later, when doing an SSL restart handshake, verify this.
6825
        ** These calls are mere accessors, and can't fail.
6826
        */
6827
0
        PK11SlotInfo *slot;
6828
0
        sslSessionID *sid = ss->sec.ci.sid;
6829
6830
0
        slot = PK11_GetSlotFromPrivateKey(privKey);
6831
0
        sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
6832
0
        sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
6833
0
        sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
6834
0
        sid->u.ssl3.clAuthValid = PR_TRUE;
6835
0
        PK11_FreeSlot(slot);
6836
0
    }
6837
0
    if (rv != SECSuccess) {
6838
0
        goto done; /* err code was set by ssl3_SignHashes */
6839
0
    }
6840
6841
0
    len = buf.len + 2 + (isTLS12 ? 2 : 0);
6842
6843
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len);
6844
0
    if (rv != SECSuccess) {
6845
0
        goto done; /* error code set by AppendHandshake */
6846
0
    }
6847
0
    if (isTLS12) {
6848
0
        rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
6849
0
        if (rv != SECSuccess) {
6850
0
            goto done; /* err set by AppendHandshake. */
6851
0
        }
6852
0
    }
6853
0
    rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
6854
0
    if (rv != SECSuccess) {
6855
0
        goto done; /* error code set by AppendHandshake */
6856
0
    }
6857
6858
0
done:
6859
0
    if (buf.data)
6860
0
        PORT_Free(buf.data);
6861
0
    return rv;
6862
0
}
6863
6864
/* Once a cipher suite has been selected, make sure that the necessary secondary
6865
 * information is properly set. */
6866
SECStatus
6867
ssl3_SetupCipherSuite(sslSocket *ss, PRBool initHashes)
6868
6.06k
{
6869
6.06k
    ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
6870
6.06k
    if (!ss->ssl3.hs.suite_def) {
6871
0
        PORT_Assert(0);
6872
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6873
0
        return SECFailure;
6874
0
    }
6875
6876
6.06k
    ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg];
6877
6.06k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite;
6878
6879
6.06k
    if (!initHashes) {
6880
0
        return SECSuccess;
6881
0
    }
6882
    /* Now we have a cipher suite, initialize the handshake hashes. */
6883
6.06k
    return ssl3_InitHandshakeHashes(ss);
6884
6.06k
}
6885
6886
SECStatus
6887
ssl_ClientSetCipherSuite(sslSocket *ss, SSL3ProtocolVersion version,
6888
                         ssl3CipherSuite suite, PRBool initHashes)
6889
0
{
6890
0
    unsigned int i;
6891
0
    if (ssl3_config_match_init(ss) == 0) {
6892
0
        PORT_Assert(PR_FALSE);
6893
0
        return SECFailure;
6894
0
    }
6895
0
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
6896
0
        ssl3CipherSuiteCfg *suiteCfg = &ss->cipherSuites[i];
6897
0
        if (suite == suiteCfg->cipher_suite) {
6898
0
            SSLVersionRange vrange = { version, version };
6899
0
            if (!ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) {
6900
                /* config_match already checks whether the cipher suite is
6901
                 * acceptable for the version, but the check is repeated here
6902
                 * in order to give a more precise error code. */
6903
0
                if (!ssl3_CipherSuiteAllowedForVersionRange(suite, &vrange)) {
6904
0
                    PORT_SetError(SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION);
6905
0
                } else {
6906
0
                    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
6907
0
                }
6908
0
                return SECFailure;
6909
0
            }
6910
0
            break;
6911
0
        }
6912
0
    }
6913
0
    if (i >= ssl_V3_SUITES_IMPLEMENTED) {
6914
0
        PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
6915
0
        return SECFailure;
6916
0
    }
6917
6918
    /* Don't let the server change its mind. */
6919
0
    if (ss->ssl3.hs.helloRetry && suite != ss->ssl3.hs.cipher_suite) {
6920
0
        (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
6921
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
6922
0
        return SECFailure;
6923
0
    }
6924
6925
0
    ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)suite;
6926
0
    return ssl3_SetupCipherSuite(ss, initHashes);
6927
0
}
6928
6929
/* Check that session ID we received from the server, if any, matches our
6930
 * expectations, depending on whether we're in compat mode and whether we
6931
 * negotiated TLS 1.3+ or TLS 1.2-.
6932
 */
6933
static PRBool
6934
ssl_CheckServerSessionIdCorrectness(sslSocket *ss, SECItem *sidBytes)
6935
0
{
6936
0
    sslSessionID *sid = ss->sec.ci.sid;
6937
0
    PRBool sidMatch = PR_FALSE;
6938
0
    PRBool sentFakeSid = PR_FALSE;
6939
0
    PRBool sentRealSid = sid && sid->version < SSL_LIBRARY_VERSION_TLS_1_3;
6940
6941
    /* If attempting to resume a TLS 1.2 connection, the session ID won't be a
6942
     * fake. Check for the real value. */
6943
0
    if (sentRealSid) {
6944
0
        sidMatch = (sidBytes->len == sid->u.ssl3.sessionIDLength) &&
6945
0
                   (!sidBytes->len || PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len) == 0);
6946
0
    } else {
6947
        /* Otherwise, the session ID was a fake if TLS 1.3 compat mode is
6948
         * enabled.  If so, check for the fake value. */
6949
0
        sentFakeSid = ss->opt.enableTls13CompatMode && !IS_DTLS(ss);
6950
0
        if (sentFakeSid && sidBytes->len == SSL3_SESSIONID_BYTES) {
6951
0
            PRUint8 buf[SSL3_SESSIONID_BYTES];
6952
0
            ssl_MakeFakeSid(ss, buf);
6953
0
            sidMatch = PORT_Memcmp(buf, sidBytes->data, sidBytes->len) == 0;
6954
0
        }
6955
0
    }
6956
6957
    /* TLS 1.2: Session ID shouldn't match if we sent a fake. */
6958
0
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
6959
0
        if (sentFakeSid) {
6960
0
            return !sidMatch;
6961
0
        }
6962
0
        return PR_TRUE;
6963
0
    }
6964
6965
    /* TLS 1.3: We sent a session ID.  The server's should match. */
6966
0
    if (!IS_DTLS(ss) && (sentRealSid || sentFakeSid)) {
6967
0
        return sidMatch;
6968
0
    }
6969
6970
    /* TLS 1.3 (no SID)/DTLS 1.3: The server shouldn't send a session ID. */
6971
0
    return sidBytes->len == 0;
6972
0
}
6973
6974
static SECStatus
6975
ssl_CheckServerRandom(sslSocket *ss)
6976
0
{
6977
    /* Check the ServerHello.random per [RFC 8446 Section 4.1.3].
6978
     *
6979
     * TLS 1.3 clients receiving a ServerHello indicating TLS 1.2 or below
6980
     * MUST check that the last 8 bytes are not equal to either of these
6981
     * values.  TLS 1.2 clients SHOULD also check that the last 8 bytes are
6982
     * not equal to the second value if the ServerHello indicates TLS 1.1 or
6983
     * below.  If a match is found, the client MUST abort the handshake with
6984
     * an "illegal_parameter" alert.
6985
     */
6986
0
    SSL3ProtocolVersion checkVersion =
6987
0
        ss->ssl3.downgradeCheckVersion ? ss->ssl3.downgradeCheckVersion
6988
0
                                       : ss->vrange.max;
6989
6990
0
    if (checkVersion >= SSL_LIBRARY_VERSION_TLS_1_2 &&
6991
0
        checkVersion > ss->version) {
6992
        /* Both sections use the same sentinel region. */
6993
0
        PRUint8 *downgrade_sentinel =
6994
0
            ss->ssl3.hs.server_random +
6995
0
            SSL3_RANDOM_LENGTH - sizeof(tls12_downgrade_random);
6996
6997
0
        if (!PORT_Memcmp(downgrade_sentinel,
6998
0
                         tls12_downgrade_random,
6999
0
                         sizeof(tls12_downgrade_random)) ||
7000
0
            !PORT_Memcmp(downgrade_sentinel,
7001
0
                         tls1_downgrade_random,
7002
0
                         sizeof(tls1_downgrade_random))) {
7003
0
            return SECFailure;
7004
0
        }
7005
0
    }
7006
7007
0
    return SECSuccess;
7008
0
}
7009
7010
/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7011
 * ssl3 ServerHello message.
7012
 * Caller must hold Handshake and RecvBuf locks.
7013
 */
7014
static SECStatus
7015
ssl3_HandleServerHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
7016
0
{
7017
0
    PRUint32 cipher;
7018
0
    int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7019
0
    PRUint32 compression;
7020
0
    SECStatus rv;
7021
0
    SECItem sidBytes = { siBuffer, NULL, 0 };
7022
0
    PRBool isHelloRetry;
7023
0
    SSL3AlertDescription desc = illegal_parameter;
7024
0
    const PRUint8 *savedMsg = b;
7025
0
    const PRUint32 savedLength = length;
7026
7027
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
7028
0
                SSL_GETPID(), ss->fd));
7029
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7030
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7031
7032
0
    if (ss->ssl3.hs.ws != wait_server_hello) {
7033
0
        errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
7034
0
        desc = unexpected_message;
7035
0
        goto alert_loser;
7036
0
    }
7037
7038
    /* clean up anything left from previous handshake. */
7039
0
    if (ss->ssl3.clientCertChain != NULL) {
7040
0
        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
7041
0
        ss->ssl3.clientCertChain = NULL;
7042
0
    }
7043
0
    if (ss->ssl3.clientCertificate != NULL) {
7044
0
        CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7045
0
        ss->ssl3.clientCertificate = NULL;
7046
0
    }
7047
0
    if (ss->ssl3.clientPrivateKey != NULL) {
7048
0
        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7049
0
        ss->ssl3.clientPrivateKey = NULL;
7050
0
    }
7051
    // TODO(djackson) - Bob removed this. Why?
7052
0
    if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL) {
7053
0
        PR_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
7054
0
        ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
7055
0
        ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
7056
0
    }
7057
7058
    /* Note that if the server selects TLS 1.3, this will set the version to TLS
7059
     * 1.2.  We will amend that once all other fields have been read. */
7060
0
    rv = ssl_ClientReadVersion(ss, &b, &length, &ss->version);
7061
0
    if (rv != SECSuccess) {
7062
0
        goto loser; /* alert has been sent */
7063
0
    }
7064
7065
0
    rv = ssl3_ConsumeHandshake(
7066
0
        ss, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
7067
0
    if (rv != SECSuccess) {
7068
0
        goto loser; /* alert has been sent */
7069
0
    }
7070
0
    isHelloRetry = !PORT_Memcmp(ss->ssl3.hs.server_random,
7071
0
                                ssl_hello_retry_random, SSL3_RANDOM_LENGTH);
7072
7073
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
7074
0
    if (rv != SECSuccess) {
7075
0
        goto loser; /* alert has been sent */
7076
0
    }
7077
0
    if (sidBytes.len > SSL3_SESSIONID_BYTES) {
7078
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_0)
7079
0
            desc = decode_error;
7080
0
        goto alert_loser; /* malformed. */
7081
0
    }
7082
7083
    /* Read the cipher suite. */
7084
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &cipher, 2, &b, &length);
7085
0
    if (rv != SECSuccess) {
7086
0
        goto loser; /* alert has been sent */
7087
0
    }
7088
7089
    /* Compression method. */
7090
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &compression, 1, &b, &length);
7091
0
    if (rv != SECSuccess) {
7092
0
        goto loser; /* alert has been sent */
7093
0
    }
7094
0
    if (compression != ssl_compression_null) {
7095
0
        desc = illegal_parameter;
7096
0
        errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7097
0
        goto alert_loser;
7098
0
    }
7099
7100
    /* Parse extensions. */
7101
0
    if (length != 0) {
7102
0
        PRUint32 extensionLength;
7103
0
        rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
7104
0
        if (rv != SECSuccess) {
7105
0
            goto loser; /* alert already sent */
7106
0
        }
7107
0
        if (extensionLength != length) {
7108
0
            desc = decode_error;
7109
0
            goto alert_loser;
7110
0
        }
7111
0
        rv = ssl3_ParseExtensions(ss, &b, &length);
7112
0
        if (rv != SECSuccess) {
7113
0
            goto alert_loser; /* malformed */
7114
0
        }
7115
0
    }
7116
7117
    /* Read supported_versions if present. */
7118
0
    rv = tls13_ClientReadSupportedVersion(ss);
7119
0
    if (rv != SECSuccess) {
7120
0
        goto loser;
7121
0
    }
7122
7123
    /* RFC 9147. 5.2. 
7124
     * DTLS Handshake Message Format states the difference between the computation
7125
     * of the transcript if the version is DTLS1.2 or DTLS1.3.
7126
     *
7127
     * At this moment we are sure which version
7128
     * we are planning to use during the connection, so we can compute the hash. */
7129
0
    rv = ssl3_MaybeUpdateHashWithSavedRecord(ss);
7130
0
    if (rv != SECSuccess) {
7131
0
        goto loser;
7132
0
    }
7133
7134
0
    PORT_Assert(!SSL_ALL_VERSIONS_DISABLED(&ss->vrange));
7135
    /* Check that the version is within the configured range. */
7136
0
    if (ss->vrange.min > ss->version || ss->vrange.max < ss->version) {
7137
0
        desc = (ss->version > SSL_LIBRARY_VERSION_3_0)
7138
0
                   ? protocol_version
7139
0
                   : handshake_failure;
7140
0
        errCode = SSL_ERROR_UNSUPPORTED_VERSION;
7141
0
        goto alert_loser;
7142
0
    }
7143
7144
0
    if (isHelloRetry && ss->ssl3.hs.helloRetry) {
7145
0
        SSL_TRC(3, ("%d: SSL3[%d]: received a second hello_retry_request",
7146
0
                    SSL_GETPID(), ss->fd));
7147
0
        desc = unexpected_message;
7148
0
        errCode = SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST;
7149
0
        goto alert_loser;
7150
0
    }
7151
7152
    /* There are three situations in which the server must pick
7153
     * TLS 1.3.
7154
     *
7155
     * 1. We received HRR
7156
     * 2. We sent early app data
7157
     * 3. ECH was accepted (checked in MaybeHandleEchSignal)
7158
     *
7159
     * If we offered ECH and the server negotiated a lower version,
7160
     * authenticate to the public name for secure disablement.
7161
     *
7162
     */
7163
0
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
7164
0
        if (isHelloRetry || ss->ssl3.hs.helloRetry) {
7165
            /* SSL3_SendAlert() will uncache the SID. */
7166
0
            desc = illegal_parameter;
7167
0
            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7168
0
            goto alert_loser;
7169
0
        }
7170
0
        if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
7171
            /* SSL3_SendAlert() will uncache the SID. */
7172
0
            desc = illegal_parameter;
7173
0
            errCode = SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA;
7174
0
            goto alert_loser;
7175
0
        }
7176
0
    }
7177
7178
    /* Check that the server negotiated the same version as it did
7179
     * in the first handshake. This isn't really the best place for
7180
     * us to be getting this version number, but it's what we have.
7181
     * (1294697). */
7182
0
    if (ss->firstHsDone && (ss->version != ss->ssl3.crSpec->version)) {
7183
0
        desc = protocol_version;
7184
0
        errCode = SSL_ERROR_UNSUPPORTED_VERSION;
7185
0
        goto alert_loser;
7186
0
    }
7187
7188
0
    if (ss->opt.enableHelloDowngradeCheck) {
7189
0
        rv = ssl_CheckServerRandom(ss);
7190
0
        if (rv != SECSuccess) {
7191
0
            desc = illegal_parameter;
7192
0
            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7193
0
            goto alert_loser;
7194
0
        }
7195
0
    }
7196
7197
    /* Finally, now all the version-related checks have passed. */
7198
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
7199
    /* Update the write cipher spec to match the version. But not after
7200
     * HelloRetryRequest, because cwSpec might be a 0-RTT cipher spec,
7201
     * in which case this is a no-op. */
7202
0
    if (!ss->firstHsDone && !isHelloRetry) {
7203
0
        ssl_GetSpecWriteLock(ss);
7204
0
        ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
7205
0
        ssl_ReleaseSpecWriteLock(ss);
7206
0
    }
7207
7208
    /* Check that the session ID is as expected. */
7209
0
    if (!ssl_CheckServerSessionIdCorrectness(ss, &sidBytes)) {
7210
0
        desc = illegal_parameter;
7211
0
        errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7212
0
        goto alert_loser;
7213
0
    }
7214
7215
    /* Only initialize hashes if this isn't a Hello Retry. */
7216
0
    rv = ssl_ClientSetCipherSuite(ss, ss->version, cipher,
7217
0
                                  !isHelloRetry);
7218
0
    if (rv != SECSuccess) {
7219
0
        desc = illegal_parameter;
7220
0
        errCode = PORT_GetError();
7221
0
        goto alert_loser;
7222
0
    }
7223
7224
0
    dtls_ReceivedFirstMessageInFlight(ss);
7225
7226
0
    if (isHelloRetry) {
7227
0
        rv = tls13_HandleHelloRetryRequest(ss, savedMsg, savedLength);
7228
0
        if (rv != SECSuccess) {
7229
0
            goto loser;
7230
0
        }
7231
0
        return SECSuccess;
7232
0
    }
7233
7234
0
    rv = ssl3_HandleParsedExtensions(ss, ssl_hs_server_hello);
7235
0
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
7236
0
    if (rv != SECSuccess) {
7237
0
        goto alert_loser;
7238
0
    }
7239
7240
0
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_server_hello,
7241
0
                                  savedMsg, savedLength);
7242
0
    if (rv != SECSuccess) {
7243
0
        goto loser;
7244
0
    }
7245
7246
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
7247
0
        rv = tls13_HandleServerHelloPart2(ss, savedMsg, savedLength);
7248
0
        if (rv != SECSuccess) {
7249
0
            errCode = PORT_GetError();
7250
0
            goto loser;
7251
0
        }
7252
0
    } else {
7253
0
        rv = ssl3_HandleServerHelloPart2(ss, &sidBytes, &errCode);
7254
0
        if (rv != SECSuccess)
7255
0
            goto loser;
7256
0
    }
7257
7258
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
7259
0
    return SECSuccess;
7260
7261
0
alert_loser:
7262
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
7263
7264
0
loser:
7265
    /* Clean up the temporary pointer to the handshake buffer. */
7266
0
    ss->xtnData.signedCertTimestamps.len = 0;
7267
0
    ssl_MapLowLevelError(errCode);
7268
0
    return SECFailure;
7269
0
}
7270
7271
static SECStatus
7272
ssl3_UnwrapMasterSecretClient(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
7273
0
{
7274
0
    PK11SlotInfo *slot;
7275
0
    PK11SymKey *wrapKey;
7276
0
    CK_FLAGS keyFlags = 0;
7277
0
    SECItem wrappedMS = {
7278
0
        siBuffer,
7279
0
        sid->u.ssl3.keys.wrapped_master_secret,
7280
0
        sid->u.ssl3.keys.wrapped_master_secret_len
7281
0
    };
7282
7283
    /* unwrap master secret */
7284
0
    slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
7285
0
                             sid->u.ssl3.masterSlotID);
7286
0
    if (slot == NULL) {
7287
0
        return SECFailure;
7288
0
    }
7289
0
    if (!PK11_IsPresent(slot)) {
7290
0
        PK11_FreeSlot(slot);
7291
0
        return SECFailure;
7292
0
    }
7293
0
    wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
7294
0
                              sid->u.ssl3.masterWrapMech,
7295
0
                              sid->u.ssl3.masterWrapSeries,
7296
0
                              ss->pkcs11PinArg);
7297
0
    PK11_FreeSlot(slot);
7298
0
    if (wrapKey == NULL) {
7299
0
        return SECFailure;
7300
0
    }
7301
7302
0
    if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
7303
0
        keyFlags = CKF_SIGN | CKF_VERIFY;
7304
0
    }
7305
7306
0
    *ms = PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
7307
0
                                     NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
7308
0
                                     CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH, keyFlags);
7309
0
    PK11_FreeSymKey(wrapKey);
7310
0
    if (!*ms) {
7311
0
        return SECFailure;
7312
0
    }
7313
0
    return SECSuccess;
7314
0
}
7315
7316
static SECStatus
7317
ssl3_HandleServerHelloPart2(sslSocket *ss, const SECItem *sidBytes,
7318
                            int *retErrCode)
7319
0
{
7320
0
    SSL3AlertDescription desc = handshake_failure;
7321
0
    int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7322
0
    SECStatus rv;
7323
0
    PRBool sid_match;
7324
0
    sslSessionID *sid = ss->sec.ci.sid;
7325
7326
0
    if ((ss->opt.requireSafeNegotiation ||
7327
0
         (ss->firstHsDone && (ss->peerRequestedProtection ||
7328
0
                              ss->opt.enableRenegotiation ==
7329
0
                                  SSL_RENEGOTIATE_REQUIRES_XTN))) &&
7330
0
        !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7331
0
        desc = handshake_failure;
7332
0
        errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
7333
0
                                  : SSL_ERROR_UNSAFE_NEGOTIATION;
7334
0
        goto alert_loser;
7335
0
    }
7336
7337
    /* Any errors after this point are not "malformed" errors. */
7338
0
    desc = handshake_failure;
7339
7340
    /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
7341
     * key exchange algorithm. */
7342
0
    rv = ssl3_SetupBothPendingCipherSpecs(ss);
7343
0
    if (rv != SECSuccess) {
7344
0
        goto alert_loser; /* error code is set. */
7345
0
    }
7346
7347
    /* We may or may not have sent a session id, we may get one back or
7348
     * not and if so it may match the one we sent.
7349
     * Attempt to restore the master secret to see if this is so...
7350
     * Don't consider failure to find a matching SID an error.
7351
     */
7352
0
    sid_match = (PRBool)(sidBytes->len > 0 &&
7353
0
                         sidBytes->len ==
7354
0
                             sid->u.ssl3.sessionIDLength &&
7355
0
                         !PORT_Memcmp(sid->u.ssl3.sessionID,
7356
0
                                      sidBytes->data, sidBytes->len));
7357
7358
0
    if (sid_match) {
7359
0
        if (sid->version != ss->version ||
7360
0
            sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
7361
0
            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7362
0
            goto alert_loser;
7363
0
        }
7364
0
        do {
7365
0
            PK11SymKey *masterSecret;
7366
7367
            /* [draft-ietf-tls-session-hash-06; Section 5.3]
7368
             *
7369
             * o  If the original session did not use the "extended_master_secret"
7370
             *    extension but the new ServerHello contains the extension, the
7371
             *    client MUST abort the handshake.
7372
             */
7373
0
            if (!sid->u.ssl3.keys.extendedMasterSecretUsed &&
7374
0
                ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
7375
0
                errCode = SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET;
7376
0
                goto alert_loser;
7377
0
            }
7378
7379
            /*
7380
             *   o  If the original session used an extended master secret but the new
7381
             *      ServerHello does not contain the "extended_master_secret"
7382
             *      extension, the client SHOULD abort the handshake.
7383
             *
7384
             * TODO(ekr@rtfm.com): Add option to refuse to resume when EMS is not
7385
             * used at all (bug 1176526).
7386
             */
7387
0
            if (sid->u.ssl3.keys.extendedMasterSecretUsed &&
7388
0
                !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
7389
0
                errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
7390
0
                goto alert_loser;
7391
0
            }
7392
7393
0
            ss->sec.authType = sid->authType;
7394
0
            ss->sec.authKeyBits = sid->authKeyBits;
7395
0
            ss->sec.keaType = sid->keaType;
7396
0
            ss->sec.keaKeyBits = sid->keaKeyBits;
7397
0
            ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
7398
0
            ss->sec.signatureScheme = sid->sigScheme;
7399
7400
0
            rv = ssl3_UnwrapMasterSecretClient(ss, sid, &masterSecret);
7401
0
            if (rv != SECSuccess) {
7402
0
                break; /* not considered an error */
7403
0
            }
7404
7405
            /* Got a Match */
7406
0
            SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_hits);
7407
7408
            /* If we sent a session ticket, then this is a stateless resume. */
7409
0
            if (ss->xtnData.sentSessionTicketInClientHello)
7410
0
                SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_stateless_resumes);
7411
7412
0
            if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
7413
0
                ss->ssl3.hs.ws = wait_new_session_ticket;
7414
0
            else
7415
0
                ss->ssl3.hs.ws = wait_change_cipher;
7416
7417
0
            ss->ssl3.hs.isResuming = PR_TRUE;
7418
7419
            /* copy the peer cert from the SID */
7420
0
            if (sid->peerCert != NULL) {
7421
0
                ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
7422
0
            }
7423
7424
            /* We are re-using the old MS, so no need to derive again. */
7425
0
            rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE);
7426
0
            if (rv != SECSuccess) {
7427
0
                goto alert_loser; /* err code was set */
7428
0
            }
7429
0
            return SECSuccess;
7430
0
        } while (0);
7431
0
    }
7432
7433
0
    if (sid_match)
7434
0
        SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_not_ok);
7435
0
    else
7436
0
        SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_misses);
7437
7438
    /* We tried to resume a 1.3 session but the server negotiated 1.2. */
7439
0
    if (ss->statelessResume) {
7440
0
        PORT_Assert(sid->version == SSL_LIBRARY_VERSION_TLS_1_3);
7441
0
        PORT_Assert(ss->ssl3.hs.currentSecret);
7442
7443
        /* Reset resumption state, only used by 1.3 code. */
7444
0
        ss->statelessResume = PR_FALSE;
7445
7446
        /* Clear TLS 1.3 early data traffic key. */
7447
0
        PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
7448
0
        ss->ssl3.hs.currentSecret = NULL;
7449
0
    }
7450
7451
    /* throw the old one away */
7452
0
    sid->u.ssl3.keys.resumable = PR_FALSE;
7453
0
    ssl_UncacheSessionID(ss);
7454
0
    ssl_FreeSID(sid);
7455
7456
    /* get a new sid */
7457
0
    ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
7458
0
    if (sid == NULL) {
7459
0
        goto alert_loser; /* memory error is set. */
7460
0
    }
7461
7462
0
    sid->version = ss->version;
7463
0
    sid->u.ssl3.sessionIDLength = sidBytes->len;
7464
0
    if (sidBytes->len > 0) {
7465
0
        PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len);
7466
0
    }
7467
7468
0
    sid->u.ssl3.keys.extendedMasterSecretUsed =
7469
0
        ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
7470
7471
    /* Copy Signed Certificate Timestamps, if any. */
7472
0
    if (ss->xtnData.signedCertTimestamps.len) {
7473
0
        rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps,
7474
0
                              &ss->xtnData.signedCertTimestamps);
7475
0
        ss->xtnData.signedCertTimestamps.len = 0;
7476
0
        if (rv != SECSuccess)
7477
0
            goto loser;
7478
0
    }
7479
7480
0
    ss->ssl3.hs.isResuming = PR_FALSE;
7481
0
    if (ss->ssl3.hs.kea_def->authKeyType != ssl_auth_null) {
7482
        /* All current cipher suites other than those with ssl_auth_null (i.e.,
7483
         * (EC)DH_anon_* suites) require a certificate, so use that signal. */
7484
0
        ss->ssl3.hs.ws = wait_server_cert;
7485
0
    } else {
7486
        /* All the remaining cipher suites must be (EC)DH_anon_* and so
7487
         * must be ephemeral. Note, if we ever add PSK this might
7488
         * change. */
7489
0
        PORT_Assert(ss->ssl3.hs.kea_def->ephemeral);
7490
0
        ss->ssl3.hs.ws = wait_server_key;
7491
0
    }
7492
0
    return SECSuccess;
7493
7494
0
alert_loser:
7495
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
7496
7497
0
loser:
7498
0
    *retErrCode = errCode;
7499
0
    return SECFailure;
7500
0
}
7501
7502
static SECStatus
7503
ssl_HandleDHServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
7504
0
{
7505
0
    SECStatus rv;
7506
0
    int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
7507
0
    SSL3AlertDescription desc = illegal_parameter;
7508
0
    SSLHashType hashAlg;
7509
0
    PRBool isTLS = ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0;
7510
0
    SSLSignatureScheme sigScheme;
7511
7512
0
    SECItem dh_p = { siBuffer, NULL, 0 };
7513
0
    SECItem dh_g = { siBuffer, NULL, 0 };
7514
0
    SECItem dh_Ys = { siBuffer, NULL, 0 };
7515
0
    unsigned dh_p_bits;
7516
0
    unsigned dh_g_bits;
7517
0
    PRInt32 minDH = 0;
7518
0
    PRInt32 optval;
7519
7520
0
    SSL3Hashes hashes;
7521
0
    SECItem signature = { siBuffer, NULL, 0 };
7522
0
    PLArenaPool *arena = NULL;
7523
0
    SECKEYPublicKey *peerKey = NULL;
7524
7525
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
7526
0
    if (rv != SECSuccess) {
7527
0
        goto loser; /* malformed. */
7528
0
    }
7529
0
    rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS, &optval);
7530
0
    if ((rv == SECSuccess) && (optval & NSS_KEY_SIZE_POLICY_SSL_FLAG)) {
7531
0
        (void)NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH);
7532
0
    }
7533
7534
0
    if (minDH <= 0) {
7535
0
        minDH = SSL_DH_MIN_P_BITS;
7536
0
    }
7537
0
    dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p);
7538
0
    if (dh_p_bits < (unsigned)minDH) {
7539
0
        errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
7540
0
        goto alert_loser;
7541
0
    }
7542
0
    if (dh_p_bits > SSL_MAX_DH_KEY_BITS) {
7543
0
        errCode = SSL_ERROR_DH_KEY_TOO_LONG;
7544
0
        goto alert_loser;
7545
0
    }
7546
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
7547
0
    if (rv != SECSuccess) {
7548
0
        goto loser; /* malformed. */
7549
0
    }
7550
    /* Abort if dh_g is 0, 1, or obviously too big. */
7551
0
    dh_g_bits = SECKEY_BigIntegerBitLength(&dh_g);
7552
0
    if (dh_g_bits > dh_p_bits || dh_g_bits <= 1) {
7553
0
        goto alert_loser;
7554
0
    }
7555
0
    if (ss->opt.requireDHENamedGroups) {
7556
        /* If we're doing named groups, make sure it's good. */
7557
0
        rv = ssl_ValidateDHENamedGroup(ss, &dh_p, &dh_g, NULL, NULL);
7558
0
        if (rv != SECSuccess) {
7559
0
            errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
7560
0
            goto alert_loser;
7561
0
        }
7562
0
    }
7563
7564
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
7565
0
    if (rv != SECSuccess) {
7566
0
        goto loser; /* malformed. */
7567
0
    }
7568
0
    if (!ssl_IsValidDHEShare(&dh_p, &dh_Ys)) {
7569
0
        errCode = SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE;
7570
0
        goto alert_loser;
7571
0
    }
7572
7573
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
7574
0
        rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
7575
0
        if (rv != SECSuccess) {
7576
0
            goto loser; /* alert already sent */
7577
0
        }
7578
0
        rv = ssl_CheckSignatureSchemeConsistency(
7579
0
            ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo);
7580
0
        if (rv != SECSuccess) {
7581
0
            goto alert_loser;
7582
0
        }
7583
0
        hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
7584
0
    } else {
7585
        /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
7586
0
        hashAlg = ssl_hash_none;
7587
0
        sigScheme = ssl_sig_none;
7588
0
    }
7589
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
7590
0
    if (rv != SECSuccess) {
7591
0
        goto loser; /* malformed. */
7592
0
    }
7593
0
    if (length != 0) {
7594
0
        if (isTLS) {
7595
0
            desc = decode_error;
7596
0
        }
7597
0
        goto alert_loser; /* malformed. */
7598
0
    }
7599
7600
0
    PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
7601
0
    PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
7602
0
    PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
7603
7604
    /* failures after this point are not malformed handshakes. */
7605
    /* TLS: send decrypt_error if signature failed. */
7606
0
    desc = isTLS ? decrypt_error : handshake_failure;
7607
7608
    /*
7609
     * Check to make sure the hash is signed by right guy.
7610
     */
7611
0
    rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
7612
0
                               dh_p, dh_g, dh_Ys, PR_FALSE /* padY */);
7613
0
    if (rv != SECSuccess) {
7614
0
        errCode =
7615
0
            ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7616
0
        goto alert_loser;
7617
0
    }
7618
0
    rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signature);
7619
0
    if (rv != SECSuccess) {
7620
0
        errCode =
7621
0
            ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7622
0
        goto alert_loser;
7623
0
    }
7624
7625
    /*
7626
     * we really need to build a new key here because we can no longer
7627
     * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
7628
     * pkcs11 slots and ID's.
7629
     */
7630
0
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7631
0
    if (arena == NULL) {
7632
0
        errCode = SEC_ERROR_NO_MEMORY;
7633
0
        goto loser;
7634
0
    }
7635
7636
0
    peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
7637
0
    if (peerKey == NULL) {
7638
0
        errCode = SEC_ERROR_NO_MEMORY;
7639
0
        goto loser;
7640
0
    }
7641
7642
0
    peerKey->arena = arena;
7643
0
    peerKey->keyType = dhKey;
7644
0
    peerKey->pkcs11Slot = NULL;
7645
0
    peerKey->pkcs11ID = CK_INVALID_HANDLE;
7646
7647
0
    if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) ||
7648
0
        SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) ||
7649
0
        SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) {
7650
0
        errCode = SEC_ERROR_NO_MEMORY;
7651
0
        goto loser;
7652
0
    }
7653
0
    ss->sec.peerKey = peerKey;
7654
0
    return SECSuccess;
7655
7656
0
alert_loser:
7657
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
7658
0
loser:
7659
0
    if (arena) {
7660
0
        PORT_FreeArena(arena, PR_FALSE);
7661
0
    }
7662
0
    PORT_SetError(ssl_MapLowLevelError(errCode));
7663
0
    return SECFailure;
7664
0
}
7665
7666
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
7667
 * complete ssl3 ServerKeyExchange message.
7668
 * Caller must hold Handshake and RecvBuf locks.
7669
 */
7670
static SECStatus
7671
ssl3_HandleServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
7672
0
{
7673
0
    SECStatus rv;
7674
7675
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
7676
0
                SSL_GETPID(), ss->fd));
7677
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7678
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7679
7680
0
    if (ss->ssl3.hs.ws != wait_server_key) {
7681
0
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
7682
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
7683
0
        return SECFailure;
7684
0
    }
7685
7686
0
    switch (ss->ssl3.hs.kea_def->exchKeyType) {
7687
0
        case ssl_kea_dh:
7688
0
            rv = ssl_HandleDHServerKeyExchange(ss, b, length);
7689
0
            break;
7690
7691
0
        case ssl_kea_ecdh:
7692
0
            rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
7693
0
            break;
7694
7695
0
        default:
7696
0
            SSL3_SendAlert(ss, alert_fatal, handshake_failure);
7697
0
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
7698
0
            rv = SECFailure;
7699
0
            break;
7700
0
    }
7701
7702
0
    if (rv == SECSuccess) {
7703
0
        ss->ssl3.hs.ws = wait_cert_request;
7704
0
    }
7705
    /* All Handle*ServerKeyExchange functions set the error code. */
7706
0
    return rv;
7707
0
}
7708
7709
typedef struct dnameNode {
7710
    struct dnameNode *next;
7711
    SECItem name;
7712
} dnameNode;
7713
7714
/*
7715
 * Parse the ca_list structure in a CertificateRequest.
7716
 *
7717
 * Called from:
7718
 * ssl3_HandleCertificateRequest
7719
 * tls13_HandleCertificateRequest
7720
 */
7721
SECStatus
7722
ssl3_ParseCertificateRequestCAs(sslSocket *ss, PRUint8 **b, PRUint32 *length,
7723
                                CERTDistNames *ca_list)
7724
0
{
7725
0
    PRUint32 remaining;
7726
0
    int nnames = 0;
7727
0
    dnameNode *node;
7728
0
    SECStatus rv;
7729
0
    int i;
7730
7731
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 2, b, length);
7732
0
    if (rv != SECSuccess)
7733
0
        return SECFailure; /* malformed, alert has been sent */
7734
7735
0
    if (remaining > *length)
7736
0
        goto alert_loser;
7737
7738
0
    ca_list->head = node = PORT_ArenaZNew(ca_list->arena, dnameNode);
7739
0
    if (node == NULL)
7740
0
        goto no_mem;
7741
7742
0
    while (remaining > 0) {
7743
0
        PRUint32 len;
7744
7745
0
        if (remaining < 2)
7746
0
            goto alert_loser; /* malformed */
7747
7748
0
        rv = ssl3_ConsumeHandshakeNumber(ss, &len, 2, b, length);
7749
0
        if (rv != SECSuccess)
7750
0
            return SECFailure; /* malformed, alert has been sent */
7751
0
        if (len == 0 || remaining < len + 2)
7752
0
            goto alert_loser; /* malformed */
7753
7754
0
        remaining -= 2;
7755
0
        if (SECITEM_MakeItem(ca_list->arena, &node->name, *b, len) != SECSuccess) {
7756
0
            goto no_mem;
7757
0
        }
7758
0
        node->name.len = len;
7759
0
        *b += len;
7760
0
        *length -= len;
7761
0
        remaining -= len;
7762
0
        nnames++;
7763
0
        if (remaining <= 0)
7764
0
            break; /* success */
7765
7766
0
        node->next = PORT_ArenaZNew(ca_list->arena, dnameNode);
7767
0
        node = node->next;
7768
0
        if (node == NULL)
7769
0
            goto no_mem;
7770
0
    }
7771
7772
0
    ca_list->nnames = nnames;
7773
0
    ca_list->names = PORT_ArenaNewArray(ca_list->arena, SECItem, nnames);
7774
0
    if (nnames > 0 && ca_list->names == NULL)
7775
0
        goto no_mem;
7776
7777
0
    for (i = 0, node = (dnameNode *)ca_list->head;
7778
0
         i < nnames;
7779
0
         i++, node = node->next) {
7780
0
        ca_list->names[i] = node->name;
7781
0
    }
7782
7783
0
    return SECSuccess;
7784
7785
0
no_mem:
7786
0
    return SECFailure;
7787
7788
0
alert_loser:
7789
0
    (void)SSL3_SendAlert(ss, alert_fatal,
7790
0
                         ss->version < SSL_LIBRARY_VERSION_TLS_1_0 ? illegal_parameter
7791
0
                                                                   : decode_error);
7792
0
    PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
7793
0
    return SECFailure;
7794
0
}
7795
7796
SECStatus
7797
ssl_ParseSignatureSchemes(const sslSocket *ss, PLArenaPool *arena,
7798
                          SSLSignatureScheme **schemesOut,
7799
                          unsigned int *numSchemesOut,
7800
                          unsigned char **b, unsigned int *len)
7801
446
{
7802
446
    SECStatus rv;
7803
446
    SECItem buf;
7804
446
    SSLSignatureScheme *schemes = NULL;
7805
446
    unsigned int numSupported = 0;
7806
446
    unsigned int numRemaining = 0;
7807
446
    unsigned int max;
7808
7809
446
    rv = ssl3_ExtConsumeHandshakeVariable(ss, &buf, 2, b, len);
7810
446
    if (rv != SECSuccess) {
7811
3
        return SECFailure;
7812
3
    }
7813
    /* An odd-length value is invalid. */
7814
443
    if ((buf.len & 1) != 0) {
7815
1
        ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
7816
1
        return SECFailure;
7817
1
    }
7818
7819
    /* Let the caller decide whether to alert here. */
7820
442
    if (buf.len == 0) {
7821
1
        goto done;
7822
1
    }
7823
7824
    /* Limit the number of schemes we read. */
7825
441
    numRemaining = buf.len / 2;
7826
441
    max = PR_MIN(numRemaining, MAX_SIGNATURE_SCHEMES);
7827
7828
441
    if (arena) {
7829
0
        schemes = PORT_ArenaZNewArray(arena, SSLSignatureScheme, max);
7830
441
    } else {
7831
441
        schemes = PORT_ZNewArray(SSLSignatureScheme, max);
7832
441
    }
7833
441
    if (!schemes) {
7834
0
        ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
7835
0
        return SECFailure;
7836
0
    }
7837
7838
6.17k
    for (; numRemaining && numSupported < MAX_SIGNATURE_SCHEMES; --numRemaining) {
7839
5.73k
        PRUint32 tmp;
7840
5.73k
        rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2, &buf.data, &buf.len);
7841
5.73k
        if (rv != SECSuccess) {
7842
0
            PORT_Assert(0);
7843
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
7844
0
            return SECFailure;
7845
0
        }
7846
5.73k
        if (ssl_SignatureSchemeValid((SSLSignatureScheme)tmp, SEC_OID_UNKNOWN,
7847
5.73k
                                     (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)) {
7848
3.22k
            ;
7849
3.22k
            schemes[numSupported++] = (SSLSignatureScheme)tmp;
7850
3.22k
        }
7851
5.73k
    }
7852
7853
441
    if (!numSupported) {
7854
19
        if (!arena) {
7855
19
            PORT_Free(schemes);
7856
19
        }
7857
19
        schemes = NULL;
7858
19
    }
7859
7860
442
done:
7861
442
    *schemesOut = schemes;
7862
442
    *numSchemesOut = numSupported;
7863
442
    return SECSuccess;
7864
441
}
7865
7866
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
7867
 * a complete ssl3 Certificate Request message.
7868
 * Caller must hold Handshake and RecvBuf locks.
7869
 */
7870
static SECStatus
7871
ssl3_HandleCertificateRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
7872
0
{
7873
0
    PLArenaPool *arena = NULL;
7874
0
    PRBool isTLS = PR_FALSE;
7875
0
    PRBool isTLS12 = PR_FALSE;
7876
0
    int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
7877
0
    SECStatus rv;
7878
0
    SSL3AlertDescription desc = illegal_parameter;
7879
0
    SECItem cert_types = { siBuffer, NULL, 0 };
7880
0
    SSLSignatureScheme *signatureSchemes = NULL;
7881
0
    unsigned int signatureSchemeCount = 0;
7882
0
    CERTDistNames ca_list;
7883
7884
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
7885
0
                SSL_GETPID(), ss->fd));
7886
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7887
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7888
7889
0
    if (ss->ssl3.hs.ws != wait_cert_request) {
7890
0
        desc = unexpected_message;
7891
0
        errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
7892
0
        goto alert_loser;
7893
0
    }
7894
7895
0
    PORT_Assert(ss->ssl3.clientCertChain == NULL);
7896
0
    PORT_Assert(ss->ssl3.clientCertificate == NULL);
7897
0
    PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
7898
7899
0
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
7900
0
    isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
7901
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
7902
0
    if (rv != SECSuccess)
7903
0
        goto loser; /* malformed, alert has been sent */
7904
7905
0
    arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7906
0
    if (arena == NULL)
7907
0
        goto no_mem;
7908
7909
0
    if (isTLS12) {
7910
0
        rv = ssl_ParseSignatureSchemes(ss, arena,
7911
0
                                       &signatureSchemes,
7912
0
                                       &signatureSchemeCount,
7913
0
                                       &b, &length);
7914
0
        if (rv != SECSuccess) {
7915
0
            PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
7916
0
            goto loser; /* malformed, alert has been sent */
7917
0
        }
7918
0
        if (signatureSchemeCount == 0) {
7919
0
            errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
7920
0
            desc = handshake_failure;
7921
0
            goto alert_loser;
7922
0
        }
7923
0
    }
7924
7925
0
    rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, &ca_list);
7926
0
    if (rv != SECSuccess)
7927
0
        goto done; /* alert sent in ssl3_ParseCertificateRequestCAs */
7928
7929
0
    if (length != 0)
7930
0
        goto alert_loser; /* malformed */
7931
7932
0
    ss->ssl3.hs.ws = wait_hello_done;
7933
7934
0
    rv = ssl3_BeginHandleCertificateRequest(ss, signatureSchemes,
7935
0
                                            signatureSchemeCount, &ca_list);
7936
0
    if (rv != SECSuccess) {
7937
0
        PORT_Assert(0);
7938
0
        errCode = SEC_ERROR_LIBRARY_FAILURE;
7939
0
        desc = internal_error;
7940
0
        goto alert_loser;
7941
0
    }
7942
0
    goto done;
7943
7944
0
no_mem:
7945
0
    rv = SECFailure;
7946
0
    PORT_SetError(SEC_ERROR_NO_MEMORY);
7947
0
    goto done;
7948
7949
0
alert_loser:
7950
0
    if (isTLS && desc == illegal_parameter)
7951
0
        desc = decode_error;
7952
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
7953
0
loser:
7954
0
    PORT_SetError(errCode);
7955
0
    rv = SECFailure;
7956
0
done:
7957
0
    if (arena != NULL)
7958
0
        PORT_FreeArena(arena, PR_FALSE);
7959
0
    return rv;
7960
0
}
7961
7962
static void
7963
ssl3_ClientAuthCallbackOutcome(sslSocket *ss, SECStatus outcome)
7964
0
{
7965
0
    SECStatus rv;
7966
0
    switch (outcome) {
7967
0
        case SECSuccess:
7968
            /* check what the callback function returned */
7969
0
            if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
7970
                /* we are missing either the key or cert */
7971
0
                goto send_no_certificate;
7972
0
            }
7973
            /* Setting ssl3.clientCertChain non-NULL will cause
7974
             * ssl3_HandleServerHelloDone to call SendCertificate.
7975
             */
7976
0
            ss->ssl3.clientCertChain = CERT_CertChainFromCert(
7977
0
                ss->ssl3.clientCertificate,
7978
0
                certUsageSSLClient, PR_FALSE);
7979
0
            if (ss->ssl3.clientCertChain == NULL) {
7980
0
                goto send_no_certificate;
7981
0
            }
7982
0
            if (ss->ssl3.hs.hashType == handshake_hash_record ||
7983
0
                ss->ssl3.hs.hashType == handshake_hash_single) {
7984
0
                rv = ssl_PickClientSignatureScheme(ss,
7985
0
                                                   ss->ssl3.clientCertificate,
7986
0
                                                   ss->ssl3.clientPrivateKey,
7987
0
                                                   ss->ssl3.hs.clientAuthSignatureSchemes,
7988
0
                                                   ss->ssl3.hs.clientAuthSignatureSchemesLen,
7989
0
                                                   &ss->ssl3.hs.signatureScheme);
7990
0
                if (rv != SECSuccess) {
7991
                    /* This should only happen if our schemes changed or
7992
                     * if an RSA-PSS cert was selected, but the token
7993
                     * does not support PSS schemes.
7994
                     */
7995
0
                    goto send_no_certificate;
7996
0
                }
7997
0
            }
7998
0
            break;
7999
8000
0
        case SECFailure:
8001
0
        default:
8002
0
        send_no_certificate:
8003
0
            CERT_DestroyCertificate(ss->ssl3.clientCertificate);
8004
0
            SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
8005
0
            ss->ssl3.clientCertificate = NULL;
8006
0
            ss->ssl3.clientPrivateKey = NULL;
8007
0
            if (ss->ssl3.clientCertChain) {
8008
0
                CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
8009
0
                ss->ssl3.clientCertChain = NULL;
8010
0
            }
8011
8012
0
            if (ss->version > SSL_LIBRARY_VERSION_3_0) {
8013
0
                ss->ssl3.sendEmptyCert = PR_TRUE;
8014
0
            } else {
8015
0
                (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
8016
0
            }
8017
0
            break;
8018
0
    }
8019
8020
    /* Release the cached parameters */
8021
0
    PORT_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
8022
0
    ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
8023
0
    ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
8024
0
}
8025
8026
SECStatus
8027
ssl3_BeginHandleCertificateRequest(sslSocket *ss,
8028
                                   const SSLSignatureScheme *signatureSchemes,
8029
                                   unsigned int signatureSchemeCount,
8030
                                   CERTDistNames *ca_list)
8031
0
{
8032
0
    SECStatus rv;
8033
8034
0
    PR_ASSERT(!ss->ssl3.hs.clientCertificatePending);
8035
8036
    /* Should not send a client cert when (non-GREASE) ECH is rejected. */
8037
0
    if (ss->ssl3.hs.echHpkeCtx && !ss->ssl3.hs.echAccepted) {
8038
0
        PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn));
8039
0
        rv = SECFailure;
8040
0
    } else if (ss->getClientAuthData != NULL) {
8041
0
        PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
8042
0
                    ssl_preinfo_all);
8043
0
        PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
8044
0
        PORT_Assert(ss->ssl3.clientCertificate == NULL);
8045
0
        PORT_Assert(ss->ssl3.clientCertChain == NULL);
8046
8047
        /* Previously cached parameters should be empty */
8048
0
        PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemes == NULL);
8049
0
        PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemesLen == 0);
8050
        /*
8051
         * Peer signatures are only available while in the context of
8052
         * of a getClientAuthData callback. It is required for proper
8053
         * functioning of SSL_CertIsUsable and SSL_FilterClientCertListBySocket
8054
         * Calling these functions outside the context of a getClientAuthData
8055
         * callback will result in no filtering.*/
8056
8057
0
        ss->ssl3.hs.clientAuthSignatureSchemes = PORT_ZNewArray(SSLSignatureScheme, signatureSchemeCount);
8058
0
        PORT_Memcpy(ss->ssl3.hs.clientAuthSignatureSchemes, signatureSchemes, signatureSchemeCount * sizeof(SSLSignatureScheme));
8059
0
        ss->ssl3.hs.clientAuthSignatureSchemesLen = signatureSchemeCount;
8060
8061
0
        rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
8062
0
                                                 ss->fd, ca_list,
8063
0
                                                 &ss->ssl3.clientCertificate,
8064
0
                                                 &ss->ssl3.clientPrivateKey);
8065
0
    } else {
8066
0
        rv = SECFailure; /* force it to send a no_certificate alert */
8067
0
    }
8068
8069
0
    if (rv == SECWouldBlock) {
8070
        /* getClientAuthData needs more time (e.g. for user interaction) */
8071
8072
        /* The out parameters should not have changed. */
8073
0
        PORT_Assert(ss->ssl3.clientCertificate == NULL);
8074
0
        PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
8075
8076
        /* Mark the handshake as blocked */
8077
0
        ss->ssl3.hs.clientCertificatePending = PR_TRUE;
8078
8079
0
        rv = SECSuccess;
8080
0
    } else {
8081
        /* getClientAuthData returned SECSuccess or SECFailure immediately, handle accordingly */
8082
0
        ssl3_ClientAuthCallbackOutcome(ss, rv);
8083
0
        rv = SECSuccess;
8084
0
    }
8085
0
    return rv;
8086
0
}
8087
8088
/* Invoked by the application when client certificate selection is complete */
8089
SECStatus
8090
ssl3_ClientCertCallbackComplete(sslSocket *ss, SECStatus outcome, SECKEYPrivateKey *clientPrivateKey, CERTCertificate *clientCertificate)
8091
0
{
8092
0
    PORT_Assert(ss->ssl3.hs.clientCertificatePending);
8093
0
    ss->ssl3.hs.clientCertificatePending = PR_FALSE;
8094
8095
0
    ss->ssl3.clientCertificate = clientCertificate;
8096
0
    ss->ssl3.clientPrivateKey = clientPrivateKey;
8097
8098
0
    ssl3_ClientAuthCallbackOutcome(ss, outcome);
8099
8100
    /* Continue the handshake */
8101
0
    PORT_Assert(ss->ssl3.hs.restartTarget);
8102
0
    if (!ss->ssl3.hs.restartTarget) {
8103
0
        FATAL_ERROR(ss, PR_INVALID_STATE_ERROR, internal_error);
8104
0
        return SECFailure;
8105
0
    }
8106
0
    sslRestartTarget target = ss->ssl3.hs.restartTarget;
8107
0
    ss->ssl3.hs.restartTarget = NULL;
8108
0
    return target(ss);
8109
0
}
8110
8111
static SECStatus
8112
ssl3_CheckFalseStart(sslSocket *ss)
8113
0
{
8114
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8115
0
    PORT_Assert(!ss->ssl3.hs.authCertificatePending);
8116
0
    PORT_Assert(!ss->ssl3.hs.canFalseStart);
8117
8118
0
    if (!ss->canFalseStartCallback) {
8119
0
        SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start",
8120
0
                    SSL_GETPID(), ss->fd));
8121
0
    } else {
8122
0
        SECStatus rv;
8123
8124
0
        rv = ssl_CheckServerRandom(ss);
8125
0
        if (rv != SECSuccess) {
8126
0
            SSL_TRC(3, ("%d: SSL[%d]: no false start due to possible downgrade",
8127
0
                        SSL_GETPID(), ss->fd));
8128
0
            goto no_false_start;
8129
0
        }
8130
8131
        /* An attacker can control the selected ciphersuite so we only wish to
8132
         * do False Start in the case that the selected ciphersuite is
8133
         * sufficiently strong that the attack can gain no advantage.
8134
         * Therefore we always require an 80-bit cipher. */
8135
0
        ssl_GetSpecReadLock(ss);
8136
0
        PRBool weakCipher = ss->ssl3.cwSpec->cipherDef->secret_key_size < 10;
8137
0
        ssl_ReleaseSpecReadLock(ss);
8138
0
        if (weakCipher) {
8139
0
            SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher",
8140
0
                        SSL_GETPID(), ss->fd));
8141
0
            goto no_false_start;
8142
0
        }
8143
8144
0
        if (ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn)) {
8145
0
            SSL_TRC(3, ("%d: SSL[%d]: no false start due to lower version after ECH",
8146
0
                        SSL_GETPID(), ss->fd));
8147
0
            goto no_false_start;
8148
0
        }
8149
8150
0
        PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
8151
0
                    ssl_preinfo_all);
8152
0
        rv = (ss->canFalseStartCallback)(ss->fd,
8153
0
                                         ss->canFalseStartCallbackData,
8154
0
                                         &ss->ssl3.hs.canFalseStart);
8155
0
        if (rv == SECSuccess) {
8156
0
            SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s",
8157
0
                        SSL_GETPID(), ss->fd,
8158
0
                        ss->ssl3.hs.canFalseStart ? "TRUE"
8159
0
                                                  : "FALSE"));
8160
0
        } else {
8161
0
            SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)",
8162
0
                        SSL_GETPID(), ss->fd,
8163
0
                        PR_ErrorToName(PR_GetError())));
8164
0
        }
8165
0
        return rv;
8166
0
    }
8167
8168
0
no_false_start:
8169
0
    ss->ssl3.hs.canFalseStart = PR_FALSE;
8170
0
    return SECSuccess;
8171
0
}
8172
8173
PRBool
8174
ssl3_WaitingForServerSecondRound(sslSocket *ss)
8175
0
{
8176
0
    PRBool result;
8177
8178
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8179
8180
0
    switch (ss->ssl3.hs.ws) {
8181
0
        case wait_new_session_ticket:
8182
0
        case wait_change_cipher:
8183
0
        case wait_finished:
8184
0
            result = PR_TRUE;
8185
0
            break;
8186
0
        default:
8187
0
            result = PR_FALSE;
8188
0
            break;
8189
0
    }
8190
8191
0
    return result;
8192
0
}
8193
8194
static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
8195
8196
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
8197
 * a complete ssl3 Server Hello Done message.
8198
 * Caller must hold Handshake and RecvBuf locks.
8199
 */
8200
static SECStatus
8201
ssl3_HandleServerHelloDone(sslSocket *ss)
8202
0
{
8203
0
    SECStatus rv;
8204
0
    SSL3WaitState ws = ss->ssl3.hs.ws;
8205
8206
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
8207
0
                SSL_GETPID(), ss->fd));
8208
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
8209
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8210
8211
    /* Skipping CertificateRequest is always permitted. */
8212
0
    if (ws != wait_hello_done &&
8213
0
        ws != wait_cert_request) {
8214
0
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8215
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
8216
0
        return SECFailure;
8217
0
    }
8218
8219
0
    rv = ssl3_SendClientSecondRound(ss);
8220
8221
0
    return rv;
8222
0
}
8223
8224
/* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
8225
 *
8226
 * Caller must hold Handshake and RecvBuf locks.
8227
 */
8228
static SECStatus
8229
ssl3_SendClientSecondRound(sslSocket *ss)
8230
0
{
8231
0
    SECStatus rv;
8232
0
    PRBool sendClientCert;
8233
8234
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
8235
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8236
8237
0
    sendClientCert = !ss->ssl3.sendEmptyCert &&
8238
0
                     ss->ssl3.clientCertChain != NULL &&
8239
0
                     ss->ssl3.clientPrivateKey != NULL;
8240
8241
    /* We must wait for the server's certificate to be authenticated before
8242
     * sending the client certificate in order to disclosing the client
8243
     * certificate to an attacker that does not have a valid cert for the
8244
     * domain we are connecting to.
8245
     *
8246
     * During the initial handshake on a connection, we never send/receive
8247
     * application data until we have authenticated the server's certificate;
8248
     * i.e. we have fully authenticated the handshake before using the cipher
8249
     * specs agreed upon for that handshake. During a renegotiation, we may
8250
     * continue sending and receiving application data during the handshake
8251
     * interleaved with the handshake records. If we were to send the client's
8252
     * second round for a renegotiation before the server's certificate was
8253
     * authenticated, then the application data sent/received after this point
8254
     * would be using cipher spec that hadn't been authenticated. By waiting
8255
     * until the server's certificate has been authenticated during
8256
     * renegotiations, we ensure that renegotiations have the same property
8257
     * as initial handshakes; i.e. we have fully authenticated the handshake
8258
     * before using the cipher specs agreed upon for that handshake for
8259
     * application data.
8260
     */
8261
0
    if (ss->ssl3.hs.restartTarget) {
8262
0
        PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
8263
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
8264
0
        return SECFailure;
8265
0
    }
8266
    /* Check whether waiting for client certificate selection OR
8267
       waiting on server certificate verification AND
8268
       going to send client cert */
8269
0
    if ((ss->ssl3.hs.clientCertificatePending) ||
8270
0
        (ss->ssl3.hs.authCertificatePending && (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone))) {
8271
0
        SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"
8272
0
                    " certificate authentication is still pending.",
8273
0
                    SSL_GETPID(), ss->fd));
8274
0
        ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
8275
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
8276
0
        return SECFailure;
8277
0
    }
8278
8279
0
    ssl_GetXmitBufLock(ss); /*******************************/
8280
8281
0
    if (ss->ssl3.sendEmptyCert) {
8282
0
        ss->ssl3.sendEmptyCert = PR_FALSE;
8283
0
        rv = ssl3_SendEmptyCertificate(ss);
8284
        /* Don't send verify */
8285
0
        if (rv != SECSuccess) {
8286
0
            goto loser; /* error code is set. */
8287
0
        }
8288
0
    } else if (sendClientCert) {
8289
0
        rv = ssl3_SendCertificate(ss);
8290
0
        if (rv != SECSuccess) {
8291
0
            goto loser; /* error code is set. */
8292
0
        }
8293
0
    }
8294
8295
0
    rv = ssl3_SendClientKeyExchange(ss);
8296
0
    if (rv != SECSuccess) {
8297
0
        goto loser; /* err is set. */
8298
0
    }
8299
8300
0
    if (sendClientCert) {
8301
0
        rv = ssl3_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
8302
0
        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
8303
0
        ss->ssl3.clientPrivateKey = NULL;
8304
0
        if (rv != SECSuccess) {
8305
0
            goto loser; /* err is set. */
8306
0
        }
8307
0
    }
8308
8309
0
    rv = ssl3_SendChangeCipherSpecs(ss);
8310
0
    if (rv != SECSuccess) {
8311
0
        goto loser; /* err code was set. */
8312
0
    }
8313
8314
    /* This must be done after we've set ss->ssl3.cwSpec in
8315
     * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information
8316
     * from cwSpec. This must be done before we call ssl3_CheckFalseStart
8317
     * because the false start callback (if any) may need the information from
8318
     * the functions that depend on this being set.
8319
     */
8320
0
    ss->enoughFirstHsDone = PR_TRUE;
8321
8322
0
    if (!ss->firstHsDone) {
8323
0
        if (ss->opt.enableFalseStart) {
8324
0
            if (!ss->ssl3.hs.authCertificatePending) {
8325
                /* When we fix bug 589047, we will need to know whether we are
8326
                 * false starting before we try to flush the client second
8327
                 * round to the network. With that in mind, we purposefully
8328
                 * call ssl3_CheckFalseStart before calling ssl3_SendFinished,
8329
                 * which includes a call to ssl3_FlushHandshake, so that
8330
                 * no application develops a reliance on such flushing being
8331
                 * done before its false start callback is called.
8332
                 */
8333
0
                ssl_ReleaseXmitBufLock(ss);
8334
0
                rv = ssl3_CheckFalseStart(ss);
8335
0
                ssl_GetXmitBufLock(ss);
8336
0
                if (rv != SECSuccess) {
8337
0
                    goto loser;
8338
0
                }
8339
0
            } else {
8340
                /* The certificate authentication and the server's Finished
8341
                 * message are racing each other. If the certificate
8342
                 * authentication wins, then we will try to false start in
8343
                 * ssl3_AuthCertificateComplete.
8344
                 */
8345
0
                SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because"
8346
0
                            " certificate authentication is still pending.",
8347
0
                            SSL_GETPID(), ss->fd));
8348
0
            }
8349
0
        }
8350
0
    }
8351
8352
0
    rv = ssl3_SendFinished(ss, 0);
8353
0
    if (rv != SECSuccess) {
8354
0
        goto loser; /* err code was set. */
8355
0
    }
8356
8357
0
    ssl_ReleaseXmitBufLock(ss); /*******************************/
8358
8359
0
    if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
8360
0
        ss->ssl3.hs.ws = wait_new_session_ticket;
8361
0
    else
8362
0
        ss->ssl3.hs.ws = wait_change_cipher;
8363
8364
0
    PORT_Assert(ssl3_WaitingForServerSecondRound(ss));
8365
8366
0
    return SECSuccess;
8367
8368
0
loser:
8369
0
    ssl_ReleaseXmitBufLock(ss);
8370
0
    return rv;
8371
0
}
8372
8373
/*
8374
 * Routines used by servers
8375
 */
8376
static SECStatus
8377
ssl3_SendHelloRequest(sslSocket *ss)
8378
0
{
8379
0
    SECStatus rv;
8380
8381
0
    SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
8382
0
                ss->fd));
8383
8384
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8385
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8386
8387
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_hello_request, 0);
8388
0
    if (rv != SECSuccess) {
8389
0
        return rv; /* err set by AppendHandshake */
8390
0
    }
8391
0
    rv = ssl3_FlushHandshake(ss, 0);
8392
0
    if (rv != SECSuccess) {
8393
0
        return rv; /* error code set by ssl3_FlushHandshake */
8394
0
    }
8395
0
    ss->ssl3.hs.ws = wait_client_hello;
8396
0
    return SECSuccess;
8397
0
}
8398
8399
/*
8400
 * Called from:
8401
 *  ssl3_HandleClientHello()
8402
 */
8403
static SECComparison
8404
ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
8405
0
{
8406
0
    if (!name1 != !name2) {
8407
0
        return SECLessThan;
8408
0
    }
8409
0
    if (!name1) {
8410
0
        return SECEqual;
8411
0
    }
8412
0
    if (name1->type != name2->type) {
8413
0
        return SECLessThan;
8414
0
    }
8415
0
    return SECITEM_CompareItem(name1, name2);
8416
0
}
8417
8418
/* Sets memory error when returning NULL.
8419
 * Called from:
8420
 *  ssl3_SendClientHello()
8421
 *  ssl3_HandleServerHello()
8422
 *  ssl3_HandleClientHello()
8423
 *  ssl3_HandleV2ClientHello()
8424
 */
8425
sslSessionID *
8426
ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
8427
6.04k
{
8428
6.04k
    sslSessionID *sid;
8429
8430
6.04k
    sid = PORT_ZNew(sslSessionID);
8431
6.04k
    if (sid == NULL)
8432
0
        return sid;
8433
8434
6.04k
    if (is_server) {
8435
6.04k
        const SECItem *srvName;
8436
6.04k
        SECStatus rv = SECSuccess;
8437
8438
6.04k
        ssl_GetSpecReadLock(ss); /********************************/
8439
6.04k
        srvName = &ss->ssl3.hs.srvVirtName;
8440
6.04k
        if (srvName->len && srvName->data) {
8441
0
            rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
8442
0
        }
8443
6.04k
        ssl_ReleaseSpecReadLock(ss); /************************************/
8444
6.04k
        if (rv != SECSuccess) {
8445
0
            PORT_Free(sid);
8446
0
            return NULL;
8447
0
        }
8448
6.04k
    }
8449
6.04k
    sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
8450
6.04k
    sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url);
8451
6.04k
    sid->addr = ss->sec.ci.peer;
8452
6.04k
    sid->port = ss->sec.ci.port;
8453
6.04k
    sid->references = 1;
8454
6.04k
    sid->cached = never_cached;
8455
6.04k
    sid->version = ss->version;
8456
6.04k
    sid->sigScheme = ssl_sig_none;
8457
8458
6.04k
    sid->u.ssl3.keys.resumable = PR_TRUE;
8459
6.04k
    sid->u.ssl3.policy = SSL_ALLOWED;
8460
6.04k
    sid->u.ssl3.keys.extendedMasterSecretUsed = PR_FALSE;
8461
8462
6.04k
    if (is_server) {
8463
6.04k
        SECStatus rv;
8464
6.04k
        int pid = SSL_GETPID();
8465
8466
6.04k
        sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
8467
6.04k
        sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff;
8468
6.04k
        sid->u.ssl3.sessionID[1] = pid & 0xff;
8469
6.04k
        rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
8470
6.04k
                                 SSL3_SESSIONID_BYTES - 2);
8471
6.04k
        if (rv != SECSuccess) {
8472
0
            ssl_FreeSID(sid);
8473
0
            ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
8474
0
            return NULL;
8475
0
        }
8476
6.04k
    }
8477
6.04k
    return sid;
8478
6.04k
}
8479
8480
/* Called from:  ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
8481
static SECStatus
8482
ssl3_SendServerHelloSequence(sslSocket *ss)
8483
6.04k
{
8484
6.04k
    const ssl3KEADef *kea_def;
8485
6.04k
    SECStatus rv;
8486
8487
6.04k
    SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
8488
6.04k
                SSL_GETPID(), ss->fd));
8489
8490
6.04k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8491
6.04k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8492
8493
6.04k
    rv = ssl3_SendServerHello(ss);
8494
6.04k
    if (rv != SECSuccess) {
8495
0
        return rv; /* err code is set. */
8496
0
    }
8497
6.04k
    rv = ssl3_SendCertificate(ss);
8498
6.04k
    if (rv != SECSuccess) {
8499
0
        return rv; /* error code is set. */
8500
0
    }
8501
6.04k
    rv = ssl3_SendCertificateStatus(ss);
8502
6.04k
    if (rv != SECSuccess) {
8503
0
        return rv; /* error code is set. */
8504
0
    }
8505
    /* We have to do this after the call to ssl3_SendServerHello,
8506
     * because kea_def is set up by ssl3_SendServerHello().
8507
     */
8508
6.04k
    kea_def = ss->ssl3.hs.kea_def;
8509
8510
6.04k
    if (kea_def->ephemeral) {
8511
5.03k
        rv = ssl3_SendServerKeyExchange(ss);
8512
5.03k
        if (rv != SECSuccess) {
8513
0
            return rv; /* err code was set. */
8514
0
        }
8515
5.03k
    }
8516
8517
6.04k
    if (ss->opt.requestCertificate) {
8518
3.51k
        rv = ssl3_SendCertificateRequest(ss);
8519
3.51k
        if (rv != SECSuccess) {
8520
0
            return rv; /* err code is set. */
8521
0
        }
8522
3.51k
    }
8523
6.04k
    rv = ssl3_SendServerHelloDone(ss);
8524
6.04k
    if (rv != SECSuccess) {
8525
0
        return rv; /* err code is set. */
8526
0
    }
8527
8528
6.04k
    ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
8529
6.04k
                                                  : wait_client_key;
8530
6.04k
    return SECSuccess;
8531
6.04k
}
8532
8533
/* An empty TLS Renegotiation Info (RI) extension */
8534
static const PRUint8 emptyRIext[5] = { 0xff, 0x01, 0x00, 0x01, 0x00 };
8535
8536
static PRBool
8537
ssl3_KEASupportsTickets(const ssl3KEADef *kea_def)
8538
0
{
8539
0
    if (kea_def->signKeyType == dsaKey) {
8540
        /* TODO: Fix session tickets for DSS. The server code rejects the
8541
         * session ticket received from the client. Bug 1174677 */
8542
0
        return PR_FALSE;
8543
0
    }
8544
0
    return PR_TRUE;
8545
0
}
8546
8547
static PRBool
8548
ssl3_PeerSupportsCipherSuite(const SECItem *peerSuites, uint16_t suite)
8549
91.6k
{
8550
580k
    for (unsigned int i = 0; i + 1 < peerSuites->len; i += 2) {
8551
494k
        PRUint16 suite_i = (peerSuites->data[i] << 8) | peerSuites->data[i + 1];
8552
494k
        if (suite_i == suite) {
8553
6.06k
            return PR_TRUE;
8554
6.06k
        }
8555
494k
    }
8556
85.6k
    return PR_FALSE;
8557
91.6k
}
8558
8559
SECStatus
8560
ssl3_NegotiateCipherSuiteInner(sslSocket *ss, const SECItem *suites,
8561
                               PRUint16 version, PRUint16 *suitep)
8562
6.08k
{
8563
6.08k
    unsigned int i;
8564
6.08k
    SSLVersionRange vrange = { version, version };
8565
8566
    /* If we negotiated an External PSK and that PSK has a ciphersuite
8567
     * configured, we need to constrain our choice. If the client does
8568
     * not support it, negotiate a certificate auth suite and fall back.
8569
     */
8570
6.08k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
8571
6.08k
        ss->xtnData.selectedPsk &&
8572
6.08k
        ss->xtnData.selectedPsk->type == ssl_psk_external &&
8573
6.08k
        ss->xtnData.selectedPsk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL) {
8574
0
        PRUint16 pskSuite = ss->xtnData.selectedPsk->zeroRttSuite;
8575
0
        ssl3CipherSuiteCfg *pskSuiteCfg = ssl_LookupCipherSuiteCfgMutable(pskSuite,
8576
0
                                                                          ss->cipherSuites);
8577
0
        if (ssl3_config_match(pskSuiteCfg, ss->ssl3.policy, &vrange, ss) &&
8578
0
            ssl3_PeerSupportsCipherSuite(suites, pskSuite)) {
8579
0
            *suitep = pskSuite;
8580
0
            return SECSuccess;
8581
0
        }
8582
0
    }
8583
8584
148k
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
8585
148k
        ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
8586
148k
        if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
8587
56.8k
            continue;
8588
56.8k
        }
8589
91.6k
        if (!ssl3_PeerSupportsCipherSuite(suites, suite->cipher_suite)) {
8590
85.6k
            continue;
8591
85.6k
        }
8592
6.06k
        *suitep = suite->cipher_suite;
8593
6.06k
        return SECSuccess;
8594
91.6k
    }
8595
20
    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8596
20
    return SECFailure;
8597
6.08k
}
8598
8599
/* Select a cipher suite.
8600
**
8601
** NOTE: This suite selection algorithm should be the same as the one in
8602
** ssl3_HandleV2ClientHello().
8603
**
8604
** If TLS 1.0 is enabled, we could handle the case where the client
8605
** offered TLS 1.1 but offered only export cipher suites by choosing TLS
8606
** 1.0 and selecting one of those export cipher suites. However, a secure
8607
** TLS 1.1 client should not have export cipher suites enabled at all,
8608
** and a TLS 1.1 client should definitely not be offering *only* export
8609
** cipher suites. Therefore, we refuse to negotiate export cipher suites
8610
** with any client that indicates support for TLS 1.1 or higher when we
8611
** (the server) have TLS 1.1 support enabled.
8612
*/
8613
SECStatus
8614
ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites,
8615
                          PRBool initHashes)
8616
6.08k
{
8617
6.08k
    PRUint16 selected;
8618
6.08k
    SECStatus rv;
8619
8620
    /* Ensure that only valid cipher suites are enabled. */
8621
6.08k
    if (ssl3_config_match_init(ss) == 0) {
8622
        /* No configured cipher is both supported by PK11 and allowed.
8623
         * This is a configuration error, so report handshake failure.*/
8624
0
        FATAL_ERROR(ss, PORT_GetError(), handshake_failure);
8625
0
        return SECFailure;
8626
0
    }
8627
8628
6.08k
    rv = ssl3_NegotiateCipherSuiteInner(ss, suites, ss->version, &selected);
8629
6.08k
    if (rv != SECSuccess) {
8630
20
        return SECFailure;
8631
20
    }
8632
8633
6.06k
    ss->ssl3.hs.cipher_suite = selected;
8634
6.06k
    return ssl3_SetupCipherSuite(ss, initHashes);
8635
6.08k
}
8636
8637
/*
8638
 * Call the SNI config hook.
8639
 *
8640
 * Called from:
8641
 *   ssl3_HandleClientHello
8642
 *   tls13_HandleClientHelloPart2
8643
 */
8644
SECStatus
8645
ssl3_ServerCallSNICallback(sslSocket *ss)
8646
6.06k
{
8647
6.06k
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8648
6.06k
    SSL3AlertDescription desc = illegal_parameter;
8649
6.06k
    int ret = 0;
8650
8651
#ifdef SSL_SNI_ALLOW_NAME_CHANGE_2HS
8652
#error("No longer allowed to set SSL_SNI_ALLOW_NAME_CHANGE_2HS")
8653
#endif
8654
6.06k
    if (!ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
8655
6.06k
        if (ss->firstHsDone) {
8656
            /* Check that we don't have the name is current spec
8657
             * if this extension was not negotiated on the 2d hs. */
8658
0
            PRBool passed = PR_TRUE;
8659
0
            ssl_GetSpecReadLock(ss); /*******************************/
8660
0
            if (ss->ssl3.hs.srvVirtName.data) {
8661
0
                passed = PR_FALSE;
8662
0
            }
8663
0
            ssl_ReleaseSpecReadLock(ss); /***************************/
8664
0
            if (!passed) {
8665
0
                errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8666
0
                desc = handshake_failure;
8667
0
                goto alert_loser;
8668
0
            }
8669
0
        }
8670
6.06k
        return SECSuccess;
8671
6.06k
    }
8672
8673
0
    if (ss->sniSocketConfig)
8674
0
        do { /* not a loop */
8675
0
            PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
8676
0
                        ssl_preinfo_all);
8677
8678
0
            ret = SSL_SNI_SEND_ALERT;
8679
            /* If extension is negotiated, the len of names should > 0. */
8680
0
            if (ss->xtnData.sniNameArrSize) {
8681
                /* Calling client callback to reconfigure the socket. */
8682
0
                ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
8683
0
                                                        ss->xtnData.sniNameArr,
8684
0
                                                        ss->xtnData.sniNameArrSize,
8685
0
                                                        ss->sniSocketConfigArg);
8686
0
            }
8687
0
            if (ret <= SSL_SNI_SEND_ALERT) {
8688
                /* Application does not know the name or was not able to
8689
                 * properly reconfigure the socket. */
8690
0
                errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8691
0
                desc = unrecognized_name;
8692
0
                break;
8693
0
            } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
8694
0
                SECStatus rv = SECSuccess;
8695
0
                SECItem pwsNameBuf = { 0, NULL, 0 };
8696
0
                SECItem *pwsName = &pwsNameBuf;
8697
0
                SECItem *cwsName;
8698
8699
0
                ssl_GetSpecWriteLock(ss); /*******************************/
8700
0
                cwsName = &ss->ssl3.hs.srvVirtName;
8701
                /* not allow name change on the 2d HS */
8702
0
                if (ss->firstHsDone) {
8703
0
                    if (ssl3_ServerNameCompare(pwsName, cwsName)) {
8704
0
                        ssl_ReleaseSpecWriteLock(ss); /******************/
8705
0
                        errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8706
0
                        desc = handshake_failure;
8707
0
                        ret = SSL_SNI_SEND_ALERT;
8708
0
                        break;
8709
0
                    }
8710
0
                }
8711
0
                if (pwsName->data) {
8712
0
                    SECITEM_FreeItem(pwsName, PR_FALSE);
8713
0
                }
8714
0
                if (cwsName->data) {
8715
0
                    rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
8716
0
                }
8717
0
                ssl_ReleaseSpecWriteLock(ss); /**************************/
8718
0
                if (rv != SECSuccess) {
8719
0
                    errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8720
0
                    desc = internal_error;
8721
0
                    ret = SSL_SNI_SEND_ALERT;
8722
0
                    break;
8723
0
                }
8724
0
            } else if ((unsigned int)ret < ss->xtnData.sniNameArrSize) {
8725
                /* Application has configured new socket info. Lets check it
8726
                 * and save the name. */
8727
0
                SECStatus rv;
8728
0
                SECItem *name = &ss->xtnData.sniNameArr[ret];
8729
0
                SECItem *pwsName;
8730
8731
                /* get rid of the old name and save the newly picked. */
8732
                /* This code is protected by ssl3HandshakeLock. */
8733
0
                ssl_GetSpecWriteLock(ss); /*******************************/
8734
                /* not allow name change on the 2d HS */
8735
0
                if (ss->firstHsDone) {
8736
0
                    SECItem *cwsName = &ss->ssl3.hs.srvVirtName;
8737
0
                    if (ssl3_ServerNameCompare(name, cwsName)) {
8738
0
                        ssl_ReleaseSpecWriteLock(ss); /******************/
8739
0
                        errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8740
0
                        desc = handshake_failure;
8741
0
                        ret = SSL_SNI_SEND_ALERT;
8742
0
                        break;
8743
0
                    }
8744
0
                }
8745
0
                pwsName = &ss->ssl3.hs.srvVirtName;
8746
0
                if (pwsName->data) {
8747
0
                    SECITEM_FreeItem(pwsName, PR_FALSE);
8748
0
                }
8749
0
                rv = SECITEM_CopyItem(NULL, pwsName, name);
8750
0
                ssl_ReleaseSpecWriteLock(ss); /***************************/
8751
0
                if (rv != SECSuccess) {
8752
0
                    errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8753
0
                    desc = internal_error;
8754
0
                    ret = SSL_SNI_SEND_ALERT;
8755
0
                    break;
8756
0
                }
8757
                /* Need to tell the client that application has picked
8758
                 * the name from the offered list and reconfigured the socket.
8759
                 */
8760
0
                ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_server_name_xtn,
8761
0
                                             ssl_SendEmptyExtension);
8762
0
            } else {
8763
                /* Callback returned index outside of the boundary. */
8764
0
                PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize);
8765
0
                errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8766
0
                desc = internal_error;
8767
0
                ret = SSL_SNI_SEND_ALERT;
8768
0
                break;
8769
0
            }
8770
0
        } while (0);
8771
0
    ssl3_FreeSniNameArray(&ss->xtnData);
8772
0
    if (ret <= SSL_SNI_SEND_ALERT) {
8773
        /* desc and errCode should be set. */
8774
0
        goto alert_loser;
8775
0
    }
8776
8777
0
    return SECSuccess;
8778
8779
0
alert_loser:
8780
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
8781
0
    PORT_SetError(errCode);
8782
0
    return SECFailure;
8783
0
}
8784
8785
SECStatus
8786
ssl3_SelectServerCert(sslSocket *ss)
8787
6.06k
{
8788
6.06k
    const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
8789
6.06k
    PRCList *cursor;
8790
6.06k
    SECStatus rv;
8791
8792
    /* If the client didn't include the supported groups extension, assume just
8793
     * P-256 support and disable all the other ECDHE groups.  This also affects
8794
     * ECDHE group selection, but this function is called first. */
8795
6.06k
    if (!ssl3_ExtensionNegotiated(ss, ssl_supported_groups_xtn)) {
8796
4.02k
        unsigned int i;
8797
132k
        for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
8798
128k
            if (ss->namedGroupPreferences[i] &&
8799
128k
                ss->namedGroupPreferences[i]->keaType == ssl_kea_ecdh &&
8800
128k
                ss->namedGroupPreferences[i]->name != ssl_grp_ec_secp256r1) {
8801
12.0k
                ss->namedGroupPreferences[i] = NULL;
8802
12.0k
            }
8803
128k
        }
8804
4.02k
    }
8805
8806
    /* This picks the first certificate that has:
8807
     * a) the right authentication method, and
8808
     * b) the right named curve (EC only)
8809
     *
8810
     * We might want to do some sort of ranking here later.  For now, it's all
8811
     * based on what order they are configured in. */
8812
6.06k
    for (cursor = PR_NEXT_LINK(&ss->serverCerts);
8813
11.6k
         cursor != &ss->serverCerts;
8814
11.6k
         cursor = PR_NEXT_LINK(cursor)) {
8815
11.6k
        sslServerCert *cert = (sslServerCert *)cursor;
8816
11.6k
        if (kea_def->authKeyType == ssl_auth_rsa_sign) {
8817
            /* We consider PSS certificates here as well for TLS 1.2. */
8818
9.52k
            if (!SSL_CERT_IS(cert, ssl_auth_rsa_sign) &&
8819
9.52k
                (!SSL_CERT_IS(cert, ssl_auth_rsa_pss) ||
8820
4.76k
                 ss->version < SSL_LIBRARY_VERSION_TLS_1_2)) {
8821
4.76k
                continue;
8822
4.76k
            }
8823
9.52k
        } else {
8824
2.12k
            if (!SSL_CERT_IS(cert, kea_def->authKeyType)) {
8825
826
                continue;
8826
826
            }
8827
1.29k
            if (SSL_CERT_IS_EC(cert) &&
8828
1.29k
                !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
8829
0
                continue;
8830
0
            }
8831
1.29k
        }
8832
8833
        /* Found one. */
8834
6.06k
        ss->sec.serverCert = cert;
8835
6.06k
        ss->sec.authKeyBits = cert->serverKeyBits;
8836
8837
        /* Don't pick a signature scheme if we aren't going to use it. */
8838
6.06k
        if (kea_def->signKeyType == nullKey) {
8839
1.00k
            ss->sec.authType = kea_def->authKeyType;
8840
1.00k
            return SECSuccess;
8841
1.00k
        }
8842
8843
5.05k
        rv = ssl3_PickServerSignatureScheme(ss);
8844
5.05k
        if (rv != SECSuccess) {
8845
22
            return SECFailure;
8846
22
        }
8847
5.03k
        ss->sec.authType =
8848
5.03k
            ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme);
8849
5.03k
        return SECSuccess;
8850
5.05k
    }
8851
8852
0
    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8853
0
    return SECFailure;
8854
6.06k
}
8855
8856
static SECStatus
8857
ssl_GenerateServerRandom(sslSocket *ss)
8858
6.04k
{
8859
6.04k
    SECStatus rv;
8860
6.04k
    PRUint8 *downgradeSentinel;
8861
8862
6.04k
    rv = ssl3_GetNewRandom(ss->ssl3.hs.server_random);
8863
6.04k
    if (rv != SECSuccess) {
8864
0
        return SECFailure;
8865
0
    }
8866
8867
6.04k
    if (ss->version == ss->vrange.max) {
8868
6.04k
        return SECSuccess;
8869
6.04k
    }
8870
8871
    /*
8872
     * [RFC 8446 Section 4.1.3].
8873
     *
8874
     * TLS 1.3 servers which negotiate TLS 1.2 or below in response to a
8875
     * ClientHello MUST set the last 8 bytes of their Random value specially in
8876
     * their ServerHello.
8877
     *
8878
     * If negotiating TLS 1.2, TLS 1.3 servers MUST set the last 8 bytes of
8879
     * their Random value to the bytes:
8880
     *
8881
     *   44 4F 57 4E 47 52 44 01
8882
     *
8883
     * If negotiating TLS 1.1 or below, TLS 1.3 servers MUST, and TLS 1.2
8884
     * servers SHOULD, set the last 8 bytes of their ServerHello.Random value to
8885
     * the bytes:
8886
     *
8887
     *   44 4F 57 4E 47 52 44 00
8888
     */
8889
0
    downgradeSentinel =
8890
0
        ss->ssl3.hs.server_random +
8891
0
        SSL3_RANDOM_LENGTH - sizeof(tls12_downgrade_random);
8892
0
    if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_2) {
8893
0
        switch (ss->version) {
8894
0
            case SSL_LIBRARY_VERSION_TLS_1_2:
8895
                /* vrange.max > 1.2, since we didn't early exit above. */
8896
0
                PORT_Memcpy(downgradeSentinel,
8897
0
                            tls12_downgrade_random, sizeof(tls12_downgrade_random));
8898
0
                break;
8899
0
            case SSL_LIBRARY_VERSION_TLS_1_1:
8900
0
            case SSL_LIBRARY_VERSION_TLS_1_0:
8901
0
                PORT_Memcpy(downgradeSentinel,
8902
0
                            tls1_downgrade_random, sizeof(tls1_downgrade_random));
8903
0
                break;
8904
0
            default:
8905
                /* Do not change random. */
8906
0
                break;
8907
0
        }
8908
0
    }
8909
8910
0
    return SECSuccess;
8911
0
}
8912
8913
SECStatus
8914
ssl3_HandleClientHelloPreamble(sslSocket *ss, PRUint8 **b, PRUint32 *length, SECItem *sidBytes,
8915
                               SECItem *cookieBytes, SECItem *suites, SECItem *comps)
8916
7.50k
{
8917
7.50k
    SECStatus rv;
8918
7.50k
    PRUint32 tmp;
8919
7.50k
    rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
8920
7.50k
    if (rv != SECSuccess) {
8921
4
        return SECFailure; /* malformed, alert already sent */
8922
4
    }
8923
8924
    /* Translate the version. */
8925
7.50k
    if (IS_DTLS(ss)) {
8926
7.50k
        ss->clientHelloVersion = dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
8927
7.50k
    } else {
8928
0
        ss->clientHelloVersion = (SSL3ProtocolVersion)tmp;
8929
0
    }
8930
8931
    /* Grab the client random data. */
8932
7.50k
    rv = ssl3_ConsumeHandshake(
8933
7.50k
        ss, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, b, length);
8934
7.50k
    if (rv != SECSuccess) {
8935
28
        return SECFailure; /* malformed */
8936
28
    }
8937
8938
    /* Grab the client's SID, if present. */
8939
7.47k
    rv = ssl3_ConsumeHandshakeVariable(ss, sidBytes, 1, b, length);
8940
    /* Check that the SID has the format: opaque legacy_session_id<0..32>, as
8941
     * specified in RFC8446, Section 4.1.2. */
8942
7.47k
    if (rv != SECSuccess || sidBytes->len > SSL3_SESSIONID_BYTES) {
8943
17
        return SECFailure; /* malformed */
8944
17
    }
8945
8946
    /* Grab the client's cookie, if present. It is checked after version negotiation. */
8947
7.45k
    if (IS_DTLS(ss)) {
8948
7.45k
        rv = ssl3_ConsumeHandshakeVariable(ss, cookieBytes, 1, b, length);
8949
7.45k
        if (rv != SECSuccess) {
8950
11
            return SECFailure; /* malformed */
8951
11
        }
8952
7.45k
    }
8953
8954
    /* Grab the list of cipher suites. */
8955
7.44k
    rv = ssl3_ConsumeHandshakeVariable(ss, suites, 2, b, length);
8956
7.44k
    if (rv != SECSuccess) {
8957
19
        return SECFailure; /* malformed */
8958
19
    }
8959
8960
    /* Grab the list of compression methods. */
8961
7.42k
    rv = ssl3_ConsumeHandshakeVariable(ss, comps, 1, b, length);
8962
7.42k
    if (rv != SECSuccess) {
8963
5
        return SECFailure; /* malformed */
8964
5
    }
8965
7.42k
    return SECSuccess;
8966
7.42k
}
8967
8968
static SECStatus
8969
ssl3_ValidatePreambleWithVersion(sslSocket *ss, const SECItem *sidBytes, const SECItem *comps,
8970
                                 const SECItem *cookieBytes)
8971
7.36k
{
8972
7.36k
    SECStatus rv;
8973
7.36k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
8974
0
        if (sidBytes->len > 0 && !IS_DTLS(ss)) {
8975
0
            SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
8976
0
            rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.fakeSid, sidBytes);
8977
0
            if (rv != SECSuccess) {
8978
0
                FATAL_ERROR(ss, PORT_GetError(), internal_error);
8979
0
                return SECFailure;
8980
0
            }
8981
0
        }
8982
8983
        /* TLS 1.3 requires that compression include only null. */
8984
0
        if (comps->len != 1 || comps->data[0] != ssl_compression_null) {
8985
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
8986
0
            return SECFailure;
8987
0
        }
8988
8989
        /* receivedCcs is only valid if we sent an HRR. */
8990
0
        if (ss->ssl3.hs.receivedCcs && !ss->ssl3.hs.helloRetry) {
8991
0
            FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message);
8992
0
            return SECFailure;
8993
0
        }
8994
8995
        /* A DTLS 1.3-only client MUST set the legacy_cookie field to zero length.
8996
         * If a DTLS 1.3 ClientHello is received with any other value in this field,
8997
         * the server MUST abort the handshake with an "illegal_parameter" alert. */
8998
0
        if (IS_DTLS(ss) && cookieBytes->len != 0) {
8999
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
9000
0
            return SECFailure;
9001
0
        }
9002
7.36k
    } else {
9003
        /* ECH not possible here. */
9004
7.36k
        ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
9005
9006
        /* HRR and ECH are TLS1.3-only. We ignore the Cookie extension here. */
9007
7.36k
        if (ss->ssl3.hs.helloRetry) {
9008
0
            FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, protocol_version);
9009
0
            return SECFailure;
9010
0
        }
9011
9012
        /* receivedCcs is only valid if we sent an HRR. */
9013
7.36k
        if (ss->ssl3.hs.receivedCcs) {
9014
0
            FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message);
9015
0
            return SECFailure;
9016
0
        }
9017
9018
        /* TLS versions prior to 1.3 must include null somewhere. */
9019
7.36k
        if (comps->len < 1 ||
9020
7.36k
            !memchr(comps->data, ssl_compression_null, comps->len)) {
9021
3
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
9022
3
            return SECFailure;
9023
3
        }
9024
9025
        /* We never send cookies in DTLS 1.2. */
9026
7.36k
        if (IS_DTLS(ss) && cookieBytes->len != 0) {
9027
2
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
9028
2
            return SECFailure;
9029
2
        }
9030
7.36k
    }
9031
9032
7.36k
    return SECSuccess;
9033
7.36k
}
9034
9035
/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9036
 * ssl3 Client Hello message.
9037
 * Caller must hold Handshake and RecvBuf locks.
9038
 */
9039
static SECStatus
9040
ssl3_HandleClientHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
9041
7.50k
{
9042
7.50k
    sslSessionID *sid = NULL;
9043
7.50k
    unsigned int i;
9044
7.50k
    SECStatus rv;
9045
7.50k
    PRUint32 extensionLength;
9046
7.50k
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9047
7.50k
    SSL3AlertDescription desc = illegal_parameter;
9048
7.50k
    SSL3AlertLevel level = alert_fatal;
9049
7.50k
    TLSExtension *versionExtension;
9050
7.50k
    SECItem sidBytes = { siBuffer, NULL, 0 };
9051
7.50k
    SECItem cookieBytes = { siBuffer, NULL, 0 };
9052
7.50k
    SECItem suites = { siBuffer, NULL, 0 };
9053
7.50k
    SECItem comps = { siBuffer, NULL, 0 };
9054
7.50k
    SECItem *echInner = NULL;
9055
7.50k
    PRBool isTLS13;
9056
7.50k
    const PRUint8 *savedMsg = b;
9057
7.50k
    const PRUint32 savedLen = length;
9058
9059
7.50k
    SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
9060
7.50k
                SSL_GETPID(), ss->fd));
9061
9062
7.50k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
9063
7.50k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9064
7.50k
    ss->ssl3.hs.preliminaryInfo = 0;
9065
9066
7.50k
    if (!ss->sec.isServer ||
9067
7.50k
        (ss->ssl3.hs.ws != wait_client_hello &&
9068
7.50k
         ss->ssl3.hs.ws != idle_handshake)) {
9069
1
        desc = unexpected_message;
9070
1
        errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
9071
1
        goto alert_loser;
9072
1
    }
9073
7.50k
    if (ss->ssl3.hs.ws == idle_handshake) {
9074
        /* Refuse re-handshake when we have already negotiated TLS 1.3. */
9075
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
9076
0
            desc = unexpected_message;
9077
0
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9078
0
            goto alert_loser;
9079
0
        }
9080
0
        if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
9081
0
            desc = no_renegotiation;
9082
0
            level = alert_warning;
9083
0
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9084
0
            goto alert_loser;
9085
0
        }
9086
0
    }
9087
9088
    /* We should always be in a fresh state. */
9089
7.50k
    SSL_ASSERT_HASHES_EMPTY(ss);
9090
9091
    /* Get peer name of client */
9092
7.50k
    rv = ssl_GetPeerInfo(ss);
9093
7.50k
    if (rv != SECSuccess) {
9094
0
        return rv; /* error code is set. */
9095
0
    }
9096
9097
    /* We might be starting session renegotiation in which case we should
9098
     * clear previous state.
9099
     */
9100
7.50k
    ssl3_ResetExtensionData(&ss->xtnData, ss);
9101
7.50k
    ss->statelessResume = PR_FALSE;
9102
9103
7.50k
    if (IS_DTLS(ss)) {
9104
7.50k
        dtls_RehandshakeCleanup(ss);
9105
7.50k
    }
9106
9107
7.50k
    rv = ssl3_HandleClientHelloPreamble(ss, &b, &length, &sidBytes,
9108
7.50k
                                        &cookieBytes, &suites, &comps);
9109
7.50k
    if (rv != SECSuccess) {
9110
84
        goto loser; /* malformed */
9111
84
    }
9112
9113
    /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
9114
     * we are restarting a previous session until extensions have been
9115
     * parsed, since we might have received a SessionTicket extension.
9116
     * Note: we allow extensions even when negotiating SSL3 for the sake
9117
     * of interoperability (and backwards compatibility).
9118
     */
9119
7.42k
    if (length) {
9120
        /* Get length of hello extensions */
9121
4.01k
        rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
9122
4.01k
        if (rv != SECSuccess) {
9123
1
            goto loser; /* alert already sent */
9124
1
        }
9125
4.00k
        if (extensionLength != length) {
9126
23
            errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9127
23
            desc = decode_error;
9128
23
            goto alert_loser;
9129
23
        }
9130
9131
3.98k
        rv = ssl3_ParseExtensions(ss, &b, &length);
9132
3.98k
        if (rv != SECSuccess) {
9133
8
            goto loser; /* malformed */
9134
8
        }
9135
3.98k
    }
9136
9137
7.39k
    versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
9138
7.39k
    if (versionExtension) {
9139
43
        rv = tls13_NegotiateVersion(ss, versionExtension);
9140
43
        if (rv != SECSuccess) {
9141
18
            errCode = PORT_GetError();
9142
18
            desc = (errCode == SSL_ERROR_UNSUPPORTED_VERSION) ? protocol_version : illegal_parameter;
9143
18
            goto alert_loser;
9144
18
        }
9145
7.34k
    } else {
9146
        /* The PR_MIN here ensures that we never negotiate 1.3 if the
9147
         * peer didn't offer "supported_versions". */
9148
7.34k
        rv = ssl3_NegotiateVersion(ss,
9149
7.34k
                                   PR_MIN(ss->clientHelloVersion,
9150
7.34k
                                          SSL_LIBRARY_VERSION_TLS_1_2),
9151
7.34k
                                   PR_TRUE);
9152
        /* Send protocol version alert if the ClientHello.legacy_version is not
9153
         * supported by the server.
9154
         *
9155
         * If the "supported_versions" extension is absent and the server only
9156
         * supports versions greater than ClientHello.legacy_version, the
9157
         * server MUST abort the handshake with a "protocol_version" alert
9158
         * [RFC8446, Appendix D.2]. */
9159
7.34k
        if (rv != SECSuccess) {
9160
5
            desc = protocol_version;
9161
5
            errCode = SSL_ERROR_UNSUPPORTED_VERSION;
9162
5
            goto alert_loser;
9163
5
        }
9164
7.34k
    }
9165
7.36k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
9166
9167
    /* Update the write spec to match the selected version. */
9168
7.36k
    if (!ss->firstHsDone) {
9169
7.36k
        ssl_GetSpecWriteLock(ss);
9170
7.36k
        ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
9171
7.36k
        ssl_ReleaseSpecWriteLock(ss);
9172
7.36k
    }
9173
9174
7.36k
    isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
9175
7.36k
    if (isTLS13) {
9176
0
        if (ss->firstHsDone) {
9177
0
            desc = unexpected_message;
9178
0
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9179
0
            goto alert_loser;
9180
0
        }
9181
9182
        /* If there is a cookie, then this is a second ClientHello (TLS 1.3). */
9183
0
        if (ssl3_FindExtension(ss, ssl_tls13_cookie_xtn)) {
9184
0
            ss->ssl3.hs.helloRetry = PR_TRUE;
9185
0
        }
9186
9187
0
        rv = tls13_MaybeHandleEch(ss, savedMsg, savedLen, &sidBytes,
9188
0
                                  &comps, &cookieBytes, &suites, &echInner);
9189
0
        if (rv != SECSuccess) {
9190
0
            errCode = PORT_GetError();
9191
0
            goto loser; /* code set, alert sent. */
9192
0
        }
9193
0
    }
9194
9195
7.36k
    rv = ssl3_ValidatePreambleWithVersion(ss, &sidBytes, &comps, &cookieBytes);
9196
7.36k
    if (rv != SECSuccess) {
9197
5
        errCode = PORT_GetError();
9198
5
        goto loser; /* code set, alert sent. */
9199
5
    }
9200
9201
    /* Now parse the rest of the extensions. */
9202
7.36k
    rv = ssl3_HandleParsedExtensions(ss, ssl_hs_client_hello);
9203
7.36k
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
9204
7.36k
    if (rv != SECSuccess) {
9205
92
        if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
9206
20
            errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
9207
20
        }
9208
92
        goto loser; /* malformed */
9209
92
    }
9210
9211
    /* If the ClientHello version is less than our maximum version, check for a
9212
     * TLS_FALLBACK_SCSV and reject the connection if found. */
9213
7.27k
    if (ss->vrange.max > ss->version) {
9214
0
        for (i = 0; i + 1 < suites.len; i += 2) {
9215
0
            PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
9216
0
            if (suite_i != TLS_FALLBACK_SCSV)
9217
0
                continue;
9218
0
            desc = inappropriate_fallback;
9219
0
            errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
9220
0
            goto alert_loser;
9221
0
        }
9222
0
    }
9223
9224
7.27k
    if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9225
        /* If we didn't receive an RI extension, look for the SCSV,
9226
         * and if found, treat it just like an empty RI extension
9227
         * by processing a local copy of an empty RI extension.
9228
         */
9229
14.3k
        for (i = 0; i + 1 < suites.len; i += 2) {
9230
10.8k
            PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
9231
10.8k
            if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
9232
3.13k
                PRUint8 *b2 = (PRUint8 *)emptyRIext;
9233
3.13k
                PRUint32 L2 = sizeof emptyRIext;
9234
3.13k
                (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
9235
3.13k
                break;
9236
3.13k
            }
9237
10.8k
        }
9238
6.58k
    }
9239
9240
    /* The check for renegotiation in TLS 1.3 is earlier. */
9241
7.27k
    if (!isTLS13) {
9242
7.27k
        if (ss->firstHsDone &&
9243
7.27k
            (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
9244
0
             ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) &&
9245
7.27k
            !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9246
0
            desc = no_renegotiation;
9247
0
            level = alert_warning;
9248
0
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9249
0
            goto alert_loser;
9250
0
        }
9251
7.27k
        if ((ss->opt.requireSafeNegotiation ||
9252
7.27k
             (ss->firstHsDone && ss->peerRequestedProtection)) &&
9253
7.27k
            !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9254
1.19k
            desc = handshake_failure;
9255
1.19k
            errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
9256
1.19k
            goto alert_loser;
9257
1.19k
        }
9258
7.27k
    }
9259
9260
    /* We do stateful resumes only if we are in TLS < 1.3 and
9261
     * either of the following conditions are satisfied:
9262
     * (1) the client does not support the session ticket extension, or
9263
     * (2) the client support the session ticket extension, but sent an
9264
     * empty ticket.
9265
     */
9266
6.08k
    if (!isTLS13 &&
9267
6.08k
        (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
9268
6.08k
         ss->xtnData.emptySessionTicket)) {
9269
6.08k
        if (sidBytes.len > 0 && !ss->opt.noCache) {
9270
2.54k
            SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
9271
2.54k
                        SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
9272
2.54k
                        ss->sec.ci.peer.pr_s6_addr32[1],
9273
2.54k
                        ss->sec.ci.peer.pr_s6_addr32[2],
9274
2.54k
                        ss->sec.ci.peer.pr_s6_addr32[3]));
9275
2.54k
            if (ssl_sid_lookup) {
9276
2.54k
                sid = (*ssl_sid_lookup)(ssl_Time(ss), &ss->sec.ci.peer,
9277
2.54k
                                        sidBytes.data, sidBytes.len, ss->dbHandle);
9278
2.54k
            } else {
9279
0
                errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
9280
0
                goto loser;
9281
0
            }
9282
2.54k
        }
9283
6.08k
    } else if (ss->statelessResume) {
9284
        /* Fill in the client's session ID if doing a stateless resume.
9285
         * (When doing stateless resumes, server echos client's SessionID.)
9286
         * This branch also handles TLS 1.3 resumption-PSK.
9287
         */
9288
0
        sid = ss->sec.ci.sid;
9289
0
        PORT_Assert(sid != NULL); /* Should have already been filled in.*/
9290
9291
0
        if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
9292
0
            sid->u.ssl3.sessionIDLength = sidBytes.len;
9293
0
            PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
9294
0
                        sidBytes.len);
9295
0
            sid->u.ssl3.sessionIDLength = sidBytes.len;
9296
0
        } else {
9297
0
            sid->u.ssl3.sessionIDLength = 0;
9298
0
        }
9299
0
        ss->sec.ci.sid = NULL;
9300
0
    }
9301
9302
    /* Free a potentially leftover session ID from a previous handshake. */
9303
6.08k
    if (ss->sec.ci.sid) {
9304
0
        ssl_FreeSID(ss->sec.ci.sid);
9305
0
        ss->sec.ci.sid = NULL;
9306
0
    }
9307
9308
6.08k
    if (sid != NULL) {
9309
        /* We've found a session cache entry for this client.
9310
         * Now, if we're going to require a client-auth cert,
9311
         * and we don't already have this client's cert in the session cache,
9312
         * and this is the first handshake on this connection (not a redo),
9313
         * then drop this old cache entry and start a new session.
9314
         */
9315
0
        if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
9316
0
            ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
9317
0
             (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
9318
0
             ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) &&
9319
0
              !ss->firstHsDone))) {
9320
9321
0
            SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
9322
0
            ssl_FreeSID(sid);
9323
0
            sid = NULL;
9324
0
            ss->statelessResume = PR_FALSE;
9325
0
        }
9326
0
    }
9327
9328
6.08k
    if (IS_DTLS(ss)) {
9329
6.08k
        ssl3_DisableNonDTLSSuites(ss);
9330
6.08k
        dtls_ReceivedFirstMessageInFlight(ss);
9331
6.08k
    }
9332
9333
6.08k
    if (isTLS13) {
9334
0
        rv = tls13_HandleClientHelloPart2(ss, &suites, sid,
9335
0
                                          ss->ssl3.hs.echAccepted ? echInner->data : savedMsg,
9336
0
                                          ss->ssl3.hs.echAccepted ? echInner->len : savedLen);
9337
0
        SECITEM_FreeItem(echInner, PR_TRUE);
9338
0
        echInner = NULL;
9339
6.08k
    } else {
9340
6.08k
        rv = ssl3_HandleClientHelloPart2(ss, &suites, sid,
9341
6.08k
                                         savedMsg, savedLen);
9342
6.08k
    }
9343
6.08k
    if (rv != SECSuccess) {
9344
42
        errCode = PORT_GetError();
9345
42
        goto loser;
9346
42
    }
9347
6.04k
    return SECSuccess;
9348
9349
1.23k
alert_loser:
9350
1.23k
    (void)SSL3_SendAlert(ss, level, desc);
9351
/* FALLTHRU */
9352
1.46k
loser:
9353
1.46k
    SECITEM_FreeItem(echInner, PR_TRUE);
9354
1.46k
    PORT_SetError(errCode);
9355
1.46k
    return SECFailure;
9356
1.23k
}
9357
9358
/* unwrap helper function to handle the case where the wrapKey doesn't wind
9359
 * up in the correct token for the master secret */
9360
PK11SymKey *
9361
ssl_unwrapSymKey(PK11SymKey *wrapKey,
9362
                 CK_MECHANISM_TYPE wrapType, SECItem *param,
9363
                 SECItem *wrappedKey,
9364
                 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
9365
                 int keySize, CK_FLAGS keyFlags, void *pinArg)
9366
0
{
9367
0
    PK11SymKey *unwrappedKey;
9368
9369
    /* unwrap the master secret. */
9370
0
    unwrappedKey = PK11_UnwrapSymKeyWithFlags(wrapKey, wrapType, param,
9371
0
                                              wrappedKey, target, operation, keySize,
9372
0
                                              keyFlags);
9373
0
    if (!unwrappedKey) {
9374
0
        PK11SlotInfo *targetSlot = PK11_GetBestSlot(target, pinArg);
9375
0
        PK11SymKey *newWrapKey;
9376
9377
        /* it's possible that we failed to unwrap because the wrapKey is in
9378
         * a slot that can't handle target. Move the wrapKey to a slot that
9379
         * can handle this mechanism and retry the operation */
9380
0
        if (targetSlot == NULL) {
9381
0
            return NULL;
9382
0
        }
9383
0
        newWrapKey = PK11_MoveSymKey(targetSlot, CKA_UNWRAP, 0,
9384
0
                                     PR_FALSE, wrapKey);
9385
0
        PK11_FreeSlot(targetSlot);
9386
0
        if (newWrapKey == NULL) {
9387
0
            return NULL;
9388
0
        }
9389
0
        unwrappedKey = PK11_UnwrapSymKeyWithFlags(newWrapKey, wrapType, param,
9390
0
                                                  wrappedKey, target, operation, keySize,
9391
0
                                                  keyFlags);
9392
0
        PK11_FreeSymKey(newWrapKey);
9393
0
    }
9394
0
    return unwrappedKey;
9395
0
}
9396
9397
static SECStatus
9398
ssl3_UnwrapMasterSecretServer(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
9399
0
{
9400
0
    PK11SymKey *wrapKey;
9401
0
    CK_FLAGS keyFlags = 0;
9402
0
    SECItem wrappedMS = {
9403
0
        siBuffer,
9404
0
        sid->u.ssl3.keys.wrapped_master_secret,
9405
0
        sid->u.ssl3.keys.wrapped_master_secret_len
9406
0
    };
9407
9408
0
    wrapKey = ssl3_GetWrappingKey(ss, NULL, sid->u.ssl3.masterWrapMech,
9409
0
                                  ss->pkcs11PinArg);
9410
0
    if (!wrapKey) {
9411
0
        return SECFailure;
9412
0
    }
9413
9414
0
    if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
9415
0
        keyFlags = CKF_SIGN | CKF_VERIFY;
9416
0
    }
9417
9418
0
    *ms = ssl_unwrapSymKey(wrapKey, sid->u.ssl3.masterWrapMech, NULL,
9419
0
                           &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
9420
0
                           CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH,
9421
0
                           keyFlags, ss->pkcs11PinArg);
9422
0
    PK11_FreeSymKey(wrapKey);
9423
0
    if (!*ms) {
9424
0
        SSL_TRC(10, ("%d: SSL3[%d]: server wrapping key found, but couldn't unwrap MasterSecret. wrapMech=0x%0lx",
9425
0
                     SSL_GETPID(), ss->fd, sid->u.ssl3.masterWrapMech));
9426
0
        return SECFailure;
9427
0
    }
9428
0
    return SECSuccess;
9429
0
}
9430
9431
static SECStatus
9432
ssl3_HandleClientHelloPart2(sslSocket *ss,
9433
                            SECItem *suites,
9434
                            sslSessionID *sid,
9435
                            const PRUint8 *msg,
9436
                            unsigned int len)
9437
6.08k
{
9438
6.08k
    PRBool haveXmitBufLock = PR_FALSE;
9439
6.08k
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9440
6.08k
    SSL3AlertDescription desc = illegal_parameter;
9441
6.08k
    SECStatus rv;
9442
6.08k
    unsigned int i;
9443
6.08k
    unsigned int j;
9444
9445
6.08k
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_client_hello, msg, len);
9446
6.08k
    if (rv != SECSuccess) {
9447
0
        errCode = SEC_ERROR_LIBRARY_FAILURE;
9448
0
        desc = internal_error;
9449
0
        goto alert_loser;
9450
0
    }
9451
9452
    /* If we already have a session for this client, be sure to pick the same
9453
    ** cipher suite we picked before.  This is not a loop, despite appearances.
9454
    */
9455
6.08k
    if (sid)
9456
0
        do {
9457
0
            ssl3CipherSuiteCfg *suite;
9458
0
            SSLVersionRange vrange = { ss->version, ss->version };
9459
9460
0
            suite = ss->cipherSuites;
9461
            /* Find the entry for the cipher suite used in the cached session. */
9462
0
            for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
9463
0
                if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
9464
0
                    break;
9465
0
            }
9466
0
            PORT_Assert(j > 0);
9467
0
            if (j == 0)
9468
0
                break;
9469
9470
            /* Double check that the cached cipher suite is still enabled,
9471
             * implemented, and allowed by policy.  Might have been disabled.
9472
             */
9473
0
            if (ssl3_config_match_init(ss) == 0) {
9474
0
                desc = handshake_failure;
9475
0
                errCode = PORT_GetError();
9476
0
                goto alert_loser;
9477
0
            }
9478
0
            if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss))
9479
0
                break;
9480
9481
            /* Double check that the cached cipher suite is in the client's
9482
             * list.  If it isn't, fall through and start a new session. */
9483
0
            for (i = 0; i + 1 < suites->len; i += 2) {
9484
0
                PRUint16 suite_i = (suites->data[i] << 8) | suites->data[i + 1];
9485
0
                if (suite_i == suite->cipher_suite) {
9486
0
                    ss->ssl3.hs.cipher_suite = suite_i;
9487
0
                    rv = ssl3_SetupCipherSuite(ss, PR_TRUE);
9488
0
                    if (rv != SECSuccess) {
9489
0
                        desc = internal_error;
9490
0
                        errCode = PORT_GetError();
9491
0
                        goto alert_loser;
9492
0
                    }
9493
9494
0
                    goto cipher_found;
9495
0
                }
9496
0
            }
9497
0
        } while (0);
9498
    /* START A NEW SESSION */
9499
9500
6.08k
    rv = ssl3_NegotiateCipherSuite(ss, suites, PR_TRUE);
9501
6.08k
    if (rv != SECSuccess) {
9502
20
        desc = handshake_failure;
9503
20
        errCode = PORT_GetError();
9504
20
        goto alert_loser;
9505
20
    }
9506
9507
6.06k
cipher_found:
9508
6.06k
    suites->data = NULL;
9509
9510
    /* If there are any failures while processing the old sid,
9511
     * we don't consider them to be errors.  Instead, We just behave
9512
     * as if the client had sent us no sid to begin with, and make a new one.
9513
     * The exception here is attempts to resume extended_master_secret
9514
     * sessions without the extension, which causes an alert.
9515
     */
9516
6.06k
    if (sid != NULL)
9517
0
        do {
9518
0
            PK11SymKey *masterSecret;
9519
9520
0
            if (sid->version != ss->version ||
9521
0
                sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
9522
0
                break; /* not an error */
9523
0
            }
9524
9525
            /* server sids don't remember the server cert we previously sent,
9526
            ** but they do remember the slot we originally used, so we
9527
            ** can locate it again, provided that the current ssl socket
9528
            ** has had its server certs configured the same as the previous one.
9529
            */
9530
0
            ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType, sid->namedCurve);
9531
0
            if (!ss->sec.serverCert || !ss->sec.serverCert->serverCert) {
9532
                /* A compatible certificate must not have been configured.  It
9533
                 * might not be the same certificate, but we only find that out
9534
                 * when the ticket fails to decrypt. */
9535
0
                break;
9536
0
            }
9537
9538
            /* [draft-ietf-tls-session-hash-06; Section 5.3]
9539
             * o  If the original session did not use the "extended_master_secret"
9540
             *    extension but the new ClientHello contains the extension, then the
9541
             *    server MUST NOT perform the abbreviated handshake.  Instead, it
9542
             *    SHOULD continue with a full handshake (as described in
9543
             *    Section 5.2) to negotiate a new session.
9544
             *
9545
             * o  If the original session used the "extended_master_secret"
9546
             *    extension but the new ClientHello does not contain the extension,
9547
             *    the server MUST abort the abbreviated handshake.
9548
             */
9549
0
            if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
9550
0
                if (!sid->u.ssl3.keys.extendedMasterSecretUsed) {
9551
0
                    break; /* not an error */
9552
0
                }
9553
0
            } else {
9554
0
                if (sid->u.ssl3.keys.extendedMasterSecretUsed) {
9555
                    /* Note: we do not destroy the session */
9556
0
                    desc = handshake_failure;
9557
0
                    errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
9558
0
                    goto alert_loser;
9559
0
                }
9560
0
            }
9561
9562
0
            if (ss->sec.ci.sid) {
9563
0
                ssl_UncacheSessionID(ss);
9564
0
                PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */
9565
0
                if (ss->sec.ci.sid != sid) {
9566
0
                    ssl_FreeSID(ss->sec.ci.sid);
9567
0
                }
9568
0
                ss->sec.ci.sid = NULL;
9569
0
            }
9570
9571
            /* we need to resurrect the master secret.... */
9572
0
            rv = ssl3_UnwrapMasterSecretServer(ss, sid, &masterSecret);
9573
0
            if (rv != SECSuccess) {
9574
0
                break; /* not an error */
9575
0
            }
9576
9577
0
            ss->sec.ci.sid = sid;
9578
0
            if (sid->peerCert != NULL) {
9579
0
                ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
9580
0
            }
9581
9582
            /*
9583
             * Old SID passed all tests, so resume this old session.
9584
             */
9585
0
            SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_hits);
9586
0
            if (ss->statelessResume)
9587
0
                SSL_AtomicIncrementLong(&ssl3stats.hch_sid_stateless_resumes);
9588
0
            ss->ssl3.hs.isResuming = PR_TRUE;
9589
9590
0
            ss->sec.authType = sid->authType;
9591
0
            ss->sec.authKeyBits = sid->authKeyBits;
9592
0
            ss->sec.keaType = sid->keaType;
9593
0
            ss->sec.keaKeyBits = sid->keaKeyBits;
9594
0
            ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
9595
0
            ss->sec.signatureScheme = sid->sigScheme;
9596
9597
0
            ss->sec.localCert =
9598
0
                CERT_DupCertificate(ss->sec.serverCert->serverCert);
9599
9600
            /* Copy cached name in to pending spec */
9601
0
            if (sid != NULL &&
9602
0
                sid->version > SSL_LIBRARY_VERSION_3_0 &&
9603
0
                sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
9604
                /* Set server name from sid */
9605
0
                SECItem *sidName = &sid->u.ssl3.srvName;
9606
0
                SECItem *pwsName = &ss->ssl3.hs.srvVirtName;
9607
0
                if (pwsName->data) {
9608
0
                    SECITEM_FreeItem(pwsName, PR_FALSE);
9609
0
                }
9610
0
                rv = SECITEM_CopyItem(NULL, pwsName, sidName);
9611
0
                if (rv != SECSuccess) {
9612
0
                    errCode = PORT_GetError();
9613
0
                    desc = internal_error;
9614
0
                    goto alert_loser;
9615
0
                }
9616
0
            }
9617
9618
            /* Clean up sni name array */
9619
0
            ssl3_FreeSniNameArray(&ss->xtnData);
9620
9621
0
            ssl_GetXmitBufLock(ss);
9622
0
            haveXmitBufLock = PR_TRUE;
9623
9624
0
            rv = ssl3_SendServerHello(ss);
9625
0
            if (rv != SECSuccess) {
9626
0
                errCode = PORT_GetError();
9627
0
                goto loser;
9628
0
            }
9629
9630
            /* We are re-using the old MS, so no need to derive again. */
9631
0
            rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE);
9632
0
            if (rv != SECSuccess) {
9633
0
                errCode = PORT_GetError();
9634
0
                goto loser;
9635
0
            }
9636
9637
0
            rv = ssl3_SendChangeCipherSpecs(ss);
9638
0
            if (rv != SECSuccess) {
9639
0
                errCode = PORT_GetError();
9640
0
                goto loser;
9641
0
            }
9642
0
            rv = ssl3_SendFinished(ss, 0);
9643
0
            ss->ssl3.hs.ws = wait_change_cipher;
9644
0
            if (rv != SECSuccess) {
9645
0
                errCode = PORT_GetError();
9646
0
                goto loser;
9647
0
            }
9648
9649
0
            if (haveXmitBufLock) {
9650
0
                ssl_ReleaseXmitBufLock(ss);
9651
0
            }
9652
9653
0
            return SECSuccess;
9654
0
        } while (0);
9655
9656
6.06k
    if (sid) { /* we had a sid, but it's no longer valid, free it */
9657
0
        ss->statelessResume = PR_FALSE;
9658
0
        SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
9659
0
        ssl_UncacheSessionID(ss);
9660
0
        ssl_FreeSID(sid);
9661
0
        sid = NULL;
9662
0
    }
9663
6.06k
    SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
9664
9665
    /* We only send a session ticket extension if the client supports
9666
     * the extension and we are unable to resume.
9667
     *
9668
     * TODO: send a session ticket if performing a stateful
9669
     * resumption.  (As per RFC4507, a server may issue a session
9670
     * ticket while doing a (stateless or stateful) session resume,
9671
     * but OpenSSL-0.9.8g does not accept session tickets while
9672
     * resuming.)
9673
     */
9674
6.06k
    if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
9675
6.06k
        ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
9676
0
        ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_session_ticket_xtn,
9677
0
                                     ssl_SendEmptyExtension);
9678
0
    }
9679
9680
6.06k
    rv = ssl3_ServerCallSNICallback(ss);
9681
6.06k
    if (rv != SECSuccess) {
9682
        /* The alert has already been sent. */
9683
0
        errCode = PORT_GetError();
9684
0
        goto loser;
9685
0
    }
9686
9687
6.06k
    rv = ssl3_SelectServerCert(ss);
9688
6.06k
    if (rv != SECSuccess) {
9689
22
        errCode = PORT_GetError();
9690
22
        desc = handshake_failure;
9691
22
        goto alert_loser;
9692
22
    }
9693
9694
6.04k
    sid = ssl3_NewSessionID(ss, PR_TRUE);
9695
6.04k
    if (sid == NULL) {
9696
0
        errCode = PORT_GetError();
9697
0
        goto loser; /* memory error is set. */
9698
0
    }
9699
6.04k
    ss->sec.ci.sid = sid;
9700
9701
6.04k
    sid->u.ssl3.keys.extendedMasterSecretUsed =
9702
6.04k
        ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
9703
6.04k
    ss->ssl3.hs.isResuming = PR_FALSE;
9704
9705
6.04k
    ssl_GetXmitBufLock(ss);
9706
6.04k
    rv = ssl3_SendServerHelloSequence(ss);
9707
6.04k
    ssl_ReleaseXmitBufLock(ss);
9708
6.04k
    if (rv != SECSuccess) {
9709
0
        errCode = PORT_GetError();
9710
0
        desc = handshake_failure;
9711
0
        goto alert_loser;
9712
0
    }
9713
9714
6.04k
    if (haveXmitBufLock) {
9715
0
        ssl_ReleaseXmitBufLock(ss);
9716
0
    }
9717
9718
6.04k
    return SECSuccess;
9719
9720
42
alert_loser:
9721
42
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
9722
/* FALLTHRU */
9723
42
loser:
9724
42
    if (sid && sid != ss->sec.ci.sid) {
9725
0
        ssl_UncacheSessionID(ss);
9726
0
        ssl_FreeSID(sid);
9727
0
    }
9728
9729
42
    if (haveXmitBufLock) {
9730
0
        ssl_ReleaseXmitBufLock(ss);
9731
0
    }
9732
9733
42
    PORT_SetError(errCode);
9734
42
    return SECFailure;
9735
42
}
9736
9737
/*
9738
 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
9739
 * in asking to use the V3 handshake.
9740
 */
9741
SECStatus
9742
ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, unsigned int length,
9743
                         PRUint8 padding)
9744
0
{
9745
0
    sslSessionID *sid = NULL;
9746
0
    unsigned char *suites;
9747
0
    unsigned char *random;
9748
0
    SSL3ProtocolVersion version;
9749
0
    SECStatus rv;
9750
0
    unsigned int i;
9751
0
    unsigned int j;
9752
0
    unsigned int sid_length;
9753
0
    unsigned int suite_length;
9754
0
    unsigned int rand_length;
9755
0
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9756
0
    SSL3AlertDescription desc = handshake_failure;
9757
0
    unsigned int total = SSL_HL_CLIENT_HELLO_HBYTES;
9758
9759
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
9760
9761
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
9762
9763
0
    ssl_GetSSL3HandshakeLock(ss);
9764
9765
0
    version = (buffer[1] << 8) | buffer[2];
9766
0
    if (version < SSL_LIBRARY_VERSION_3_0) {
9767
0
        goto loser;
9768
0
    }
9769
9770
0
    ssl3_RestartHandshakeHashes(ss);
9771
9772
0
    if (ss->ssl3.hs.ws != wait_client_hello) {
9773
0
        desc = unexpected_message;
9774
0
        errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
9775
0
        goto alert_loser;
9776
0
    }
9777
9778
0
    total += suite_length = (buffer[3] << 8) | buffer[4];
9779
0
    total += sid_length = (buffer[5] << 8) | buffer[6];
9780
0
    total += rand_length = (buffer[7] << 8) | buffer[8];
9781
0
    total += padding;
9782
0
    ss->clientHelloVersion = version;
9783
9784
0
    if (version >= SSL_LIBRARY_VERSION_TLS_1_3) {
9785
        /* [draft-ietf-tls-tls-11; C.3] forbids sending a TLS 1.3
9786
         * ClientHello using the backwards-compatible format. */
9787
0
        desc = illegal_parameter;
9788
0
        errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9789
0
        goto alert_loser;
9790
0
    }
9791
9792
0
    rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
9793
0
    if (rv != SECSuccess) {
9794
        /* send back which ever alert client will understand. */
9795
0
        desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
9796
0
                                                   : handshake_failure;
9797
0
        errCode = SSL_ERROR_UNSUPPORTED_VERSION;
9798
0
        goto alert_loser;
9799
0
    }
9800
    /* ECH not possible here. */
9801
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
9802
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
9803
0
    if (!ss->firstHsDone) {
9804
0
        ssl_GetSpecWriteLock(ss);
9805
0
        ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
9806
0
        ssl_ReleaseSpecWriteLock(ss);
9807
0
    }
9808
9809
    /* if we get a non-zero SID, just ignore it. */
9810
0
    if (length != total) {
9811
0
        SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
9812
0
                 SSL_GETPID(), ss->fd, length, total));
9813
0
        desc = illegal_parameter;
9814
0
        errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9815
0
        goto alert_loser;
9816
0
    }
9817
9818
0
    suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
9819
0
    random = suites + suite_length + sid_length;
9820
9821
0
    if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
9822
0
        rand_length > SSL_MAX_CHALLENGE_BYTES) {
9823
0
        desc = illegal_parameter;
9824
0
        errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9825
0
        goto alert_loser;
9826
0
    }
9827
9828
0
    PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
9829
9830
0
    PORT_Memset(ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
9831
0
    PORT_Memcpy(&ss->ssl3.hs.client_random[SSL3_RANDOM_LENGTH - rand_length],
9832
0
                random, rand_length);
9833
9834
0
    PRINT_BUF(60, (ss, "client random:", ss->ssl3.hs.client_random,
9835
0
                   SSL3_RANDOM_LENGTH));
9836
9837
0
    if (ssl3_config_match_init(ss) == 0) {
9838
0
        errCode = PORT_GetError(); /* error code is already set. */
9839
0
        goto alert_loser;
9840
0
    }
9841
9842
    /* Select a cipher suite.
9843
    **
9844
    ** NOTE: This suite selection algorithm should be the same as the one in
9845
    ** ssl3_HandleClientHello().
9846
    */
9847
0
    for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
9848
0
        ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
9849
0
        SSLVersionRange vrange = { ss->version, ss->version };
9850
0
        if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
9851
0
            continue;
9852
0
        }
9853
0
        for (i = 0; i + 2 < suite_length; i += 3) {
9854
0
            PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9855
0
            if (suite_i == suite->cipher_suite) {
9856
0
                ss->ssl3.hs.cipher_suite = suite_i;
9857
0
                rv = ssl3_SetupCipherSuite(ss, PR_TRUE);
9858
0
                if (rv != SECSuccess) {
9859
0
                    desc = internal_error;
9860
0
                    errCode = PORT_GetError();
9861
0
                    goto alert_loser;
9862
0
                }
9863
0
                goto suite_found;
9864
0
            }
9865
0
        }
9866
0
    }
9867
0
    errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
9868
0
    goto alert_loser;
9869
9870
0
suite_found:
9871
9872
    /* If the ClientHello version is less than our maximum version, check for a
9873
     * TLS_FALLBACK_SCSV and reject the connection if found. */
9874
0
    if (ss->vrange.max > ss->clientHelloVersion) {
9875
0
        for (i = 0; i + 2 < suite_length; i += 3) {
9876
0
            PRUint16 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9877
0
            if (suite_i == TLS_FALLBACK_SCSV) {
9878
0
                desc = inappropriate_fallback;
9879
0
                errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
9880
0
                goto alert_loser;
9881
0
            }
9882
0
        }
9883
0
    }
9884
9885
    /* Look for the SCSV, and if found, treat it just like an empty RI
9886
     * extension by processing a local copy of an empty RI extension.
9887
     */
9888
0
    for (i = 0; i + 2 < suite_length; i += 3) {
9889
0
        PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9890
0
        if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
9891
0
            PRUint8 *b2 = (PRUint8 *)emptyRIext;
9892
0
            PRUint32 L2 = sizeof emptyRIext;
9893
0
            (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
9894
0
            break;
9895
0
        }
9896
0
    }
9897
9898
0
    if (ss->opt.requireSafeNegotiation &&
9899
0
        !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9900
0
        desc = handshake_failure;
9901
0
        errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
9902
0
        goto alert_loser;
9903
0
    }
9904
9905
0
    rv = ssl3_SelectServerCert(ss);
9906
0
    if (rv != SECSuccess) {
9907
0
        errCode = PORT_GetError();
9908
0
        desc = handshake_failure;
9909
0
        goto alert_loser;
9910
0
    }
9911
9912
    /* we don't even search for a cache hit here.  It's just a miss. */
9913
0
    SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
9914
0
    sid = ssl3_NewSessionID(ss, PR_TRUE);
9915
0
    if (sid == NULL) {
9916
0
        errCode = PORT_GetError();
9917
0
        goto loser; /* memory error is set. */
9918
0
    }
9919
0
    ss->sec.ci.sid = sid;
9920
    /* do not worry about memory leak of sid since it now belongs to ci */
9921
9922
    /* We have to update the handshake hashes before we can send stuff */
9923
0
    rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
9924
0
    if (rv != SECSuccess) {
9925
0
        errCode = PORT_GetError();
9926
0
        goto loser;
9927
0
    }
9928
9929
0
    ssl_GetXmitBufLock(ss);
9930
0
    rv = ssl3_SendServerHelloSequence(ss);
9931
0
    ssl_ReleaseXmitBufLock(ss);
9932
0
    if (rv != SECSuccess) {
9933
0
        errCode = PORT_GetError();
9934
0
        goto loser;
9935
0
    }
9936
9937
0
    ssl_ReleaseSSL3HandshakeLock(ss);
9938
0
    return SECSuccess;
9939
9940
0
alert_loser:
9941
0
    SSL3_SendAlert(ss, alert_fatal, desc);
9942
0
loser:
9943
0
    ssl_ReleaseSSL3HandshakeLock(ss);
9944
0
    PORT_SetError(errCode);
9945
0
    return SECFailure;
9946
0
}
9947
9948
SECStatus
9949
ssl_ConstructServerHello(sslSocket *ss, PRBool helloRetry,
9950
                         const sslBuffer *extensionBuf, sslBuffer *messageBuf)
9951
6.04k
{
9952
6.04k
    SECStatus rv;
9953
6.04k
    SSL3ProtocolVersion version;
9954
6.04k
    sslSessionID *sid = ss->sec.ci.sid;
9955
6.04k
    const PRUint8 *random;
9956
9957
6.04k
    version = PR_MIN(ss->version, SSL_LIBRARY_VERSION_TLS_1_2);
9958
6.04k
    if (IS_DTLS(ss)) {
9959
6.04k
        version = dtls_TLSVersionToDTLSVersion(version);
9960
6.04k
    }
9961
6.04k
    rv = sslBuffer_AppendNumber(messageBuf, version, 2);
9962
6.04k
    if (rv != SECSuccess) {
9963
0
        return SECFailure;
9964
0
    }
9965
9966
6.04k
    if (helloRetry) {
9967
0
        random = ssl_hello_retry_random;
9968
6.04k
    } else {
9969
6.04k
        rv = ssl_GenerateServerRandom(ss);
9970
6.04k
        if (rv != SECSuccess) {
9971
0
            return SECFailure;
9972
0
        }
9973
6.04k
        random = ss->ssl3.hs.server_random;
9974
6.04k
    }
9975
6.04k
    rv = sslBuffer_Append(messageBuf, random, SSL3_RANDOM_LENGTH);
9976
6.04k
    if (rv != SECSuccess) {
9977
0
        return SECFailure;
9978
0
    }
9979
9980
6.04k
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
9981
6.04k
        if (sid) {
9982
6.04k
            rv = sslBuffer_AppendVariable(messageBuf, sid->u.ssl3.sessionID,
9983
6.04k
                                          sid->u.ssl3.sessionIDLength, 1);
9984
6.04k
        } else {
9985
0
            rv = sslBuffer_AppendNumber(messageBuf, 0, 1);
9986
0
        }
9987
6.04k
    } else {
9988
0
        rv = sslBuffer_AppendVariable(messageBuf, ss->ssl3.hs.fakeSid.data,
9989
0
                                      ss->ssl3.hs.fakeSid.len, 1);
9990
0
    }
9991
6.04k
    if (rv != SECSuccess) {
9992
0
        return SECFailure;
9993
0
    }
9994
9995
6.04k
    rv = sslBuffer_AppendNumber(messageBuf, ss->ssl3.hs.cipher_suite, 2);
9996
6.04k
    if (rv != SECSuccess) {
9997
0
        return SECFailure;
9998
0
    }
9999
6.04k
    rv = sslBuffer_AppendNumber(messageBuf, ssl_compression_null, 1);
10000
6.04k
    if (rv != SECSuccess) {
10001
0
        return SECFailure;
10002
0
    }
10003
6.04k
    if (SSL_BUFFER_LEN(extensionBuf)) {
10004
        /* Directly copy the extensions */
10005
4.86k
        rv = sslBuffer_AppendBufferVariable(messageBuf, extensionBuf, 2);
10006
4.86k
        if (rv != SECSuccess) {
10007
0
            return SECFailure;
10008
0
        }
10009
4.86k
    }
10010
10011
6.04k
    if (ss->xtnData.ech && ss->xtnData.ech->receivedInnerXtn) {
10012
        /* Signal ECH acceptance if we handled handled both CHOuter/CHInner (i.e.
10013
         * in shared mode), or if we received a CHInner in split/backend mode. */
10014
0
        if (ss->ssl3.hs.echAccepted || ss->opt.enableTls13BackendEch) {
10015
0
            if (helloRetry) {
10016
0
                return tls13_WriteServerEchHrrSignal(ss, SSL_BUFFER_BASE(messageBuf),
10017
0
                                                     SSL_BUFFER_LEN(messageBuf));
10018
0
            } else {
10019
0
                return tls13_WriteServerEchSignal(ss, SSL_BUFFER_BASE(messageBuf),
10020
0
                                                  SSL_BUFFER_LEN(messageBuf));
10021
0
            }
10022
0
        }
10023
0
    }
10024
6.04k
    return SECSuccess;
10025
6.04k
}
10026
10027
/* The negotiated version number has been already placed in ss->version.
10028
**
10029
** Called from:  ssl3_HandleClientHello                     (resuming session),
10030
**  ssl3_SendServerHelloSequence <- ssl3_HandleClientHello   (new session),
10031
**  ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
10032
*/
10033
SECStatus
10034
ssl3_SendServerHello(sslSocket *ss)
10035
6.04k
{
10036
6.04k
    SECStatus rv;
10037
6.04k
    sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
10038
6.04k
    sslBuffer messageBuf = SSL_BUFFER_EMPTY;
10039
10040
6.04k
    SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
10041
6.04k
                ss->fd));
10042
10043
6.04k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10044
6.04k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10045
10046
6.04k
    PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
10047
6.04k
    if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
10048
0
        PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
10049
0
        return SECFailure;
10050
0
    }
10051
10052
6.04k
    rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_server_hello);
10053
6.04k
    if (rv != SECSuccess) {
10054
0
        goto loser;
10055
0
    }
10056
10057
6.04k
    rv = ssl_ConstructServerHello(ss, PR_FALSE, &extensionBuf, &messageBuf);
10058
6.04k
    if (rv != SECSuccess) {
10059
0
        goto loser;
10060
0
    }
10061
10062
6.04k
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello,
10063
6.04k
                                    SSL_BUFFER_LEN(&messageBuf));
10064
6.04k
    if (rv != SECSuccess) {
10065
0
        goto loser; /* err set by AppendHandshake. */
10066
0
    }
10067
10068
6.04k
    rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&messageBuf),
10069
6.04k
                              SSL_BUFFER_LEN(&messageBuf));
10070
6.04k
    if (rv != SECSuccess) {
10071
0
        goto loser; /* err set by AppendHandshake. */
10072
0
    }
10073
10074
6.04k
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
10075
6.04k
        rv = ssl3_SetupBothPendingCipherSpecs(ss);
10076
6.04k
        if (rv != SECSuccess) {
10077
0
            goto loser; /* err set */
10078
0
        }
10079
6.04k
    }
10080
10081
6.04k
    sslBuffer_Clear(&extensionBuf);
10082
6.04k
    sslBuffer_Clear(&messageBuf);
10083
6.04k
    return SECSuccess;
10084
10085
0
loser:
10086
0
    sslBuffer_Clear(&extensionBuf);
10087
0
    sslBuffer_Clear(&messageBuf);
10088
0
    return SECFailure;
10089
6.04k
}
10090
10091
SECStatus
10092
ssl_CreateDHEKeyPair(const sslNamedGroupDef *groupDef,
10093
                     const ssl3DHParams *params,
10094
                     sslEphemeralKeyPair **keyPair)
10095
1.07k
{
10096
1.07k
    SECKEYDHParams dhParam;
10097
1.07k
    SECKEYPublicKey *pubKey = NULL;   /* Ephemeral DH key */
10098
1.07k
    SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */
10099
1.07k
    sslEphemeralKeyPair *pair;
10100
10101
1.07k
    dhParam.prime.data = params->prime.data;
10102
1.07k
    dhParam.prime.len = params->prime.len;
10103
1.07k
    dhParam.base.data = params->base.data;
10104
1.07k
    dhParam.base.len = params->base.len;
10105
10106
1.07k
    PRINT_BUF(60, (NULL, "Server DH p", dhParam.prime.data,
10107
1.07k
                   dhParam.prime.len));
10108
1.07k
    PRINT_BUF(60, (NULL, "Server DH g", dhParam.base.data,
10109
1.07k
                   dhParam.base.len));
10110
10111
    /* Generate ephemeral DH keypair */
10112
1.07k
    privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
10113
1.07k
    if (!privKey || !pubKey) {
10114
0
        ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
10115
0
        return SECFailure;
10116
0
    }
10117
10118
1.07k
    pair = ssl_NewEphemeralKeyPair(groupDef, privKey, pubKey);
10119
1.07k
    if (!pair) {
10120
0
        SECKEY_DestroyPrivateKey(privKey);
10121
0
        SECKEY_DestroyPublicKey(pubKey);
10122
10123
0
        return SECFailure;
10124
0
    }
10125
10126
1.07k
    *keyPair = pair;
10127
1.07k
    return SECSuccess;
10128
1.07k
}
10129
10130
static SECStatus
10131
ssl3_SendDHServerKeyExchange(sslSocket *ss)
10132
1.07k
{
10133
1.07k
    const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
10134
1.07k
    SECStatus rv = SECFailure;
10135
1.07k
    int length;
10136
1.07k
    SECItem signed_hash = { siBuffer, NULL, 0 };
10137
1.07k
    SSL3Hashes hashes;
10138
1.07k
    SSLHashType hashAlg;
10139
10140
1.07k
    const ssl3DHParams *params;
10141
1.07k
    sslEphemeralKeyPair *keyPair;
10142
1.07k
    SECKEYPublicKey *pubKey;
10143
1.07k
    SECKEYPrivateKey *certPrivateKey;
10144
1.07k
    const sslNamedGroupDef *groupDef;
10145
    /* Do this on the heap, this could be over 2k long. */
10146
1.07k
    sslBuffer dhBuf = SSL_BUFFER_EMPTY;
10147
10148
1.07k
    if (kea_def->kea != kea_dhe_dss && kea_def->kea != kea_dhe_rsa) {
10149
        /* TODO: Support DH_anon. It might be sufficient to drop the signature.
10150
                 See bug 1170510. */
10151
0
        PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
10152
0
        return SECFailure;
10153
0
    }
10154
10155
1.07k
    rv = ssl_SelectDHEGroup(ss, &groupDef);
10156
1.07k
    if (rv == SECFailure) {
10157
0
        PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
10158
0
        return SECFailure;
10159
0
    }
10160
1.07k
    ss->sec.keaGroup = groupDef;
10161
10162
1.07k
    params = ssl_GetDHEParams(groupDef);
10163
1.07k
    rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
10164
1.07k
    if (rv == SECFailure) {
10165
0
        ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
10166
0
        return SECFailure;
10167
0
    }
10168
1.07k
    PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs);
10169
10170
1.07k
    if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
10171
1.07k
        hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
10172
1.07k
    } else {
10173
        /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
10174
0
        hashAlg = ssl_hash_none;
10175
0
    }
10176
10177
1.07k
    pubKey = keyPair->keys->pubKey;
10178
1.07k
    PRINT_BUF(50, (ss, "DH public value:",
10179
1.07k
                   pubKey->u.dh.publicValue.data,
10180
1.07k
                   pubKey->u.dh.publicValue.len));
10181
1.07k
    rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
10182
1.07k
                               pubKey->u.dh.prime,
10183
1.07k
                               pubKey->u.dh.base,
10184
1.07k
                               pubKey->u.dh.publicValue,
10185
1.07k
                               PR_TRUE /* padY */);
10186
1.07k
    if (rv != SECSuccess) {
10187
0
        ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
10188
0
        goto loser;
10189
0
    }
10190
10191
1.07k
    certPrivateKey = ss->sec.serverCert->serverKeyPair->privKey;
10192
1.07k
    rv = ssl3_SignHashes(ss, &hashes, certPrivateKey, &signed_hash);
10193
1.07k
    if (rv != SECSuccess) {
10194
0
        goto loser; /* ssl3_SignHashes has set err. */
10195
0
    }
10196
10197
1.07k
    length = 2 + pubKey->u.dh.prime.len +
10198
1.07k
             2 + pubKey->u.dh.base.len +
10199
1.07k
             2 + pubKey->u.dh.prime.len +
10200
1.07k
             2 + signed_hash.len;
10201
10202
1.07k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
10203
1.07k
        length += 2;
10204
1.07k
    }
10205
10206
1.07k
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_key_exchange, length);
10207
1.07k
    if (rv != SECSuccess) {
10208
0
        goto loser; /* err set by AppendHandshake. */
10209
0
    }
10210
10211
1.07k
    rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.prime.data,
10212
1.07k
                                      pubKey->u.dh.prime.len, 2);
10213
1.07k
    if (rv != SECSuccess) {
10214
0
        goto loser; /* err set by AppendHandshake. */
10215
0
    }
10216
10217
1.07k
    rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.base.data,
10218
1.07k
                                      pubKey->u.dh.base.len, 2);
10219
1.07k
    if (rv != SECSuccess) {
10220
0
        goto loser; /* err set by AppendHandshake. */
10221
0
    }
10222
10223
1.07k
    rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE);
10224
1.07k
    if (rv != SECSuccess) {
10225
0
        goto loser; /* err set by AppendPaddedDHKeyShare. */
10226
0
    }
10227
1.07k
    rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
10228
1.07k
    if (rv != SECSuccess) {
10229
0
        goto loser; /* err set by AppendHandshake. */
10230
0
    }
10231
10232
1.07k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
10233
1.07k
        rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
10234
1.07k
        if (rv != SECSuccess) {
10235
0
            goto loser; /* err set by AppendHandshake. */
10236
0
        }
10237
1.07k
    }
10238
10239
1.07k
    rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
10240
1.07k
                                      signed_hash.len, 2);
10241
1.07k
    if (rv != SECSuccess) {
10242
0
        goto loser; /* err set by AppendHandshake. */
10243
0
    }
10244
10245
1.07k
    sslBuffer_Clear(&dhBuf);
10246
1.07k
    PORT_Free(signed_hash.data);
10247
1.07k
    return SECSuccess;
10248
10249
0
loser:
10250
0
    if (signed_hash.data)
10251
0
        PORT_Free(signed_hash.data);
10252
0
    sslBuffer_Clear(&dhBuf);
10253
0
    return SECFailure;
10254
1.07k
}
10255
10256
static SECStatus
10257
ssl3_SendServerKeyExchange(sslSocket *ss)
10258
5.03k
{
10259
5.03k
    const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
10260
10261
5.03k
    SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
10262
5.03k
                SSL_GETPID(), ss->fd));
10263
10264
5.03k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10265
5.03k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10266
10267
5.03k
    switch (kea_def->exchKeyType) {
10268
1.07k
        case ssl_kea_dh: {
10269
1.07k
            return ssl3_SendDHServerKeyExchange(ss);
10270
0
        }
10271
10272
3.96k
        case ssl_kea_ecdh: {
10273
3.96k
            return ssl3_SendECDHServerKeyExchange(ss);
10274
0
        }
10275
10276
0
        case ssl_kea_rsa:
10277
0
        case ssl_kea_null:
10278
0
        default:
10279
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10280
0
            break;
10281
5.03k
    }
10282
10283
0
    return SECFailure;
10284
5.03k
}
10285
10286
SECStatus
10287
ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool forCert,
10288
                   PRBool grease, sslBuffer *buf)
10289
3.51k
{
10290
3.51k
    SSLSignatureScheme filtered[MAX_SIGNATURE_SCHEMES] = { 0 };
10291
3.51k
    unsigned int filteredCount = 0;
10292
10293
3.51k
    SECStatus rv = ssl3_FilterSigAlgs(ss, minVersion, PR_FALSE, forCert,
10294
3.51k
                                      PR_ARRAY_SIZE(filtered),
10295
3.51k
                                      filtered, &filteredCount);
10296
3.51k
    if (rv != SECSuccess) {
10297
0
        return SECFailure;
10298
0
    }
10299
3.51k
    return ssl3_EncodeFilteredSigAlgs(ss, filtered, filteredCount, grease, buf);
10300
3.51k
}
10301
10302
SECStatus
10303
ssl3_EncodeFilteredSigAlgs(const sslSocket *ss, const SSLSignatureScheme *schemes,
10304
                           PRUint32 numSchemes, PRBool grease, sslBuffer *buf)
10305
3.51k
{
10306
3.51k
    if (!numSchemes) {
10307
0
        PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
10308
0
        return SECFailure;
10309
0
    }
10310
10311
3.51k
    unsigned int lengthOffset;
10312
3.51k
    SECStatus rv;
10313
10314
3.51k
    rv = sslBuffer_Skip(buf, 2, &lengthOffset);
10315
3.51k
    if (rv != SECSuccess) {
10316
0
        return SECFailure;
10317
0
    }
10318
10319
56.2k
    for (unsigned int i = 0; i < numSchemes; ++i) {
10320
52.7k
        rv = sslBuffer_AppendNumber(buf, schemes[i], 2);
10321
52.7k
        if (rv != SECSuccess) {
10322
0
            return SECFailure;
10323
0
        }
10324
52.7k
    }
10325
10326
    /* GREASE SignatureAlgorithms:
10327
     * A client MAY select one or more GREASE signature algorithm values and
10328
     * advertise them in the "signature_algorithms" or
10329
     * "signature_algorithms_cert" extensions, if sent [RFC8701, Section 3.1].
10330
     *
10331
     * When sending a CertificateRequest in TLS 1.3, a server MAY behave as
10332
     * follows: [...] A server MAY select one or more GREASE signature
10333
     * algorithm values and advertise them in the "signature_algorithms" or
10334
     * "signature_algorithms_cert" extensions, if present
10335
     * [RFC8701, Section 4.1]. */
10336
3.51k
    if (grease &&
10337
3.51k
        ((!ss->sec.isServer && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) ||
10338
0
         (ss->sec.isServer && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3))) {
10339
0
        PRUint16 value;
10340
0
        if (ss->sec.isServer) {
10341
0
            rv = tls13_RandomGreaseValue(&value);
10342
0
            if (rv != SECSuccess) {
10343
0
                return SECFailure;
10344
0
            }
10345
0
        } else {
10346
0
            value = ss->ssl3.hs.grease->idx[grease_sigalg];
10347
0
        }
10348
0
        rv = sslBuffer_AppendNumber(buf, value, 2);
10349
0
        if (rv != SECSuccess) {
10350
0
            return SECFailure;
10351
0
        }
10352
0
    }
10353
10354
3.51k
    return sslBuffer_InsertLength(buf, lengthOffset, 2);
10355
3.51k
}
10356
10357
/*
10358
 * In TLS 1.3 we are permitted to advertise support for PKCS#1
10359
 * schemes. This doesn't affect the signatures in TLS itself, just
10360
 * those on certificates. Not advertising PKCS#1 signatures creates a
10361
 * serious compatibility risk as it excludes many certificate chains
10362
 * that include PKCS#1. Hence, forCert is used to enable advertising
10363
 * PKCS#1 support. Note that we include these in signature_algorithms
10364
 * because we don't yet support signature_algorithms_cert. TLS 1.3
10365
 * requires that PKCS#1 schemes are placed last in the list if they
10366
 * are present. This sorting can be removed once we support
10367
 * signature_algorithms_cert.
10368
 */
10369
SECStatus
10370
ssl3_FilterSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool disableRsae,
10371
                   PRBool forCert,
10372
                   unsigned int maxSchemes, SSLSignatureScheme *filteredSchemes,
10373
                   unsigned int *numFilteredSchemes)
10374
3.51k
{
10375
3.51k
    PORT_Assert(filteredSchemes);
10376
3.51k
    PORT_Assert(numFilteredSchemes);
10377
3.51k
    PORT_Assert(maxSchemes >= ss->ssl3.signatureSchemeCount);
10378
3.51k
    if (maxSchemes < ss->ssl3.signatureSchemeCount) {
10379
0
        return SECFailure;
10380
0
    }
10381
10382
3.51k
    *numFilteredSchemes = 0;
10383
3.51k
    PRBool allowUnsortedPkcs1 = forCert && minVersion < SSL_LIBRARY_VERSION_TLS_1_3;
10384
56.2k
    for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
10385
52.7k
        if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
10386
0
            continue;
10387
0
        }
10388
52.7k
        if (ssl_SignatureSchemeAccepted(minVersion,
10389
52.7k
                                        ss->ssl3.signatureSchemes[i],
10390
52.7k
                                        allowUnsortedPkcs1)) {
10391
52.7k
            filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
10392
52.7k
        }
10393
52.7k
    }
10394
3.51k
    if (forCert && !allowUnsortedPkcs1) {
10395
0
        for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
10396
0
            if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
10397
0
                continue;
10398
0
            }
10399
0
            if (!ssl_SignatureSchemeAccepted(minVersion,
10400
0
                                             ss->ssl3.signatureSchemes[i],
10401
0
                                             PR_FALSE) &&
10402
0
                ssl_SignatureSchemeAccepted(minVersion,
10403
0
                                            ss->ssl3.signatureSchemes[i],
10404
0
                                            PR_TRUE)) {
10405
0
                filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
10406
0
            }
10407
0
        }
10408
0
    }
10409
3.51k
    return SECSuccess;
10410
3.51k
}
10411
10412
static SECStatus
10413
ssl3_SendCertificateRequest(sslSocket *ss)
10414
3.51k
{
10415
3.51k
    PRBool isTLS12;
10416
3.51k
    const PRUint8 *certTypes;
10417
3.51k
    SECStatus rv;
10418
3.51k
    PRUint32 length;
10419
3.51k
    const SECItem *names;
10420
3.51k
    unsigned int calen;
10421
3.51k
    unsigned int nnames;
10422
3.51k
    const SECItem *name;
10423
3.51k
    unsigned int i;
10424
3.51k
    int certTypesLength;
10425
3.51k
    PRUint8 sigAlgs[2 + MAX_SIGNATURE_SCHEMES * 2];
10426
3.51k
    sslBuffer sigAlgsBuf = SSL_BUFFER(sigAlgs);
10427
10428
3.51k
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
10429
3.51k
                SSL_GETPID(), ss->fd));
10430
10431
3.51k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10432
3.51k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10433
10434
3.51k
    isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
10435
10436
3.51k
    rv = ssl_GetCertificateRequestCAs(ss, &calen, &names, &nnames);
10437
3.51k
    if (rv != SECSuccess) {
10438
0
        return rv;
10439
0
    }
10440
3.51k
    certTypes = certificate_types;
10441
3.51k
    certTypesLength = sizeof certificate_types;
10442
10443
3.51k
    length = 1 + certTypesLength + 2 + calen;
10444
3.51k
    if (isTLS12) {
10445
3.51k
        rv = ssl3_EncodeSigAlgs(ss, ss->version, PR_TRUE /* forCert */,
10446
3.51k
                                PR_FALSE /* GREASE */, &sigAlgsBuf);
10447
3.51k
        if (rv != SECSuccess) {
10448
0
            return rv;
10449
0
        }
10450
3.51k
        length += SSL_BUFFER_LEN(&sigAlgsBuf);
10451
3.51k
    }
10452
10453
3.51k
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request, length);
10454
3.51k
    if (rv != SECSuccess) {
10455
0
        return rv; /* err set by AppendHandshake. */
10456
0
    }
10457
3.51k
    rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
10458
3.51k
    if (rv != SECSuccess) {
10459
0
        return rv; /* err set by AppendHandshake. */
10460
0
    }
10461
3.51k
    if (isTLS12) {
10462
3.51k
        rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&sigAlgsBuf),
10463
3.51k
                                  SSL_BUFFER_LEN(&sigAlgsBuf));
10464
3.51k
        if (rv != SECSuccess) {
10465
0
            return rv; /* err set by AppendHandshake. */
10466
0
        }
10467
3.51k
    }
10468
3.51k
    rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
10469
3.51k
    if (rv != SECSuccess) {
10470
0
        return rv; /* err set by AppendHandshake. */
10471
0
    }
10472
3.51k
    for (i = 0, name = names; i < nnames; i++, name++) {
10473
0
        rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
10474
0
        if (rv != SECSuccess) {
10475
0
            return rv; /* err set by AppendHandshake. */
10476
0
        }
10477
0
    }
10478
10479
3.51k
    return SECSuccess;
10480
3.51k
}
10481
10482
static SECStatus
10483
ssl3_SendServerHelloDone(sslSocket *ss)
10484
6.04k
{
10485
6.04k
    SECStatus rv;
10486
10487
6.04k
    SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
10488
6.04k
                SSL_GETPID(), ss->fd));
10489
10490
6.04k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10491
6.04k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10492
10493
6.04k
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello_done, 0);
10494
6.04k
    if (rv != SECSuccess) {
10495
0
        return rv; /* err set by AppendHandshake. */
10496
0
    }
10497
6.04k
    rv = ssl3_FlushHandshake(ss, 0);
10498
6.04k
    if (rv != SECSuccess) {
10499
0
        return rv; /* error code set by ssl3_FlushHandshake */
10500
0
    }
10501
6.04k
    return SECSuccess;
10502
6.04k
}
10503
10504
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10505
 * a complete ssl3 Certificate Verify message
10506
 * Caller must hold Handshake and RecvBuf locks.
10507
 */
10508
static SECStatus
10509
ssl3_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
10510
3
{
10511
3
    SECItem signed_hash = { siBuffer, NULL, 0 };
10512
3
    SECStatus rv;
10513
3
    int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
10514
3
    SSL3AlertDescription desc = handshake_failure;
10515
3
    PRBool isTLS;
10516
3
    SSLSignatureScheme sigScheme;
10517
3
    SSL3Hashes hashes;
10518
3
    const PRUint8 *savedMsg = b;
10519
3
    const PRUint32 savedLen = length;
10520
10521
3
    SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
10522
3
                SSL_GETPID(), ss->fd));
10523
3
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10524
3
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10525
10526
3
    if (ss->ssl3.hs.ws != wait_cert_verify) {
10527
3
        desc = unexpected_message;
10528
3
        errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
10529
3
        goto alert_loser;
10530
3
    }
10531
10532
    /* TLS 1.3 is handled by tls13_HandleCertificateVerify */
10533
0
    PORT_Assert(ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2);
10534
10535
0
    if (ss->ssl3.prSpec->version == SSL_LIBRARY_VERSION_TLS_1_2) {
10536
0
        PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_record);
10537
0
        rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
10538
0
        if (rv != SECSuccess) {
10539
0
            if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
10540
0
                errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
10541
0
            }
10542
0
            goto loser; /* alert already sent */
10543
0
        }
10544
0
        rv = ssl_CheckSignatureSchemeConsistency(
10545
0
            ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo);
10546
0
        if (rv != SECSuccess) {
10547
0
            errCode = PORT_GetError();
10548
0
            desc = illegal_parameter;
10549
0
            goto alert_loser;
10550
0
        }
10551
10552
0
        rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
10553
0
                                       ss->ssl3.hs.messages.len,
10554
0
                                       ssl_SignatureSchemeToHashType(sigScheme),
10555
0
                                       &hashes);
10556
0
    } else {
10557
0
        PORT_Assert(ss->ssl3.hs.hashType != handshake_hash_record);
10558
0
        sigScheme = ssl_sig_none;
10559
0
        rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.prSpec, &hashes, 0);
10560
0
    }
10561
10562
0
    if (rv != SECSuccess) {
10563
0
        errCode = SSL_ERROR_DIGEST_FAILURE;
10564
0
        desc = decrypt_error;
10565
0
        goto alert_loser;
10566
0
    }
10567
10568
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
10569
0
    if (rv != SECSuccess) {
10570
0
        goto loser; /* malformed. */
10571
0
    }
10572
10573
0
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
10574
10575
    /* XXX verify that the key & kea match */
10576
0
    rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signed_hash);
10577
0
    if (rv != SECSuccess) {
10578
0
        errCode = PORT_GetError();
10579
0
        desc = isTLS ? decrypt_error : handshake_failure;
10580
0
        goto alert_loser;
10581
0
    }
10582
10583
0
    signed_hash.data = NULL;
10584
10585
0
    if (length != 0) {
10586
0
        desc = isTLS ? decode_error : illegal_parameter;
10587
0
        goto alert_loser; /* malformed */
10588
0
    }
10589
10590
0
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify,
10591
0
                                  savedMsg, savedLen);
10592
0
    if (rv != SECSuccess) {
10593
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10594
0
        return rv;
10595
0
    }
10596
10597
0
    ss->ssl3.hs.ws = wait_change_cipher;
10598
0
    return SECSuccess;
10599
10600
3
alert_loser:
10601
3
    SSL3_SendAlert(ss, alert_fatal, desc);
10602
3
loser:
10603
3
    PORT_SetError(errCode);
10604
3
    return SECFailure;
10605
3
}
10606
10607
/* find a slot that is able to generate a PMS and wrap it with RSA.
10608
 * Then generate and return the PMS.
10609
 * If the serverKeySlot parameter is non-null, this function will use
10610
 * that slot to do the job, otherwise it will find a slot.
10611
 *
10612
 * Called from  ssl3_DeriveConnectionKeys()  (above)
10613
 *      ssl3_SendRSAClientKeyExchange()     (above)
10614
 *      ssl3_HandleRSAClientKeyExchange()  (below)
10615
 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
10616
 */
10617
static PK11SymKey *
10618
ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
10619
                    PK11SlotInfo *serverKeySlot)
10620
2
{
10621
2
    PK11SymKey *pms = NULL;
10622
2
    PK11SlotInfo *slot = serverKeySlot;
10623
2
    void *pwArg = ss->pkcs11PinArg;
10624
2
    SECItem param;
10625
2
    CK_VERSION version;
10626
2
    CK_MECHANISM_TYPE mechanism_array[3];
10627
10628
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10629
10630
2
    if (slot == NULL) {
10631
0
        SSLCipherAlgorithm calg;
10632
        /* The specReadLock would suffice here, but we cannot assert on
10633
        ** read locks.  Also, all the callers who call with a non-null
10634
        ** slot already hold the SpecWriteLock.
10635
        */
10636
0
        PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
10637
0
        PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
10638
10639
0
        calg = spec->cipherDef->calg;
10640
10641
        /* First get an appropriate slot.  */
10642
0
        mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
10643
0
        mechanism_array[1] = CKM_RSA_PKCS;
10644
0
        mechanism_array[2] = ssl3_Alg2Mech(calg);
10645
10646
0
        slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
10647
0
        if (slot == NULL) {
10648
            /* can't find a slot with all three, find a slot with the minimum */
10649
0
            slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
10650
0
            if (slot == NULL) {
10651
0
                PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
10652
0
                return pms; /* which is NULL */
10653
0
            }
10654
0
        }
10655
0
    }
10656
10657
    /* Generate the pre-master secret ...  */
10658
2
    if (IS_DTLS(ss)) {
10659
2
        SSL3ProtocolVersion temp;
10660
10661
2
        temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
10662
2
        version.major = MSB(temp);
10663
2
        version.minor = LSB(temp);
10664
2
    } else {
10665
0
        version.major = MSB(ss->clientHelloVersion);
10666
0
        version.minor = LSB(ss->clientHelloVersion);
10667
0
    }
10668
10669
2
    param.data = (unsigned char *)&version;
10670
2
    param.len = sizeof version;
10671
10672
2
    pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
10673
2
    if (!serverKeySlot)
10674
0
        PK11_FreeSlot(slot);
10675
2
    if (pms == NULL) {
10676
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10677
0
    }
10678
2
    return pms;
10679
2
}
10680
10681
static void
10682
ssl3_CSwapPK11SymKey(PK11SymKey **x, PK11SymKey **y, PRBool c)
10683
4
{
10684
4
    uintptr_t mask = (uintptr_t)c;
10685
4
    unsigned int i;
10686
28
    for (i = 1; i < sizeof(uintptr_t) * 8; i <<= 1) {
10687
24
        mask |= mask << i;
10688
24
    }
10689
4
    uintptr_t x_ptr = (uintptr_t)*x;
10690
4
    uintptr_t y_ptr = (uintptr_t)*y;
10691
4
    uintptr_t tmp = (x_ptr ^ y_ptr) & mask;
10692
4
    x_ptr = x_ptr ^ tmp;
10693
4
    y_ptr = y_ptr ^ tmp;
10694
4
    *x = (PK11SymKey *)x_ptr;
10695
4
    *y = (PK11SymKey *)y_ptr;
10696
4
}
10697
10698
/* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
10699
 * return any indication of failure of the Client Key Exchange message,
10700
 * where that failure is caused by the content of the client's message.
10701
 * This function must not return SECFailure for any reason that is directly
10702
 * or indirectly caused by the content of the client's encrypted PMS.
10703
 * We must not send an alert and also not drop the connection.
10704
 * Instead, we generate a random PMS.  This will cause a failure
10705
 * in the processing the finished message, which is exactly where
10706
 * the failure must occur.
10707
 *
10708
 * Called from ssl3_HandleClientKeyExchange
10709
 */
10710
static SECStatus
10711
ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
10712
                                PRUint8 *b,
10713
                                PRUint32 length,
10714
                                sslKeyPair *serverKeyPair)
10715
2
{
10716
2
    SECStatus rv;
10717
2
    SECItem enc_pms;
10718
2
    PK11SymKey *pms = NULL;
10719
2
    PK11SymKey *fauxPms = NULL;
10720
2
    PK11SlotInfo *slot = NULL;
10721
10722
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10723
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10724
2
    PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
10725
10726
2
    enc_pms.data = b;
10727
2
    enc_pms.len = length;
10728
10729
2
    if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
10730
2
        PRUint32 kLen;
10731
2
        rv = ssl3_ConsumeHandshakeNumber(ss, &kLen, 2, &enc_pms.data, &enc_pms.len);
10732
2
        if (rv != SECSuccess) {
10733
0
            PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10734
0
            return SECFailure;
10735
0
        }
10736
2
        if ((unsigned)kLen < enc_pms.len) {
10737
0
            enc_pms.len = kLen;
10738
0
        }
10739
2
    }
10740
10741
    /*
10742
     * Get as close to algorithm 2 from RFC 5246; Section 7.4.7.1
10743
     * as we can within the constraints of the PKCS#11 interface.
10744
     *
10745
     * 1. Unconditionally generate a bogus PMS (what RFC 5246
10746
     *    calls R).
10747
     * 2. Attempt the RSA decryption to recover the PMS (what
10748
     *    RFC 5246 calls M).
10749
     * 3. Set PMS = (M == NULL) ? R : M
10750
     * 4. Use ssl3_ComputeMasterSecret(PMS) to attempt to derive
10751
     *    the MS from PMS. This includes performing the version
10752
     *    check and length check.
10753
     * 5. If either the initial RSA decryption failed or
10754
     *    ssl3_ComputeMasterSecret(PMS) failed, then discard
10755
     *    M and set PMS = R. Else, discard R and set PMS = M.
10756
     *
10757
     * We do two derivations here because we can't rely on having
10758
     * a function that only performs the PMS version and length
10759
     * check. The only redundant cost is that this runs the PRF,
10760
     * which isn't necessary here.
10761
     */
10762
10763
    /* Generate the bogus PMS (R) */
10764
2
    slot = PK11_GetSlotFromPrivateKey(serverKeyPair->privKey);
10765
2
    if (!slot) {
10766
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10767
0
        return SECFailure;
10768
0
    }
10769
10770
2
    if (!PK11_DoesMechanism(slot, CKM_SSL3_MASTER_KEY_DERIVE)) {
10771
0
        PK11_FreeSlot(slot);
10772
0
        slot = PK11_GetBestSlot(CKM_SSL3_MASTER_KEY_DERIVE, NULL);
10773
0
        if (!slot) {
10774
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10775
0
            return SECFailure;
10776
0
        }
10777
0
    }
10778
10779
2
    ssl_GetSpecWriteLock(ss);
10780
2
    fauxPms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
10781
2
    ssl_ReleaseSpecWriteLock(ss);
10782
2
    PK11_FreeSlot(slot);
10783
10784
2
    if (fauxPms == NULL) {
10785
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10786
0
        return SECFailure;
10787
0
    }
10788
10789
    /*
10790
     * unwrap pms out of the incoming buffer
10791
     * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
10792
     *  the unwrap.  Rather, it is the mechanism with which the
10793
     *      unwrapped pms will be used.
10794
     */
10795
2
    pms = PK11_PubUnwrapSymKey(serverKeyPair->privKey, &enc_pms,
10796
2
                               CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
10797
    /* Temporarily use the PMS if unwrapping the real PMS fails. */
10798
2
    ssl3_CSwapPK11SymKey(&pms, &fauxPms, pms == NULL);
10799
10800
    /* Attempt to derive the MS from the PMS. This is the only way to
10801
     * check the version field in the RSA PMS. If this fails, we
10802
     * then use the faux PMS in place of the PMS. Note that this
10803
     * operation should never fail if we are using the faux PMS
10804
     * since it is correctly formatted. */
10805
2
    rv = ssl3_ComputeMasterSecret(ss, pms, NULL);
10806
10807
    /* If we succeeded, then select the true PMS, else select the FPMS. */
10808
2
    ssl3_CSwapPK11SymKey(&pms, &fauxPms, (rv != SECSuccess) & (fauxPms != NULL));
10809
10810
    /* This step will derive the MS from the PMS, among other things. */
10811
2
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
10812
10813
    /* Clear both PMS. */
10814
2
    PK11_FreeSymKey(pms);
10815
2
    PK11_FreeSymKey(fauxPms);
10816
10817
2
    if (rv != SECSuccess) {
10818
0
        (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10819
0
        return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
10820
0
    }
10821
10822
2
    return SECSuccess;
10823
2
}
10824
10825
static SECStatus
10826
ssl3_HandleDHClientKeyExchange(sslSocket *ss,
10827
                               PRUint8 *b,
10828
                               PRUint32 length,
10829
                               sslKeyPair *serverKeyPair)
10830
11
{
10831
11
    PK11SymKey *pms;
10832
11
    SECStatus rv;
10833
11
    SECKEYPublicKey clntPubKey;
10834
11
    CK_MECHANISM_TYPE target;
10835
11
    PRBool isTLS;
10836
10837
11
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10838
11
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10839
10840
11
    clntPubKey.keyType = dhKey;
10841
11
    clntPubKey.u.dh.prime.len = serverKeyPair->pubKey->u.dh.prime.len;
10842
11
    clntPubKey.u.dh.prime.data = serverKeyPair->pubKey->u.dh.prime.data;
10843
11
    clntPubKey.u.dh.base.len = serverKeyPair->pubKey->u.dh.base.len;
10844
11
    clntPubKey.u.dh.base.data = serverKeyPair->pubKey->u.dh.base.data;
10845
10846
11
    rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.dh.publicValue,
10847
11
                                       2, &b, &length);
10848
11
    if (rv != SECSuccess) {
10849
1
        return SECFailure;
10850
1
    }
10851
10852
10
    if (!ssl_IsValidDHEShare(&serverKeyPair->pubKey->u.dh.prime,
10853
10
                             &clntPubKey.u.dh.publicValue)) {
10854
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE);
10855
0
        return SECFailure;
10856
0
    }
10857
10858
10
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
10859
10860
10
    if (isTLS)
10861
10
        target = CKM_TLS_MASTER_KEY_DERIVE_DH;
10862
0
    else
10863
0
        target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
10864
10865
    /* Determine the PMS */
10866
10
    pms = PK11_PubDerive(serverKeyPair->privKey, &clntPubKey, PR_FALSE, NULL, NULL,
10867
10
                         CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
10868
10
    if (pms == NULL) {
10869
0
        ssl_FreeEphemeralKeyPairs(ss);
10870
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10871
0
        return SECFailure;
10872
0
    }
10873
10874
10
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
10875
10
    PK11_FreeSymKey(pms);
10876
10
    ssl_FreeEphemeralKeyPairs(ss);
10877
10
    return rv;
10878
10
}
10879
10880
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10881
 * a complete ssl3 ClientKeyExchange message from the remote client
10882
 * Caller must hold Handshake and RecvBuf locks.
10883
 */
10884
static SECStatus
10885
ssl3_HandleClientKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
10886
3.21k
{
10887
3.21k
    sslKeyPair *serverKeyPair = NULL;
10888
3.21k
    SECStatus rv;
10889
3.21k
    const ssl3KEADef *kea_def;
10890
10891
3.21k
    SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
10892
3.21k
                SSL_GETPID(), ss->fd));
10893
10894
3.21k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10895
3.21k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10896
10897
3.21k
    if (ss->ssl3.hs.ws != wait_client_key) {
10898
3.20k
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10899
3.20k
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
10900
3.20k
        return SECFailure;
10901
3.20k
    }
10902
10903
18
    kea_def = ss->ssl3.hs.kea_def;
10904
10905
18
    if (kea_def->ephemeral) {
10906
16
        sslEphemeralKeyPair *keyPair;
10907
        /* There should be exactly one pair. */
10908
16
        PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
10909
16
        PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==
10910
16
                    PR_NEXT_LINK(&ss->ephemeralKeyPairs));
10911
16
        keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs);
10912
16
        serverKeyPair = keyPair->keys;
10913
16
        ss->sec.keaKeyBits =
10914
16
            SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
10915
16
    } else {
10916
2
        serverKeyPair = ss->sec.serverCert->serverKeyPair;
10917
2
        ss->sec.keaKeyBits = ss->sec.serverCert->serverKeyBits;
10918
2
    }
10919
10920
18
    if (!serverKeyPair) {
10921
0
        SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10922
0
        PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
10923
0
        return SECFailure;
10924
0
    }
10925
18
    PORT_Assert(serverKeyPair->pubKey);
10926
18
    PORT_Assert(serverKeyPair->privKey);
10927
10928
18
    ss->sec.keaType = kea_def->exchKeyType;
10929
10930
18
    switch (kea_def->exchKeyType) {
10931
2
        case ssl_kea_rsa:
10932
2
            rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKeyPair);
10933
2
            break;
10934
10935
11
        case ssl_kea_dh:
10936
11
            rv = ssl3_HandleDHClientKeyExchange(ss, b, length, serverKeyPair);
10937
11
            break;
10938
10939
5
        case ssl_kea_ecdh:
10940
5
            rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, serverKeyPair);
10941
5
            break;
10942
10943
0
        default:
10944
0
            (void)ssl3_HandshakeFailure(ss);
10945
0
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
10946
0
            return SECFailure;
10947
18
    }
10948
18
    ssl_FreeEphemeralKeyPairs(ss);
10949
18
    if (rv == SECSuccess) {
10950
15
        ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
10951
15
    } else {
10952
        /* PORT_SetError has been called by all the Handle*ClientKeyExchange
10953
         * functions above.  However, not all error paths result in an alert, so
10954
         * this ensures that the server knows about the error.  Note that if an
10955
         * alert was already sent, SSL3_SendAlert() is a noop. */
10956
3
        PRErrorCode errCode = PORT_GetError();
10957
3
        (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10958
3
        PORT_SetError(errCode);
10959
3
    }
10960
18
    return rv;
10961
18
}
10962
10963
/* This is TLS's equivalent of sending a no_certificate alert. */
10964
SECStatus
10965
ssl3_SendEmptyCertificate(sslSocket *ss)
10966
0
{
10967
0
    SECStatus rv;
10968
0
    unsigned int len = 0;
10969
0
    PRBool isTLS13 = PR_FALSE;
10970
0
    const SECItem *context;
10971
10972
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
10973
0
        PORT_Assert(ss->ssl3.hs.clientCertRequested);
10974
0
        context = &ss->xtnData.certReqContext;
10975
0
        len = context->len + 1;
10976
0
        isTLS13 = PR_TRUE;
10977
0
    }
10978
10979
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate, len + 3);
10980
0
    if (rv != SECSuccess) {
10981
0
        return rv;
10982
0
    }
10983
10984
0
    if (isTLS13) {
10985
0
        rv = ssl3_AppendHandshakeVariable(ss, context->data, context->len, 1);
10986
0
        if (rv != SECSuccess) {
10987
0
            return rv;
10988
0
        }
10989
0
    }
10990
10991
0
    return ssl3_AppendHandshakeNumber(ss, 0, 3);
10992
0
}
10993
10994
/*
10995
 * NewSessionTicket
10996
 * Called from ssl3_HandleFinished
10997
 */
10998
static SECStatus
10999
ssl3_SendNewSessionTicket(sslSocket *ss)
11000
0
{
11001
0
    SECItem ticket = { 0, NULL, 0 };
11002
0
    SECStatus rv;
11003
0
    NewSessionTicket nticket = { 0 };
11004
11005
0
    rv = ssl3_EncodeSessionTicket(ss, &nticket, NULL, 0,
11006
0
                                  ss->ssl3.pwSpec->masterSecret, &ticket);
11007
0
    if (rv != SECSuccess)
11008
0
        goto loser;
11009
11010
    /* Serialize the handshake message. Length =
11011
     * lifetime (4) + ticket length (2) + ticket. */
11012
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
11013
0
                                    4 + 2 + ticket.len);
11014
0
    if (rv != SECSuccess)
11015
0
        goto loser;
11016
11017
    /* This is a fixed value. */
11018
0
    rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
11019
0
    if (rv != SECSuccess)
11020
0
        goto loser;
11021
11022
    /* Encode the ticket. */
11023
0
    rv = ssl3_AppendHandshakeVariable(ss, ticket.data, ticket.len, 2);
11024
0
    if (rv != SECSuccess)
11025
0
        goto loser;
11026
11027
0
    rv = SECSuccess;
11028
11029
0
loser:
11030
0
    if (ticket.data) {
11031
0
        SECITEM_FreeItem(&ticket, PR_FALSE);
11032
0
    }
11033
0
    return rv;
11034
0
}
11035
11036
static SECStatus
11037
ssl3_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
11038
0
{
11039
0
    SECStatus rv;
11040
0
    SECItem ticketData;
11041
0
    PRUint32 temp;
11042
11043
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
11044
0
                SSL_GETPID(), ss->fd));
11045
11046
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11047
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11048
11049
0
    PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
11050
0
    PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket);
11051
11052
0
    if (ss->ssl3.hs.ws != wait_new_session_ticket) {
11053
0
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11054
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
11055
0
        return SECFailure;
11056
0
    }
11057
11058
    /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid
11059
     * until it has verified the server's Finished message." See the comment in
11060
     * ssl3_FinishHandshake for more details.
11061
     */
11062
0
    ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(ss);
11063
0
    if (length < 4) {
11064
0
        (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
11065
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
11066
0
        return SECFailure;
11067
0
    }
11068
11069
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 4, &b, &length);
11070
0
    if (rv != SECSuccess) {
11071
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
11072
0
        return SECFailure;
11073
0
    }
11074
0
    ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = temp;
11075
11076
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length);
11077
0
    if (rv != SECSuccess || length != 0) {
11078
0
        (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
11079
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
11080
0
        return SECFailure; /* malformed */
11081
0
    }
11082
    /* If the server sent a zero-length ticket, ignore it and keep the
11083
     * existing ticket. */
11084
0
    if (ticketData.len != 0) {
11085
0
        rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket,
11086
0
                              &ticketData);
11087
0
        if (rv != SECSuccess) {
11088
0
            return rv;
11089
0
        }
11090
0
        ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE;
11091
0
    }
11092
11093
0
    ss->ssl3.hs.ws = wait_change_cipher;
11094
0
    return SECSuccess;
11095
0
}
11096
11097
#ifdef NISCC_TEST
11098
static PRInt32 connNum = 0;
11099
11100
static SECStatus
11101
get_fake_cert(SECItem *pCertItem, int *pIndex)
11102
{
11103
    PRFileDesc *cf;
11104
    char *testdir;
11105
    char *startat;
11106
    char *stopat;
11107
    const char *extension;
11108
    int fileNum;
11109
    PRInt32 numBytes = 0;
11110
    PRStatus prStatus;
11111
    PRFileInfo info;
11112
    char cfn[100];
11113
11114
    pCertItem->data = 0;
11115
    if ((testdir = PR_GetEnvSecure("NISCC_TEST")) == NULL) {
11116
        return SECSuccess;
11117
    }
11118
    *pIndex = (NULL != strstr(testdir, "root"));
11119
    extension = (strstr(testdir, "simple") ? "" : ".der");
11120
    fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1;
11121
    if ((startat = PR_GetEnvSecure("START_AT")) != NULL) {
11122
        fileNum += atoi(startat);
11123
    }
11124
    if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL &&
11125
        fileNum >= atoi(stopat)) {
11126
        *pIndex = -1;
11127
        return SECSuccess;
11128
    }
11129
    snprintf(cfn, sizeof(cfn), "%s/%08d%s", testdir, fileNum, extension);
11130
    cf = PR_Open(cfn, PR_RDONLY, 0);
11131
    if (!cf) {
11132
        goto loser;
11133
    }
11134
    prStatus = PR_GetOpenFileInfo(cf, &info);
11135
    if (prStatus != PR_SUCCESS) {
11136
        PR_Close(cf);
11137
        goto loser;
11138
    }
11139
    pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
11140
    if (pCertItem) {
11141
        numBytes = PR_Read(cf, pCertItem->data, info.size);
11142
    }
11143
    PR_Close(cf);
11144
    if (numBytes != info.size) {
11145
        SECITEM_FreeItem(pCertItem, PR_FALSE);
11146
        PORT_SetError(SEC_ERROR_IO);
11147
        goto loser;
11148
    }
11149
    fprintf(stderr, "using %s\n", cfn);
11150
    return SECSuccess;
11151
11152
loser:
11153
    fprintf(stderr, "failed to use %s\n", cfn);
11154
    *pIndex = -1;
11155
    return SECFailure;
11156
}
11157
#endif
11158
11159
/*
11160
 * Used by both client and server.
11161
 * Called from HandleServerHelloDone and from SendServerHelloSequence.
11162
 */
11163
static SECStatus
11164
ssl3_SendCertificate(sslSocket *ss)
11165
6.04k
{
11166
6.04k
    SECStatus rv;
11167
6.04k
    CERTCertificateList *certChain;
11168
6.04k
    int certChainLen = 0;
11169
6.04k
    int i;
11170
#ifdef NISCC_TEST
11171
    SECItem fakeCert;
11172
    int ndex = -1;
11173
#endif
11174
6.04k
    PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
11175
6.04k
    SECItem context = { siBuffer, NULL, 0 };
11176
6.04k
    unsigned int contextLen = 0;
11177
11178
6.04k
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
11179
6.04k
                SSL_GETPID(), ss->fd));
11180
11181
6.04k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11182
6.04k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11183
6.04k
    PR_ASSERT(!ss->ssl3.hs.clientCertificatePending);
11184
11185
6.04k
    if (ss->sec.localCert)
11186
0
        CERT_DestroyCertificate(ss->sec.localCert);
11187
6.04k
    if (ss->sec.isServer) {
11188
        /* A server certificate is selected in ssl3_HandleClientHello. */
11189
6.04k
        PORT_Assert(ss->sec.serverCert);
11190
11191
6.04k
        certChain = ss->sec.serverCert->serverCertChain;
11192
6.04k
        ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
11193
6.04k
    } else {
11194
0
        certChain = ss->ssl3.clientCertChain;
11195
0
        ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
11196
0
    }
11197
11198
#ifdef NISCC_TEST
11199
    rv = get_fake_cert(&fakeCert, &ndex);
11200
#endif
11201
11202
6.04k
    if (isTLS13) {
11203
0
        contextLen = 1; /* Size of the context length */
11204
0
        if (!ss->sec.isServer) {
11205
0
            PORT_Assert(ss->ssl3.hs.clientCertRequested);
11206
0
            context = ss->xtnData.certReqContext;
11207
0
            contextLen += context.len;
11208
0
        }
11209
0
    }
11210
6.04k
    if (certChain) {
11211
12.0k
        for (i = 0; i < certChain->len; i++) {
11212
#ifdef NISCC_TEST
11213
            if (fakeCert.len > 0 && i == ndex) {
11214
                certChainLen += fakeCert.len + 3;
11215
            } else {
11216
                certChainLen += certChain->certs[i].len + 3;
11217
            }
11218
#else
11219
6.04k
            certChainLen += certChain->certs[i].len + 3;
11220
6.04k
#endif
11221
6.04k
        }
11222
6.04k
    }
11223
11224
6.04k
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate,
11225
6.04k
                                    contextLen + certChainLen + 3);
11226
6.04k
    if (rv != SECSuccess) {
11227
0
        return rv; /* err set by AppendHandshake. */
11228
0
    }
11229
11230
6.04k
    if (isTLS13) {
11231
0
        rv = ssl3_AppendHandshakeVariable(ss, context.data,
11232
0
                                          context.len, 1);
11233
0
        if (rv != SECSuccess) {
11234
0
            return rv; /* err set by AppendHandshake. */
11235
0
        }
11236
0
    }
11237
11238
6.04k
    rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3);
11239
6.04k
    if (rv != SECSuccess) {
11240
0
        return rv; /* err set by AppendHandshake. */
11241
0
    }
11242
6.04k
    if (certChain) {
11243
12.0k
        for (i = 0; i < certChain->len; i++) {
11244
#ifdef NISCC_TEST
11245
            if (fakeCert.len > 0 && i == ndex) {
11246
                rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
11247
                                                  fakeCert.len, 3);
11248
                SECITEM_FreeItem(&fakeCert, PR_FALSE);
11249
            } else {
11250
                rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
11251
                                                  certChain->certs[i].len, 3);
11252
            }
11253
#else
11254
6.04k
            rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
11255
6.04k
                                              certChain->certs[i].len, 3);
11256
6.04k
#endif
11257
6.04k
            if (rv != SECSuccess) {
11258
0
                return rv; /* err set by AppendHandshake. */
11259
0
            }
11260
6.04k
        }
11261
6.04k
    }
11262
11263
6.04k
    return SECSuccess;
11264
6.04k
}
11265
11266
/*
11267
 * Used by server only.
11268
 * single-stapling, send only a single cert status
11269
 */
11270
SECStatus
11271
ssl3_SendCertificateStatus(sslSocket *ss)
11272
6.04k
{
11273
6.04k
    SECStatus rv;
11274
6.04k
    int len = 0;
11275
6.04k
    SECItemArray *statusToSend = NULL;
11276
6.04k
    const sslServerCert *serverCert;
11277
11278
6.04k
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
11279
6.04k
                SSL_GETPID(), ss->fd));
11280
11281
6.04k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11282
6.04k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11283
6.04k
    PORT_Assert(ss->sec.isServer);
11284
11285
6.04k
    if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
11286
6.02k
        return SECSuccess;
11287
11288
    /* Use certStatus based on the cert being used. */
11289
16
    serverCert = ss->sec.serverCert;
11290
16
    if (serverCert->certStatusArray && serverCert->certStatusArray->len) {
11291
0
        statusToSend = serverCert->certStatusArray;
11292
0
    }
11293
16
    if (!statusToSend)
11294
16
        return SECSuccess;
11295
11296
    /* Use the array's first item only (single stapling) */
11297
0
    len = 1 + statusToSend->items[0].len + 3;
11298
11299
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_status, len);
11300
0
    if (rv != SECSuccess) {
11301
0
        return rv; /* err set by AppendHandshake. */
11302
0
    }
11303
0
    rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
11304
0
    if (rv != SECSuccess)
11305
0
        return rv; /* err set by AppendHandshake. */
11306
11307
0
    rv = ssl3_AppendHandshakeVariable(ss,
11308
0
                                      statusToSend->items[0].data,
11309
0
                                      statusToSend->items[0].len,
11310
0
                                      3);
11311
0
    if (rv != SECSuccess)
11312
0
        return rv; /* err set by AppendHandshake. */
11313
11314
0
    return SECSuccess;
11315
0
}
11316
11317
/* This is used to delete the CA certificates in the peer certificate chain
11318
 * from the cert database after they've been validated.
11319
 */
11320
void
11321
ssl3_CleanupPeerCerts(sslSocket *ss)
11322
10
{
11323
10
    PLArenaPool *arena = ss->ssl3.peerCertArena;
11324
10
    ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
11325
11326
10
    for (; certs; certs = certs->next) {
11327
0
        CERT_DestroyCertificate(certs->cert);
11328
0
    }
11329
10
    if (arena)
11330
3
        PORT_FreeArena(arena, PR_FALSE);
11331
10
    ss->ssl3.peerCertArena = NULL;
11332
10
    ss->ssl3.peerCertChain = NULL;
11333
11334
10
    if (ss->sec.peerCert != NULL) {
11335
0
        if (ss->sec.peerKey) {
11336
0
            SECKEY_DestroyPublicKey(ss->sec.peerKey);
11337
0
            ss->sec.peerKey = NULL;
11338
0
        }
11339
0
        CERT_DestroyCertificate(ss->sec.peerCert);
11340
0
        ss->sec.peerCert = NULL;
11341
0
    }
11342
10
}
11343
11344
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11345
 * a complete ssl3 CertificateStatus message.
11346
 * Caller must hold Handshake and RecvBuf locks.
11347
 */
11348
static SECStatus
11349
ssl3_HandleCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
11350
3
{
11351
3
    SECStatus rv;
11352
11353
3
    if (ss->ssl3.hs.ws != wait_certificate_status) {
11354
3
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11355
3
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
11356
3
        return SECFailure;
11357
3
    }
11358
11359
0
    rv = ssl_ReadCertificateStatus(ss, b, length);
11360
0
    if (rv != SECSuccess) {
11361
0
        return SECFailure; /* code already set */
11362
0
    }
11363
11364
0
    return ssl3_AuthCertificate(ss);
11365
0
}
11366
11367
SECStatus
11368
ssl_ReadCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
11369
0
{
11370
0
    PRUint32 status, len;
11371
0
    SECStatus rv;
11372
11373
0
    PORT_Assert(!ss->sec.isServer);
11374
11375
    /* Consume the CertificateStatusType enum */
11376
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &status, 1, &b, &length);
11377
0
    if (rv != SECSuccess || status != 1 /* ocsp */) {
11378
0
        return ssl3_DecodeError(ss);
11379
0
    }
11380
11381
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &len, 3, &b, &length);
11382
0
    if (rv != SECSuccess || len != length) {
11383
0
        return ssl3_DecodeError(ss);
11384
0
    }
11385
11386
0
#define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */
11387
0
    if (length > MAX_CERTSTATUS_LEN) {
11388
0
        ssl3_DecodeError(ss); /* sets error code */
11389
0
        return SECFailure;
11390
0
    }
11391
0
#undef MAX_CERTSTATUS_LEN
11392
11393
    /* Array size 1, because we currently implement single-stapling only */
11394
0
    SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
11395
0
    if (!ss->sec.ci.sid->peerCertStatus.items)
11396
0
        return SECFailure; /* code already set */
11397
11398
0
    ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
11399
11400
0
    if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
11401
0
        SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
11402
0
        return SECFailure; /* code already set */
11403
0
    }
11404
11405
0
    PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
11406
0
    ss->sec.ci.sid->peerCertStatus.items[0].len = length;
11407
0
    ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
11408
0
    return SECSuccess;
11409
0
}
11410
11411
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11412
 * a complete ssl3 Certificate message.
11413
 * Caller must hold Handshake and RecvBuf locks.
11414
 */
11415
static SECStatus
11416
ssl3_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
11417
2.15k
{
11418
2.15k
    SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
11419
2.15k
                SSL_GETPID(), ss->fd));
11420
2.15k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11421
2.15k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11422
11423
2.15k
    if ((ss->sec.isServer && ss->ssl3.hs.ws != wait_client_cert) ||
11424
2.15k
        (!ss->sec.isServer && ss->ssl3.hs.ws != wait_server_cert)) {
11425
2.15k
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11426
2.15k
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE);
11427
2.15k
        return SECFailure;
11428
2.15k
    }
11429
11430
4
    if (ss->sec.isServer) {
11431
4
        dtls_ReceivedFirstMessageInFlight(ss);
11432
4
    }
11433
11434
4
    return ssl3_CompleteHandleCertificate(ss, b, length);
11435
2.15k
}
11436
11437
/* Called from ssl3_HandleCertificate
11438
 */
11439
SECStatus
11440
ssl3_CompleteHandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
11441
4
{
11442
4
    ssl3CertNode *c;
11443
4
    ssl3CertNode *lastCert = NULL;
11444
4
    PRUint32 remaining = 0;
11445
4
    PRUint32 size;
11446
4
    SECStatus rv;
11447
4
    PRBool isServer = ss->sec.isServer;
11448
4
    PRBool isTLS;
11449
4
    SSL3AlertDescription desc;
11450
4
    int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
11451
4
    SECItem certItem;
11452
11453
4
    ssl3_CleanupPeerCerts(ss);
11454
4
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
11455
11456
    /* It is reported that some TLS client sends a Certificate message
11457
    ** with a zero-length message body.  We'll treat that case like a
11458
    ** normal no_certificates message to maximize interoperability.
11459
    */
11460
4
    if (length) {
11461
4
        rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 3, &b, &length);
11462
4
        if (rv != SECSuccess)
11463
1
            goto loser; /* fatal alert already sent by ConsumeHandshake. */
11464
3
        if (remaining > length)
11465
0
            goto decode_loser;
11466
3
    }
11467
11468
3
    if (!remaining) {
11469
0
        if (!(isTLS && isServer)) {
11470
0
            desc = bad_certificate;
11471
0
            goto alert_loser;
11472
0
        }
11473
        /* This is TLS's version of a no_certificate alert. */
11474
        /* I'm a server. I've requested a client cert. He hasn't got one. */
11475
0
        rv = ssl3_HandleNoCertificate(ss);
11476
0
        if (rv != SECSuccess) {
11477
0
            errCode = PORT_GetError();
11478
0
            goto loser;
11479
0
        }
11480
11481
0
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11482
0
            ss->ssl3.hs.ws = wait_client_key;
11483
0
        } else {
11484
0
            TLS13_SET_HS_STATE(ss, wait_finished);
11485
0
        }
11486
0
        return SECSuccess;
11487
0
    }
11488
11489
3
    ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
11490
3
    if (ss->ssl3.peerCertArena == NULL) {
11491
0
        goto loser; /* don't send alerts on memory errors */
11492
0
    }
11493
11494
    /* First get the peer cert. */
11495
3
    if (remaining < 3)
11496
0
        goto decode_loser;
11497
11498
3
    remaining -= 3;
11499
3
    rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
11500
3
    if (rv != SECSuccess)
11501
0
        goto loser; /* fatal alert already sent by ConsumeHandshake. */
11502
3
    if (size == 0 || remaining < size)
11503
0
        goto decode_loser;
11504
11505
3
    certItem.data = b;
11506
3
    certItem.len = size;
11507
3
    b += size;
11508
3
    length -= size;
11509
3
    remaining -= size;
11510
11511
3
    ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
11512
3
                                               PR_FALSE, PR_TRUE);
11513
3
    if (ss->sec.peerCert == NULL) {
11514
        /* We should report an alert if the cert was bad, but not if the
11515
         * problem was just some local problem, like memory error.
11516
         */
11517
1
        goto ambiguous_err;
11518
1
    }
11519
11520
    /* Now get all of the CA certs. */
11521
2
    while (remaining > 0) {
11522
1
        if (remaining < 3)
11523
0
            goto decode_loser;
11524
11525
1
        remaining -= 3;
11526
1
        rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
11527
1
        if (rv != SECSuccess)
11528
0
            goto loser; /* fatal alert already sent by ConsumeHandshake. */
11529
1
        if (size == 0 || remaining < size)
11530
1
            goto decode_loser;
11531
11532
0
        certItem.data = b;
11533
0
        certItem.len = size;
11534
0
        b += size;
11535
0
        length -= size;
11536
0
        remaining -= size;
11537
11538
0
        c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
11539
0
        if (c == NULL) {
11540
0
            goto loser; /* don't send alerts on memory errors */
11541
0
        }
11542
11543
0
        c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
11544
0
                                          PR_FALSE, PR_TRUE);
11545
0
        if (c->cert == NULL) {
11546
0
            goto ambiguous_err;
11547
0
        }
11548
11549
0
        c->next = NULL;
11550
0
        if (lastCert) {
11551
0
            lastCert->next = c;
11552
0
        } else {
11553
0
            ss->ssl3.peerCertChain = c;
11554
0
        }
11555
0
        lastCert = c;
11556
0
    }
11557
11558
1
    SECKEY_UpdateCertPQG(ss->sec.peerCert);
11559
11560
1
    if (!isServer &&
11561
1
        ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
11562
1
        ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
11563
0
        ss->ssl3.hs.ws = wait_certificate_status;
11564
0
        rv = SECSuccess;
11565
1
    } else {
11566
1
        rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
11567
1
    }
11568
11569
1
    return rv;
11570
11571
1
ambiguous_err:
11572
1
    errCode = PORT_GetError();
11573
1
    switch (errCode) {
11574
0
        case PR_OUT_OF_MEMORY_ERROR:
11575
0
        case SEC_ERROR_BAD_DATABASE:
11576
0
        case SEC_ERROR_NO_MEMORY:
11577
0
            if (isTLS) {
11578
0
                desc = internal_error;
11579
0
                goto alert_loser;
11580
0
            }
11581
0
            goto loser;
11582
1
    }
11583
1
    ssl3_SendAlertForCertError(ss, errCode);
11584
1
    goto loser;
11585
11586
1
decode_loser:
11587
1
    desc = isTLS ? decode_error : bad_certificate;
11588
11589
1
alert_loser:
11590
1
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
11591
11592
3
loser:
11593
3
    (void)ssl_MapLowLevelError(errCode);
11594
3
    return SECFailure;
11595
1
}
11596
11597
SECStatus
11598
ssl_SetAuthKeyBits(sslSocket *ss, const SECKEYPublicKey *pubKey)
11599
0
{
11600
0
    SECStatus rv;
11601
0
    PRUint32 minKey = 0;
11602
0
    PRInt32 optval;
11603
0
    PRBool usePolicyLength = PR_TRUE;
11604
11605
0
    rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS, &optval);
11606
0
    if (rv == SECSuccess) {
11607
0
        usePolicyLength = (PRBool)((optval & NSS_KEY_SIZE_POLICY_SSL_FLAG) == NSS_KEY_SIZE_POLICY_SSL_FLAG);
11608
0
    }
11609
11610
0
    ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(pubKey);
11611
0
    switch (SECKEY_GetPublicKeyType(pubKey)) {
11612
0
        case rsaKey:
11613
0
        case rsaPssKey:
11614
0
        case rsaOaepKey:
11615
0
            rv = usePolicyLength ? NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &optval)
11616
0
                                 : SECFailure;
11617
0
            if (rv == SECSuccess && optval > 0) {
11618
0
                minKey = (PRUint32)optval;
11619
0
            } else {
11620
0
                minKey = SSL_RSA_MIN_MODULUS_BITS;
11621
0
            }
11622
0
            break;
11623
11624
0
        case dsaKey:
11625
0
            rv = usePolicyLength ? NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &optval)
11626
0
                                 : SECFailure;
11627
0
            if (rv == SECSuccess && optval > 0) {
11628
0
                minKey = (PRUint32)optval;
11629
0
            } else {
11630
0
                minKey = SSL_DSA_MIN_P_BITS;
11631
0
            }
11632
0
            break;
11633
11634
0
        case dhKey:
11635
0
            rv = usePolicyLength ? NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &optval)
11636
0
                                 : SECFailure;
11637
0
            if (rv == SECSuccess && optval > 0) {
11638
0
                minKey = (PRUint32)optval;
11639
0
            } else {
11640
0
                minKey = SSL_DH_MIN_P_BITS;
11641
0
            }
11642
0
            break;
11643
11644
0
        case ecKey:
11645
0
            rv = usePolicyLength ? NSS_OptionGet(NSS_ECC_MIN_KEY_SIZE, &optval)
11646
0
                                 : SECFailure;
11647
0
            if (rv == SECSuccess && optval > 0) {
11648
0
                minKey = (PRUint32)optval;
11649
0
            } else {
11650
                /* Don't check EC strength here on the understanding that we
11651
                 * only support curves we like. */
11652
0
                minKey = ss->sec.authKeyBits;
11653
0
            }
11654
0
            break;
11655
11656
0
        default:
11657
0
            FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
11658
0
            return SECFailure;
11659
0
    }
11660
11661
    /* Too small: not good enough. Send a fatal alert. */
11662
0
    if (ss->sec.authKeyBits < minKey) {
11663
0
        FATAL_ERROR(ss, SSL_ERROR_WEAK_SERVER_CERT_KEY,
11664
0
                    ss->version >= SSL_LIBRARY_VERSION_TLS_1_0
11665
0
                        ? insufficient_security
11666
0
                        : illegal_parameter);
11667
0
        return SECFailure;
11668
0
    }
11669
11670
    /* PreliminaryChannelInfo.authKeyBits, scheme, and peerDelegCred are now valid. */
11671
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_peer_auth;
11672
11673
0
    return SECSuccess;
11674
0
}
11675
11676
SECStatus
11677
ssl3_HandleServerSpki(sslSocket *ss)
11678
0
{
11679
0
    PORT_Assert(!ss->sec.isServer);
11680
0
    SECKEYPublicKey *pubKey;
11681
11682
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
11683
0
        tls13_IsVerifyingWithDelegatedCredential(ss)) {
11684
0
        sslDelegatedCredential *dc = ss->xtnData.peerDelegCred;
11685
0
        pubKey = SECKEY_ExtractPublicKey(dc->spki);
11686
0
        if (!pubKey) {
11687
0
            PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
11688
0
            return SECFailure;
11689
0
        }
11690
11691
        /* Because we have only a single authType (ssl_auth_tls13_any)
11692
         * for TLS 1.3 at this point, set the scheme so that the
11693
         * callback can interpret |authKeyBits| correctly.
11694
         */
11695
0
        ss->sec.signatureScheme = dc->expectedCertVerifyAlg;
11696
0
    } else {
11697
0
        pubKey = CERT_ExtractPublicKey(ss->sec.peerCert);
11698
0
        if (!pubKey) {
11699
0
            PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
11700
0
            return SECFailure;
11701
0
        }
11702
0
    }
11703
11704
0
    SECStatus rv = ssl_SetAuthKeyBits(ss, pubKey);
11705
0
    SECKEY_DestroyPublicKey(pubKey);
11706
0
    if (rv != SECSuccess) {
11707
0
        return rv; /* Alert sent and code set. */
11708
0
    }
11709
11710
0
    return SECSuccess;
11711
0
}
11712
11713
SECStatus
11714
ssl3_AuthCertificate(sslSocket *ss)
11715
1
{
11716
1
    SECStatus rv;
11717
1
    PRBool isServer = ss->sec.isServer;
11718
1
    int errCode;
11719
11720
1
    ss->ssl3.hs.authCertificatePending = PR_FALSE;
11721
11722
1
    PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
11723
1
                ssl_preinfo_all);
11724
11725
1
    if (!ss->sec.isServer) {
11726
        /* Set the |spki| used to verify the handshake. When verifying with a
11727
         * delegated credential (DC), this corresponds to the DC public key;
11728
         * otherwise it correspond to the public key of the peer's end-entity
11729
         * certificate. */
11730
0
        rv = ssl3_HandleServerSpki(ss);
11731
0
        if (rv != SECSuccess) {
11732
            /* Alert sent and code set (if not SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE).
11733
             * In either case, we're done here. */
11734
0
            errCode = PORT_GetError();
11735
0
            goto loser;
11736
0
        }
11737
11738
0
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11739
0
            ss->sec.authType = ss->ssl3.hs.kea_def->authKeyType;
11740
0
            ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
11741
0
        }
11742
0
    }
11743
11744
    /*
11745
     * Ask caller-supplied callback function to validate cert chain.
11746
     */
11747
1
    rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
11748
1
                                           PR_TRUE, isServer);
11749
1
    if (rv != SECSuccess) {
11750
1
        errCode = PORT_GetError();
11751
1
        if (errCode == 0) {
11752
0
            errCode = SSL_ERROR_BAD_CERTIFICATE;
11753
0
        }
11754
1
        if (rv != SECWouldBlock) {
11755
1
            if (ss->handleBadCert) {
11756
0
                rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
11757
0
            }
11758
1
        }
11759
11760
1
        if (rv == SECWouldBlock) {
11761
0
            if (ss->sec.isServer) {
11762
0
                errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
11763
0
                goto loser;
11764
0
            }
11765
11766
0
            ss->ssl3.hs.authCertificatePending = PR_TRUE;
11767
0
            rv = SECSuccess;
11768
0
        }
11769
11770
1
        if (rv != SECSuccess) {
11771
1
            ssl3_SendAlertForCertError(ss, errCode);
11772
1
            goto loser;
11773
1
        }
11774
1
    }
11775
11776
0
    if (ss->sec.ci.sid->peerCert) {
11777
0
        CERT_DestroyCertificate(ss->sec.ci.sid->peerCert);
11778
0
    }
11779
0
    ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
11780
11781
0
    if (!ss->sec.isServer) {
11782
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
11783
0
            TLS13_SET_HS_STATE(ss, wait_cert_verify);
11784
0
        } else {
11785
            /* Ephemeral suites require ServerKeyExchange. */
11786
0
            if (ss->ssl3.hs.kea_def->ephemeral) {
11787
                /* require server_key_exchange */
11788
0
                ss->ssl3.hs.ws = wait_server_key;
11789
0
            } else {
11790
                /* disallow server_key_exchange */
11791
0
                ss->ssl3.hs.ws = wait_cert_request;
11792
                /* This is static RSA key exchange so set the key exchange
11793
                 * details to compensate for that. */
11794
0
                ss->sec.keaKeyBits = ss->sec.authKeyBits;
11795
0
                ss->sec.signatureScheme = ssl_sig_none;
11796
0
                ss->sec.keaGroup = NULL;
11797
0
            }
11798
0
        }
11799
0
    } else {
11800
        /* Server */
11801
0
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11802
0
            ss->ssl3.hs.ws = wait_client_key;
11803
0
        } else {
11804
0
            TLS13_SET_HS_STATE(ss, wait_cert_verify);
11805
0
        }
11806
0
    }
11807
11808
0
    PORT_Assert(rv == SECSuccess);
11809
0
    if (rv != SECSuccess) {
11810
0
        errCode = SEC_ERROR_LIBRARY_FAILURE;
11811
0
        goto loser;
11812
0
    }
11813
11814
0
    return SECSuccess;
11815
11816
1
loser:
11817
1
    (void)ssl_MapLowLevelError(errCode);
11818
1
    return SECFailure;
11819
0
}
11820
11821
static SECStatus ssl3_FinishHandshake(sslSocket *ss);
11822
11823
static SECStatus
11824
ssl3_AlwaysFail(sslSocket *ss)
11825
0
{
11826
    /* The caller should have cleared the callback. */
11827
0
    ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
11828
0
    PORT_SetError(PR_INVALID_STATE_ERROR);
11829
0
    return SECFailure;
11830
0
}
11831
11832
/* Caller must hold 1stHandshakeLock.
11833
 */
11834
SECStatus
11835
ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
11836
0
{
11837
0
    SECStatus rv;
11838
11839
0
    PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
11840
11841
0
    if (ss->sec.isServer) {
11842
0
        PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
11843
0
        return SECFailure;
11844
0
    }
11845
11846
0
    ssl_GetRecvBufLock(ss);
11847
0
    ssl_GetSSL3HandshakeLock(ss);
11848
11849
0
    if (!ss->ssl3.hs.authCertificatePending) {
11850
0
        PORT_SetError(PR_INVALID_STATE_ERROR);
11851
0
        rv = SECFailure;
11852
0
        goto done;
11853
0
    }
11854
11855
0
    ss->ssl3.hs.authCertificatePending = PR_FALSE;
11856
11857
0
    if (error != 0) {
11858
0
        ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
11859
0
        ssl3_SendAlertForCertError(ss, error);
11860
0
        rv = SECSuccess;
11861
0
    } else if (ss->ssl3.hs.restartTarget != NULL) {
11862
0
        sslRestartTarget target = ss->ssl3.hs.restartTarget;
11863
0
        ss->ssl3.hs.restartTarget = NULL;
11864
11865
0
        if (target == ssl3_FinishHandshake) {
11866
0
            SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication lost the race"
11867
0
                        " with peer's finished message",
11868
0
                        SSL_GETPID(), ss->fd));
11869
0
        }
11870
11871
0
        rv = target(ss);
11872
0
    } else {
11873
0
        SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with"
11874
0
                    " peer's finished message",
11875
0
                    SSL_GETPID(), ss->fd));
11876
11877
0
        PORT_Assert(!ss->ssl3.hs.isResuming);
11878
0
        PORT_Assert(ss->ssl3.hs.ws != idle_handshake);
11879
11880
0
        if (ss->opt.enableFalseStart &&
11881
0
            !ss->firstHsDone &&
11882
0
            !ss->ssl3.hs.isResuming &&
11883
0
            ssl3_WaitingForServerSecondRound(ss)) {
11884
            /* ssl3_SendClientSecondRound deferred the false start check because
11885
             * certificate authentication was pending, so we do it now if we still
11886
             * haven't received all of the server's second round yet.
11887
             */
11888
0
            rv = ssl3_CheckFalseStart(ss);
11889
0
        } else {
11890
0
            rv = SECSuccess;
11891
0
        }
11892
0
    }
11893
11894
0
done:
11895
0
    ssl_ReleaseSSL3HandshakeLock(ss);
11896
0
    ssl_ReleaseRecvBufLock(ss);
11897
11898
0
    return rv;
11899
0
}
11900
11901
static SECStatus
11902
ssl3_ComputeTLSFinished(sslSocket *ss, ssl3CipherSpec *spec,
11903
                        PRBool isServer,
11904
                        const SSL3Hashes *hashes,
11905
                        TLSFinished *tlsFinished)
11906
0
{
11907
0
    SECStatus rv;
11908
0
    CK_TLS_MAC_PARAMS tls_mac_params;
11909
0
    SECItem param = { siBuffer, NULL, 0 };
11910
0
    PK11Context *prf_context;
11911
0
    unsigned int retLen;
11912
11913
0
    PORT_Assert(spec->masterSecret);
11914
0
    if (!spec->masterSecret) {
11915
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11916
0
        return SECFailure;
11917
0
    }
11918
11919
0
    if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) {
11920
0
        tls_mac_params.prfHashMechanism = CKM_TLS_PRF;
11921
0
    } else {
11922
0
        tls_mac_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
11923
0
    }
11924
0
    tls_mac_params.ulMacLength = 12;
11925
0
    tls_mac_params.ulServerOrClient = isServer ? 1 : 2;
11926
0
    param.data = (unsigned char *)&tls_mac_params;
11927
0
    param.len = sizeof(tls_mac_params);
11928
0
    prf_context = PK11_CreateContextBySymKey(CKM_TLS_MAC, CKA_SIGN,
11929
0
                                             spec->masterSecret, &param);
11930
0
    if (!prf_context)
11931
0
        return SECFailure;
11932
11933
0
    rv = PK11_DigestBegin(prf_context);
11934
0
    rv |= PK11_DigestOp(prf_context, hashes->u.raw, hashes->len);
11935
0
    rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data, &retLen,
11936
0
                           sizeof tlsFinished->verify_data);
11937
0
    PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data);
11938
11939
0
    PK11_DestroyContext(prf_context, PR_TRUE);
11940
11941
0
    return rv;
11942
0
}
11943
11944
/* The calling function must acquire and release the appropriate
11945
 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
11946
 * ss->ssl3.crSpec).
11947
 */
11948
SECStatus
11949
ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec,
11950
                            const char *label, unsigned int labelLen,
11951
                            const unsigned char *val, unsigned int valLen,
11952
                            unsigned char *out, unsigned int outLen)
11953
0
{
11954
0
    SECItem param = { siBuffer, NULL, 0 };
11955
0
    CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
11956
0
    PK11Context *prf_context;
11957
0
    unsigned int retLen;
11958
0
    SECStatus rv;
11959
11960
0
    if (!spec->masterSecret) {
11961
0
        PORT_Assert(spec->masterSecret);
11962
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11963
0
        return SECFailure;
11964
0
    }
11965
11966
0
    if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
11967
        /* Bug 1312976 non-SHA256 exporters are broken. */
11968
0
        if (ssl3_GetPrfHashMechanism(ss) != CKM_SHA256) {
11969
0
            PORT_Assert(0);
11970
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11971
0
            return SECFailure;
11972
0
        }
11973
0
        mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
11974
0
    }
11975
0
    prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
11976
0
                                             spec->masterSecret, &param);
11977
0
    if (!prf_context)
11978
0
        return SECFailure;
11979
11980
0
    rv = PK11_DigestBegin(prf_context);
11981
0
    rv |= PK11_DigestOp(prf_context, (unsigned char *)label, labelLen);
11982
0
    rv |= PK11_DigestOp(prf_context, val, valLen);
11983
0
    rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
11984
0
    PORT_Assert(rv != SECSuccess || retLen == outLen);
11985
11986
0
    PK11_DestroyContext(prf_context, PR_TRUE);
11987
0
    return rv;
11988
0
}
11989
11990
/* called from ssl3_SendClientSecondRound
11991
 *             ssl3_HandleFinished
11992
 */
11993
static SECStatus
11994
ssl3_SendNextProto(sslSocket *ss)
11995
0
{
11996
0
    SECStatus rv;
11997
0
    int padding_len;
11998
0
    static const unsigned char padding[32] = { 0 };
11999
12000
0
    if (ss->xtnData.nextProto.len == 0 ||
12001
0
        ss->xtnData.nextProtoState == SSL_NEXT_PROTO_SELECTED) {
12002
0
        return SECSuccess;
12003
0
    }
12004
12005
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
12006
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12007
12008
0
    padding_len = 32 - ((ss->xtnData.nextProto.len + 2) % 32);
12009
12010
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_next_proto, ss->xtnData.nextProto.len + 2 + padding_len);
12011
0
    if (rv != SECSuccess) {
12012
0
        return rv; /* error code set by AppendHandshakeHeader */
12013
0
    }
12014
0
    rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.nextProto.data,
12015
0
                                      ss->xtnData.nextProto.len, 1);
12016
0
    if (rv != SECSuccess) {
12017
0
        return rv; /* error code set by AppendHandshake */
12018
0
    }
12019
0
    rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
12020
0
    if (rv != SECSuccess) {
12021
0
        return rv; /* error code set by AppendHandshake */
12022
0
    }
12023
0
    return rv;
12024
0
}
12025
12026
/* called from ssl3_SendFinished and tls13_DeriveSecret.
12027
 *
12028
 * This function is simply a debugging aid and therefore does not return a
12029
 * SECStatus. */
12030
void
12031
ssl3_RecordKeyLog(sslSocket *ss, const char *label, PK11SymKey *secret)
12032
0
{
12033
0
#ifdef NSS_ALLOW_SSLKEYLOGFILE
12034
0
    SECStatus rv;
12035
0
    SECItem *keyData;
12036
    /* Longest label is "CLIENT_HANDSHAKE_TRAFFIC_SECRET", master secret is 48
12037
     * bytes which happens to be the largest in TLS 1.3 as well (SHA384).
12038
     * Maximum line length: "CLIENT_HANDSHAKE_TRAFFIC_SECRET" (31) + " " (1) +
12039
     * client_random (32*2) + " " (1) +
12040
     * traffic_secret (48*2) + "\n" (1) = 194. */
12041
0
    char buf[200];
12042
0
    unsigned int offset, len;
12043
12044
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12045
12046
0
    if (!ssl_keylog_iob)
12047
0
        return;
12048
12049
0
    rv = PK11_ExtractKeyValue(secret);
12050
0
    if (rv != SECSuccess)
12051
0
        return;
12052
12053
    /* keyData does not need to be freed. */
12054
0
    keyData = PK11_GetKeyData(secret);
12055
0
    if (!keyData || !keyData->data)
12056
0
        return;
12057
12058
0
    len = strlen(label) + 1 +          /* label + space */
12059
0
          SSL3_RANDOM_LENGTH * 2 + 1 + /* client random (hex) + space */
12060
0
          keyData->len * 2 + 1;        /* secret (hex) + newline */
12061
0
    PORT_Assert(len <= sizeof(buf));
12062
0
    if (len > sizeof(buf))
12063
0
        return;
12064
12065
    /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
12066
12067
    /* There could be multiple, concurrent writers to the
12068
     * keylog, so we have to do everything in a single call to
12069
     * fwrite. */
12070
12071
0
    strcpy(buf, label);
12072
0
    offset = strlen(label);
12073
0
    buf[offset++] += ' ';
12074
0
    hexEncode(buf + offset, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
12075
0
    offset += SSL3_RANDOM_LENGTH * 2;
12076
0
    buf[offset++] = ' ';
12077
0
    hexEncode(buf + offset, keyData->data, keyData->len);
12078
0
    offset += keyData->len * 2;
12079
0
    buf[offset++] = '\n';
12080
12081
0
    PORT_Assert(offset == len);
12082
12083
0
    PZ_Lock(ssl_keylog_lock);
12084
0
    if (fwrite(buf, len, 1, ssl_keylog_iob) == 1)
12085
0
        fflush(ssl_keylog_iob);
12086
0
    PZ_Unlock(ssl_keylog_lock);
12087
0
#endif
12088
0
}
12089
12090
/* called from ssl3_SendClientSecondRound
12091
 *             ssl3_HandleClientHello
12092
 *             ssl3_HandleFinished
12093
 */
12094
static SECStatus
12095
ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
12096
0
{
12097
0
    ssl3CipherSpec *cwSpec;
12098
0
    PRBool isTLS;
12099
0
    PRBool isServer = ss->sec.isServer;
12100
0
    SECStatus rv;
12101
0
    SSL3Sender sender = isServer ? sender_server : sender_client;
12102
0
    SSL3Hashes hashes;
12103
0
    TLSFinished tlsFinished;
12104
12105
0
    SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
12106
12107
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
12108
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12109
0
    PR_ASSERT(!ss->ssl3.hs.clientCertificatePending);
12110
12111
0
    ssl_GetSpecReadLock(ss);
12112
0
    cwSpec = ss->ssl3.cwSpec;
12113
0
    isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
12114
0
    rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
12115
0
    if (isTLS && rv == SECSuccess) {
12116
0
        rv = ssl3_ComputeTLSFinished(ss, cwSpec, isServer, &hashes, &tlsFinished);
12117
0
    }
12118
0
    ssl_ReleaseSpecReadLock(ss);
12119
0
    if (rv != SECSuccess) {
12120
0
        goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */
12121
0
    }
12122
12123
0
    if (isTLS) {
12124
0
        if (isServer)
12125
0
            ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
12126
0
        else
12127
0
            ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
12128
0
        ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
12129
0
        rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof tlsFinished);
12130
0
        if (rv != SECSuccess)
12131
0
            goto fail; /* err set by AppendHandshake. */
12132
0
        rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
12133
0
        if (rv != SECSuccess)
12134
0
            goto fail; /* err set by AppendHandshake. */
12135
0
    } else {
12136
0
        if (isServer)
12137
0
            ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
12138
0
        else
12139
0
            ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
12140
0
        PORT_Assert(hashes.len == sizeof hashes.u.s);
12141
0
        ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
12142
0
        rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof hashes.u.s);
12143
0
        if (rv != SECSuccess)
12144
0
            goto fail; /* err set by AppendHandshake. */
12145
0
        rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
12146
0
        if (rv != SECSuccess)
12147
0
            goto fail; /* err set by AppendHandshake. */
12148
0
    }
12149
0
    rv = ssl3_FlushHandshake(ss, flags);
12150
0
    if (rv != SECSuccess) {
12151
0
        goto fail; /* error code set by ssl3_FlushHandshake */
12152
0
    }
12153
12154
0
    ssl3_RecordKeyLog(ss, "CLIENT_RANDOM", ss->ssl3.cwSpec->masterSecret);
12155
12156
0
    return SECSuccess;
12157
12158
0
fail:
12159
0
    return rv;
12160
0
}
12161
12162
/* wrap the master secret, and put it into the SID.
12163
 * Caller holds the Spec read lock.
12164
 */
12165
SECStatus
12166
ssl3_CacheWrappedSecret(sslSocket *ss, sslSessionID *sid,
12167
                        PK11SymKey *secret)
12168
0
{
12169
0
    PK11SymKey *wrappingKey = NULL;
12170
0
    PK11SlotInfo *symKeySlot;
12171
0
    void *pwArg = ss->pkcs11PinArg;
12172
0
    SECStatus rv = SECFailure;
12173
0
    PRBool isServer = ss->sec.isServer;
12174
0
    CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
12175
12176
0
    symKeySlot = PK11_GetSlotFromKey(secret);
12177
0
    if (!isServer) {
12178
0
        int wrapKeyIndex;
12179
0
        int incarnation;
12180
12181
        /* these next few functions are mere accessors and don't fail. */
12182
0
        sid->u.ssl3.masterWrapIndex = wrapKeyIndex =
12183
0
            PK11_GetCurrentWrapIndex(symKeySlot);
12184
0
        PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
12185
12186
0
        sid->u.ssl3.masterWrapSeries = incarnation =
12187
0
            PK11_GetSlotSeries(symKeySlot);
12188
0
        sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot);
12189
0
        sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
12190
0
        sid->u.ssl3.masterValid = PR_TRUE;
12191
        /* Get the default wrapping key, for wrapping the master secret before
12192
         * placing it in the SID cache entry. */
12193
0
        wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
12194
0
                                      CKM_INVALID_MECHANISM, incarnation,
12195
0
                                      pwArg);
12196
0
        if (wrappingKey) {
12197
0
            mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
12198
0
        } else {
12199
0
            int keyLength;
12200
            /* if the wrappingKey doesn't exist, attempt to create it.
12201
             * Note: we intentionally ignore errors here.  If we cannot
12202
             * generate a wrapping key, it is not fatal to this SSL connection,
12203
             * but we will not be able to restart this session.
12204
             */
12205
0
            mechanism = PK11_GetBestWrapMechanism(symKeySlot);
12206
0
            keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
12207
            /* Zero length means fixed key length algorithm, or error.
12208
             * It's ambiguous.
12209
             */
12210
0
            wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
12211
0
                                      keyLength, pwArg);
12212
0
            if (wrappingKey) {
12213
                /* The thread safety characteristics of PK11_[SG]etWrapKey is
12214
                 * abominable.  This protects against races in calling
12215
                 * PK11_SetWrapKey by dropping and re-acquiring the canonical
12216
                 * value once it is set.  The mutex in PK11_[SG]etWrapKey will
12217
                 * ensure that races produce the same value in the end. */
12218
0
                PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
12219
0
                PK11_FreeSymKey(wrappingKey);
12220
0
                wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
12221
0
                                              CKM_INVALID_MECHANISM, incarnation, pwArg);
12222
0
                if (!wrappingKey) {
12223
0
                    PK11_FreeSlot(symKeySlot);
12224
0
                    return SECFailure;
12225
0
                }
12226
0
            }
12227
0
        }
12228
0
    } else {
12229
        /* server socket using session cache. */
12230
0
        mechanism = PK11_GetBestWrapMechanism(symKeySlot);
12231
0
        if (mechanism != CKM_INVALID_MECHANISM) {
12232
0
            wrappingKey =
12233
0
                ssl3_GetWrappingKey(ss, symKeySlot, mechanism, pwArg);
12234
0
            if (wrappingKey) {
12235
0
                mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
12236
0
            }
12237
0
        }
12238
0
    }
12239
12240
0
    sid->u.ssl3.masterWrapMech = mechanism;
12241
0
    PK11_FreeSlot(symKeySlot);
12242
12243
0
    if (wrappingKey) {
12244
0
        SECItem wmsItem;
12245
12246
0
        wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
12247
0
        wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret;
12248
0
        rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
12249
0
                             secret, &wmsItem);
12250
        /* rv is examined below. */
12251
0
        sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
12252
0
        PK11_FreeSymKey(wrappingKey);
12253
0
    }
12254
0
    return rv;
12255
0
}
12256
12257
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
12258
 * a complete ssl3 Finished message from the peer.
12259
 * Caller must hold Handshake and RecvBuf locks.
12260
 */
12261
static SECStatus
12262
ssl3_HandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
12263
2
{
12264
2
    SECStatus rv = SECSuccess;
12265
2
    PRBool isServer = ss->sec.isServer;
12266
2
    PRBool isTLS;
12267
2
    SSL3Hashes hashes;
12268
12269
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12270
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12271
12272
2
    SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
12273
2
                SSL_GETPID(), ss->fd));
12274
12275
2
    if (ss->ssl3.hs.ws != wait_finished) {
12276
2
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12277
2
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
12278
2
        return SECFailure;
12279
2
    }
12280
12281
0
    if (!ss->sec.isServer || !ss->opt.requestCertificate) {
12282
0
        dtls_ReceivedFirstMessageInFlight(ss);
12283
0
    }
12284
12285
0
    rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.crSpec, &hashes,
12286
0
                                     isServer ? sender_client : sender_server);
12287
0
    if (rv != SECSuccess) {
12288
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12289
0
        return SECFailure;
12290
0
    }
12291
12292
0
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
12293
0
    if (rv != SECSuccess) {
12294
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12295
0
        return rv;
12296
0
    }
12297
12298
0
    isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
12299
0
    if (isTLS) {
12300
0
        TLSFinished tlsFinished;
12301
12302
0
        if (length != sizeof(tlsFinished)) {
12303
0
#ifndef UNSAFE_FUZZER_MODE
12304
0
            (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
12305
0
            PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12306
0
            return SECFailure;
12307
0
#endif
12308
0
        }
12309
0
        rv = ssl3_ComputeTLSFinished(ss, ss->ssl3.crSpec, !isServer,
12310
0
                                     &hashes, &tlsFinished);
12311
0
        if (!isServer)
12312
0
            ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
12313
0
        else
12314
0
            ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
12315
0
        ss->ssl3.hs.finishedBytes = sizeof(tlsFinished);
12316
0
        if (rv != SECSuccess ||
12317
0
            0 != NSS_SecureMemcmp(&tlsFinished, b,
12318
0
                                  PR_MIN(length, ss->ssl3.hs.finishedBytes))) {
12319
0
#ifndef UNSAFE_FUZZER_MODE
12320
0
            (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
12321
0
            PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12322
0
            return SECFailure;
12323
0
#endif
12324
0
        }
12325
0
    } else {
12326
0
        if (length != sizeof(SSL3Finished)) {
12327
0
            (void)ssl3_IllegalParameter(ss);
12328
0
            PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
12329
0
            return SECFailure;
12330
0
        }
12331
12332
0
        if (!isServer)
12333
0
            ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
12334
0
        else
12335
0
            ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
12336
0
        PORT_Assert(hashes.len == sizeof hashes.u.s);
12337
0
        ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
12338
0
        if (0 != NSS_SecureMemcmp(&hashes.u.s, b, length)) {
12339
0
            (void)ssl3_HandshakeFailure(ss);
12340
0
            PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12341
0
            return SECFailure;
12342
0
        }
12343
0
    }
12344
12345
0
    ssl_GetXmitBufLock(ss); /*************************************/
12346
12347
0
    if ((isServer && !ss->ssl3.hs.isResuming) ||
12348
0
        (!isServer && ss->ssl3.hs.isResuming)) {
12349
0
        PRInt32 flags = 0;
12350
12351
        /* Send a NewSessionTicket message if the client sent us
12352
         * either an empty session ticket, or one that did not verify.
12353
         * (Note that if either of these conditions was met, then the
12354
         * server has sent a SessionTicket extension in the
12355
         * ServerHello message.)
12356
         */
12357
0
        if (isServer && !ss->ssl3.hs.isResuming &&
12358
0
            ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
12359
0
            ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
12360
            /* RFC 5077 Section 3.3: "In the case of a full handshake, the
12361
             * server MUST verify the client's Finished message before sending
12362
             * the ticket." Presumably, this also means that the client's
12363
             * certificate, if any, must be verified beforehand too.
12364
             */
12365
0
            rv = ssl3_SendNewSessionTicket(ss);
12366
0
            if (rv != SECSuccess) {
12367
0
                goto xmit_loser;
12368
0
            }
12369
0
        }
12370
12371
0
        rv = ssl3_SendChangeCipherSpecs(ss);
12372
0
        if (rv != SECSuccess) {
12373
0
            goto xmit_loser; /* err is set. */
12374
0
        }
12375
        /* If this thread is in SSL_SecureSend (trying to write some data)
12376
        ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
12377
        ** last two handshake messages (change cipher spec and finished)
12378
        ** will be sent in the same send/write call as the application data.
12379
        */
12380
0
        if (ss->writerThread == PR_GetCurrentThread()) {
12381
0
            flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
12382
0
        }
12383
12384
0
        if (!isServer && !ss->firstHsDone) {
12385
0
            rv = ssl3_SendNextProto(ss);
12386
0
            if (rv != SECSuccess) {
12387
0
                goto xmit_loser; /* err code was set. */
12388
0
            }
12389
0
        }
12390
12391
0
        if (IS_DTLS(ss)) {
12392
0
            flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
12393
0
        }
12394
12395
0
        rv = ssl3_SendFinished(ss, flags);
12396
0
        if (rv != SECSuccess) {
12397
0
            goto xmit_loser; /* err is set. */
12398
0
        }
12399
0
    }
12400
12401
0
xmit_loser:
12402
0
    ssl_ReleaseXmitBufLock(ss); /*************************************/
12403
0
    if (rv != SECSuccess) {
12404
0
        return rv;
12405
0
    }
12406
12407
0
    if (ss->ssl3.hs.authCertificatePending) {
12408
0
        if (ss->ssl3.hs.restartTarget) {
12409
0
            PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
12410
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12411
0
            return SECFailure;
12412
0
        }
12413
12414
0
        ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
12415
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
12416
0
        return SECFailure;
12417
0
    }
12418
12419
0
    rv = ssl3_FinishHandshake(ss);
12420
0
    return rv;
12421
0
}
12422
12423
SECStatus
12424
ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid, PK11SymKey *secret)
12425
0
{
12426
0
    PORT_Assert(secret);
12427
12428
    /* fill in the sid */
12429
0
    sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
12430
0
    sid->u.ssl3.policy = ss->ssl3.policy;
12431
0
    sid->version = ss->version;
12432
0
    sid->authType = ss->sec.authType;
12433
0
    sid->authKeyBits = ss->sec.authKeyBits;
12434
0
    sid->keaType = ss->sec.keaType;
12435
0
    sid->keaKeyBits = ss->sec.keaKeyBits;
12436
0
    if (ss->sec.keaGroup) {
12437
0
        sid->keaGroup = ss->sec.keaGroup->name;
12438
0
    } else {
12439
0
        sid->keaGroup = ssl_grp_none;
12440
0
    }
12441
0
    sid->sigScheme = ss->sec.signatureScheme;
12442
0
    sid->lastAccessTime = sid->creationTime = ssl_Time(ss);
12443
0
    sid->expirationTime = sid->creationTime + (ssl_ticket_lifetime * PR_USEC_PER_SEC);
12444
0
    sid->localCert = CERT_DupCertificate(ss->sec.localCert);
12445
0
    if (ss->sec.isServer) {
12446
0
        sid->namedCurve = ss->sec.serverCert->namedCurve;
12447
0
    }
12448
12449
0
    if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
12450
0
        ss->xtnData.nextProto.data) {
12451
0
        SECITEM_FreeItem(&sid->u.ssl3.alpnSelection, PR_FALSE);
12452
0
        if (SECITEM_CopyItem(
12453
0
                NULL, &sid->u.ssl3.alpnSelection, &ss->xtnData.nextProto) != SECSuccess) {
12454
0
            return SECFailure; /* error already set. */
12455
0
        }
12456
0
    }
12457
12458
    /* Copy the master secret (wrapped or unwrapped) into the sid */
12459
0
    return ssl3_CacheWrappedSecret(ss, ss->sec.ci.sid, secret);
12460
0
}
12461
12462
/* The return type is SECStatus instead of void because this function needs
12463
 * to have type sslRestartTarget.
12464
 */
12465
SECStatus
12466
ssl3_FinishHandshake(sslSocket *ss)
12467
0
{
12468
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12469
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12470
0
    PORT_Assert(ss->ssl3.hs.restartTarget == NULL);
12471
0
    sslSessionID *sid = ss->sec.ci.sid;
12472
0
    SECStatus sidRv = SECFailure;
12473
12474
    /* The first handshake is now completed. */
12475
0
    ss->handshake = NULL;
12476
12477
0
    if (sid->cached == never_cached && !ss->opt.noCache) {
12478
        /* If the wrap fails, don't cache the sid. The connection proceeds
12479
         * normally, so the rv is only used to determine whether we cache. */
12480
0
        sidRv = ssl3_FillInCachedSID(ss, sid, ss->ssl3.crSpec->masterSecret);
12481
0
    }
12482
12483
    /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid
12484
     * until it has verified the server's Finished message." When the server
12485
     * sends a NewSessionTicket in a resumption handshake, we must wait until
12486
     * the handshake is finished (we have verified the server's Finished
12487
     * AND the server's certificate) before we update the ticket in the sid.
12488
     *
12489
     * This must be done before we call ssl_CacheSessionID(ss)
12490
     * because CacheSID requires the session ticket to already be set, and also
12491
     * because of the lazy lock creation scheme used by CacheSID and
12492
     * ssl3_SetSIDSessionTicket. */
12493
0
    if (ss->ssl3.hs.receivedNewSessionTicket) {
12494
0
        PORT_Assert(!ss->sec.isServer);
12495
0
        if (sidRv == SECSuccess) {
12496
            /* The sid takes over the ticket data */
12497
0
            ssl3_SetSIDSessionTicket(ss->sec.ci.sid,
12498
0
                                     &ss->ssl3.hs.newSessionTicket);
12499
0
        } else {
12500
0
            PORT_Assert(ss->ssl3.hs.newSessionTicket.ticket.data);
12501
0
            SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket,
12502
0
                             PR_FALSE);
12503
0
        }
12504
0
        PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
12505
0
        ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
12506
0
    }
12507
0
    if (sidRv == SECSuccess) {
12508
0
        PORT_Assert(ss->sec.ci.sid->cached == never_cached);
12509
0
        ssl_CacheSessionID(ss);
12510
0
    }
12511
12512
0
    ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */
12513
0
    ss->ssl3.hs.ws = idle_handshake;
12514
12515
0
    return ssl_FinishHandshake(ss);
12516
0
}
12517
12518
SECStatus
12519
ssl_HashHandshakeMessageInt(sslSocket *ss, SSLHandshakeType ct,
12520
                            PRUint32 dtlsSeq,
12521
                            const PRUint8 *b, PRUint32 length,
12522
                            sslUpdateHandshakeHashes updateHashes)
12523
11.4k
{
12524
11.4k
    PRUint8 hdr[4];
12525
11.4k
    PRUint8 dtlsData[8];
12526
11.4k
    SECStatus rv;
12527
12528
11.4k
    PRINT_BUF(50, (ss, "Hash handshake message:", b, length));
12529
12530
11.4k
    hdr[0] = (PRUint8)ct;
12531
11.4k
    hdr[1] = (PRUint8)(length >> 16);
12532
11.4k
    hdr[2] = (PRUint8)(length >> 8);
12533
11.4k
    hdr[3] = (PRUint8)(length);
12534
12535
11.4k
    rv = updateHashes(ss, (unsigned char *)hdr, 4);
12536
11.4k
    if (rv != SECSuccess)
12537
0
        return rv; /* err code already set. */
12538
12539
    /* Extra data to simulate a complete DTLS handshake fragment */
12540
11.4k
    if (IS_DTLS_1_OR_12(ss)) {
12541
        /* Sequence number */
12542
11.4k
        dtlsData[0] = MSB(dtlsSeq);
12543
11.4k
        dtlsData[1] = LSB(dtlsSeq);
12544
12545
        /* Fragment offset */
12546
11.4k
        dtlsData[2] = 0;
12547
11.4k
        dtlsData[3] = 0;
12548
11.4k
        dtlsData[4] = 0;
12549
12550
        /* Fragment length */
12551
11.4k
        dtlsData[5] = (PRUint8)(length >> 16);
12552
11.4k
        dtlsData[6] = (PRUint8)(length >> 8);
12553
11.4k
        dtlsData[7] = (PRUint8)(length);
12554
12555
11.4k
        rv = updateHashes(ss, (unsigned char *)dtlsData, sizeof(dtlsData));
12556
11.4k
        if (rv != SECSuccess)
12557
0
            return rv; /* err code already set. */
12558
11.4k
    }
12559
12560
    /* The message body */
12561
11.4k
    rv = updateHashes(ss, b, length);
12562
11.4k
    if (rv != SECSuccess)
12563
0
        return rv; /* err code already set. */
12564
12565
11.4k
    return SECSuccess;
12566
11.4k
}
12567
12568
SECStatus
12569
ssl_HashHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
12570
                         const PRUint8 *b, PRUint32 length)
12571
11.4k
{
12572
11.4k
    return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12573
11.4k
                                       b, length, ssl3_UpdateHandshakeHashes);
12574
11.4k
}
12575
12576
SECStatus
12577
ssl_HashHandshakeMessageDefault(sslSocket *ss, SSLHandshakeType ct,
12578
                                const PRUint8 *b, PRUint32 length)
12579
0
{
12580
0
    return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12581
0
                                       b, length, ssl3_UpdateDefaultHandshakeHashes);
12582
0
}
12583
SECStatus
12584
ssl_HashHandshakeMessageEchInner(sslSocket *ss, SSLHandshakeType ct,
12585
                                 const PRUint8 *b, PRUint32 length)
12586
0
{
12587
0
    return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12588
0
                                       b, length, ssl3_UpdateInnerHandshakeHashes);
12589
0
}
12590
12591
SECStatus
12592
ssl_HashPostHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
12593
                             const PRUint8 *b, PRUint32 length)
12594
0
{
12595
0
    return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12596
0
                                       b, length, ssl3_UpdatePostHandshakeHashes);
12597
0
}
12598
12599
/* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
12600
 * handshake message.
12601
 * Caller must hold Handshake and RecvBuf locks.
12602
 */
12603
SECStatus
12604
ssl3_HandleHandshakeMessage(sslSocket *ss, PRUint8 *b, PRUint32 length,
12605
                            PRBool endOfRecord)
12606
12.9k
{
12607
12.9k
    SECStatus rv = SECSuccess;
12608
12.9k
    PRUint16 epoch;
12609
12610
12.9k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12611
12.9k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12612
12613
12.9k
    SSL_TRC(30, ("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
12614
12.9k
                 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
12615
12616
    /* Start new handshake hashes when we start a new handshake. */
12617
12.9k
    if (ss->ssl3.hs.msg_type == ssl_hs_client_hello) {
12618
7.50k
        ssl3_RestartHandshakeHashes(ss);
12619
7.50k
    }
12620
12.9k
    switch (ss->ssl3.hs.msg_type) {
12621
6
        case ssl_hs_hello_request:
12622
7
        case ssl_hs_hello_verify_request:
12623
            /* We don't include hello_request and hello_verify_request messages
12624
             * in the handshake hashes */
12625
7
            break;
12626
12627
        /* Defer hashing of these messages until the message handlers. */
12628
7.50k
        case ssl_hs_client_hello:
12629
7.51k
        case ssl_hs_server_hello:
12630
7.51k
        case ssl_hs_certificate_verify:
12631
7.51k
        case ssl_hs_finished:
12632
7.51k
            break;
12633
12634
5.40k
        default:
12635
5.40k
            if (!tls13_IsPostHandshake(ss)) {
12636
5.40k
                rv = ssl_HashHandshakeMessage(ss, ss->ssl3.hs.msg_type, b, length);
12637
5.40k
                if (rv != SECSuccess) {
12638
0
                    return SECFailure;
12639
0
                }
12640
5.40k
            }
12641
12.9k
    }
12642
12643
12.9k
    PORT_SetError(0); /* each message starts with no error. */
12644
12645
12.9k
    if (ss->ssl3.hs.ws == wait_certificate_status &&
12646
12.9k
        ss->ssl3.hs.msg_type != ssl_hs_certificate_status) {
12647
        /* If we negotiated the certificate_status extension then we deferred
12648
         * certificate validation until we get the CertificateStatus messsage.
12649
         * But the CertificateStatus message is optional. If the server did
12650
         * not send it then we need to validate the certificate now. If the
12651
         * server does send the CertificateStatus message then we will
12652
         * authenticate the certificate in ssl3_HandleCertificateStatus.
12653
         */
12654
0
        rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
12655
0
        if (rv != SECSuccess) {
12656
            /* This can't block. */
12657
0
            PORT_Assert(PORT_GetError() != PR_WOULD_BLOCK_ERROR);
12658
0
            return SECFailure;
12659
0
        }
12660
0
    }
12661
12662
12.9k
    epoch = ss->ssl3.crSpec->epoch;
12663
12.9k
    switch (ss->ssl3.hs.msg_type) {
12664
7.50k
        case ssl_hs_client_hello:
12665
7.50k
            if (!ss->sec.isServer) {
12666
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12667
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
12668
0
                return SECFailure;
12669
0
            }
12670
7.50k
            rv = ssl3_HandleClientHello(ss, b, length);
12671
7.50k
            break;
12672
3
        case ssl_hs_server_hello:
12673
3
            if (ss->sec.isServer) {
12674
3
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12675
3
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
12676
3
                return SECFailure;
12677
3
            }
12678
0
            rv = ssl3_HandleServerHello(ss, b, length);
12679
0
            break;
12680
5.41k
        default:
12681
5.41k
            if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
12682
5.41k
                rv = ssl3_HandlePostHelloHandshakeMessage(ss, b, length);
12683
5.41k
            } else {
12684
0
                rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length);
12685
0
            }
12686
5.41k
            break;
12687
12.9k
    }
12688
12.9k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
12689
12.9k
        (epoch != ss->ssl3.crSpec->epoch) && !endOfRecord) {
12690
        /* If we changed read cipher states, there must not be any
12691
         * data in the input queue. */
12692
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12693
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
12694
0
        return SECFailure;
12695
0
    }
12696
    /* We consider the record to have been handled if SECSuccess or else WOULD_BLOCK is set
12697
     * Whoever set WOULD_BLOCK must handle any remaining actions required to finsih processing the record.
12698
     * e.g. by setting restartTarget.
12699
     */
12700
12.9k
    if (IS_DTLS(ss) && (rv == SECSuccess || (rv == SECFailure && PR_GetError() == PR_WOULD_BLOCK_ERROR))) {
12701
        /* Increment the expected sequence number */
12702
6.05k
        ss->ssl3.hs.recvMessageSeq++;
12703
6.05k
    }
12704
12705
    /* Taint the message so that it's easier to detect UAFs. */
12706
12.9k
    PORT_Memset(b, 'N', length);
12707
12708
12.9k
    return rv;
12709
12.9k
}
12710
12711
static SECStatus
12712
ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b,
12713
                                     PRUint32 length)
12714
5.41k
{
12715
5.41k
    SECStatus rv;
12716
5.41k
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
12717
12718
5.41k
    switch (ss->ssl3.hs.msg_type) {
12719
6
        case ssl_hs_hello_request:
12720
6
            if (length != 0) {
12721
3
                (void)ssl3_DecodeError(ss);
12722
3
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
12723
3
                return SECFailure;
12724
3
            }
12725
3
            if (ss->sec.isServer) {
12726
3
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12727
3
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
12728
3
                return SECFailure;
12729
3
            }
12730
0
            rv = ssl3_HandleHelloRequest(ss);
12731
0
            break;
12732
12733
1
        case ssl_hs_hello_verify_request:
12734
1
            if (!IS_DTLS(ss) || ss->sec.isServer) {
12735
1
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12736
1
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
12737
1
                return SECFailure;
12738
1
            }
12739
0
            rv = dtls_HandleHelloVerifyRequest(ss, b, length);
12740
0
            break;
12741
2.15k
        case ssl_hs_certificate:
12742
2.15k
            rv = ssl3_HandleCertificate(ss, b, length);
12743
2.15k
            break;
12744
3
        case ssl_hs_certificate_status:
12745
3
            rv = ssl3_HandleCertificateStatus(ss, b, length);
12746
3
            break;
12747
5
        case ssl_hs_server_key_exchange:
12748
5
            if (ss->sec.isServer) {
12749
5
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12750
5
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
12751
5
                return SECFailure;
12752
5
            }
12753
0
            rv = ssl3_HandleServerKeyExchange(ss, b, length);
12754
0
            break;
12755
3
        case ssl_hs_certificate_request:
12756
3
            if (ss->sec.isServer) {
12757
3
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12758
3
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
12759
3
                return SECFailure;
12760
3
            }
12761
0
            rv = ssl3_HandleCertificateRequest(ss, b, length);
12762
0
            break;
12763
7
        case ssl_hs_server_hello_done:
12764
7
            if (length != 0) {
12765
3
                (void)ssl3_DecodeError(ss);
12766
3
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
12767
3
                return SECFailure;
12768
3
            }
12769
4
            if (ss->sec.isServer) {
12770
4
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12771
4
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
12772
4
                return SECFailure;
12773
4
            }
12774
0
            rv = ssl3_HandleServerHelloDone(ss);
12775
0
            break;
12776
3
        case ssl_hs_certificate_verify:
12777
3
            if (!ss->sec.isServer) {
12778
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12779
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
12780
0
                return SECFailure;
12781
0
            }
12782
3
            rv = ssl3_HandleCertificateVerify(ss, b, length);
12783
3
            break;
12784
3.21k
        case ssl_hs_client_key_exchange:
12785
3.21k
            if (!ss->sec.isServer) {
12786
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12787
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
12788
0
                return SECFailure;
12789
0
            }
12790
3.21k
            rv = ssl3_HandleClientKeyExchange(ss, b, length);
12791
3.21k
            break;
12792
3
        case ssl_hs_new_session_ticket:
12793
3
            if (ss->sec.isServer) {
12794
3
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12795
3
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
12796
3
                return SECFailure;
12797
3
            }
12798
0
            rv = ssl3_HandleNewSessionTicket(ss, b, length);
12799
0
            break;
12800
2
        case ssl_hs_finished:
12801
2
            rv = ssl3_HandleFinished(ss, b, length);
12802
2
            break;
12803
2
        default:
12804
2
            (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12805
2
            PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
12806
2
            rv = SECFailure;
12807
5.41k
    }
12808
12809
5.38k
    return rv;
12810
5.41k
}
12811
12812
/* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
12813
 * origBuf is the decrypted ssl record content.
12814
 * Caller must hold the handshake and RecvBuf locks.
12815
 */
12816
static SECStatus
12817
ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
12818
0
{
12819
0
    sslBuffer buf = *origBuf; /* Work from a copy. */
12820
0
    SECStatus rv;
12821
12822
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12823
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12824
12825
0
    while (buf.len > 0) {
12826
0
        if (ss->ssl3.hs.header_bytes < 4) {
12827
0
            PRUint8 t;
12828
0
            t = *(buf.buf++);
12829
0
            buf.len--;
12830
0
            if (ss->ssl3.hs.header_bytes++ == 0)
12831
0
                ss->ssl3.hs.msg_type = (SSLHandshakeType)t;
12832
0
            else
12833
0
                ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
12834
0
            if (ss->ssl3.hs.header_bytes < 4)
12835
0
                continue;
12836
12837
0
#define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
12838
0
            if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
12839
0
                (void)ssl3_DecodeError(ss);
12840
0
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
12841
0
                goto loser;
12842
0
            }
12843
0
#undef MAX_HANDSHAKE_MSG_LEN
12844
12845
            /* If msg_len is zero, be sure we fall through,
12846
            ** even if buf.len is zero.
12847
            */
12848
0
            if (ss->ssl3.hs.msg_len > 0)
12849
0
                continue;
12850
0
        }
12851
12852
        /*
12853
         * Header has been gathered and there is at least one byte of new
12854
         * data available for this message. If it can be done right out
12855
         * of the original buffer, then use it from there.
12856
         */
12857
0
        if (ss->ssl3.hs.msg_body.len == 0 && buf.len >= ss->ssl3.hs.msg_len) {
12858
            /* handle it from input buffer */
12859
0
            rv = ssl3_HandleHandshakeMessage(ss, buf.buf, ss->ssl3.hs.msg_len,
12860
0
                                             buf.len == ss->ssl3.hs.msg_len);
12861
0
            buf.buf += ss->ssl3.hs.msg_len;
12862
0
            buf.len -= ss->ssl3.hs.msg_len;
12863
0
            ss->ssl3.hs.msg_len = 0;
12864
0
            ss->ssl3.hs.header_bytes = 0;
12865
0
            if (rv != SECSuccess) {
12866
0
                goto loser;
12867
0
            }
12868
0
        } else {
12869
            /* must be copied to msg_body and dealt with from there */
12870
0
            unsigned int bytes;
12871
12872
0
            PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
12873
0
            bytes = PR_MIN(buf.len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
12874
12875
            /* Grow the buffer if needed */
12876
0
            rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
12877
0
            if (rv != SECSuccess) {
12878
                /* sslBuffer_Grow has set a memory error code. */
12879
0
                goto loser;
12880
0
            }
12881
12882
0
            PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
12883
0
                        buf.buf, bytes);
12884
0
            ss->ssl3.hs.msg_body.len += bytes;
12885
0
            buf.buf += bytes;
12886
0
            buf.len -= bytes;
12887
12888
0
            PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
12889
12890
            /* if we have a whole message, do it */
12891
0
            if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
12892
0
                rv = ssl3_HandleHandshakeMessage(
12893
0
                    ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len,
12894
0
                    buf.len == 0);
12895
0
                ss->ssl3.hs.msg_body.len = 0;
12896
0
                ss->ssl3.hs.msg_len = 0;
12897
0
                ss->ssl3.hs.header_bytes = 0;
12898
0
                if (rv != SECSuccess) {
12899
0
                    goto loser;
12900
0
                }
12901
0
            } else {
12902
0
                PORT_Assert(buf.len == 0);
12903
0
                break;
12904
0
            }
12905
0
        }
12906
0
    } /* end loop */
12907
12908
0
    origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
12909
0
    return SECSuccess;
12910
12911
0
loser : {
12912
    /* Make sure to remove any data that was consumed. */
12913
0
    unsigned int consumed = origBuf->len - buf.len;
12914
0
    PORT_Assert(consumed == buf.buf - origBuf->buf);
12915
0
    if (consumed > 0) {
12916
0
        memmove(origBuf->buf, origBuf->buf + consumed, buf.len);
12917
0
        origBuf->len = buf.len;
12918
0
    }
12919
0
}
12920
0
    return SECFailure;
12921
0
}
12922
12923
/* SECStatusToMask returns, in constant time, a mask value of all ones if
12924
 * rv == SECSuccess.  Otherwise it returns zero. */
12925
static unsigned int
12926
SECStatusToMask(SECStatus rv)
12927
14.2k
{
12928
14.2k
    return PORT_CT_EQ(rv, SECSuccess);
12929
14.2k
}
12930
12931
/* ssl_ConstantTimeGE returns 0xffffffff if a>=b and 0x00 otherwise. */
12932
static unsigned char
12933
ssl_ConstantTimeGE(unsigned int a, unsigned int b)
12934
10.4k
{
12935
10.4k
    return PORT_CT_GE(a, b);
12936
10.4k
}
12937
12938
/* ssl_ConstantTimeEQ returns 0xffffffff if a==b and 0x00 otherwise. */
12939
static unsigned char
12940
ssl_ConstantTimeEQ(unsigned char a, unsigned char b)
12941
119k
{
12942
119k
    return PORT_CT_EQ(a, b);
12943
119k
}
12944
12945
/* ssl_constantTimeSelect return a if mask is 0xFF and b if mask is 0x00 */
12946
static unsigned char
12947
ssl_constantTimeSelect(unsigned char mask, unsigned char a, unsigned char b)
12948
2.63k
{
12949
2.63k
    return (mask & a) | (~mask & b);
12950
2.63k
}
12951
12952
static SECStatus
12953
ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
12954
                          unsigned int blockSize,
12955
                          unsigned int macSize)
12956
0
{
12957
0
    unsigned int paddingLength, good;
12958
0
    const unsigned int overhead = 1 /* padding length byte */ + macSize;
12959
12960
    /* These lengths are all public so we can test them in non-constant
12961
     * time. */
12962
0
    if (overhead > plaintext->len) {
12963
0
        return SECFailure;
12964
0
    }
12965
12966
0
    paddingLength = plaintext->buf[plaintext->len - 1];
12967
    /* SSLv3 padding bytes are random and cannot be checked. */
12968
0
    good = PORT_CT_GE(plaintext->len, paddingLength + overhead);
12969
    /* SSLv3 requires that the padding is minimal. */
12970
0
    good &= PORT_CT_GE(blockSize, paddingLength + 1);
12971
0
    plaintext->len -= good & (paddingLength + 1);
12972
0
    return (good & SECSuccess) | (~good & SECFailure);
12973
0
}
12974
12975
SECStatus
12976
ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
12977
54
{
12978
54
    unsigned int paddingLength, good, toCheck, i;
12979
54
    const unsigned int overhead = 1 /* padding length byte */ + macSize;
12980
12981
    /* These lengths are all public so we can test them in non-constant
12982
     * time. */
12983
54
    if (overhead > plaintext->len) {
12984
0
        return SECFailure;
12985
0
    }
12986
12987
54
    paddingLength = plaintext->buf[plaintext->len - 1];
12988
54
    good = PORT_CT_GE(plaintext->len, paddingLength + overhead);
12989
12990
    /* The padding consists of a length byte at the end of the record and then
12991
     * that many bytes of padding, all with the same value as the length byte.
12992
     * Thus, with the length byte included, there are paddingLength+1 bytes of
12993
     * padding.
12994
     *
12995
     * We can't check just |paddingLength+1| bytes because that leaks
12996
     * decrypted information. Therefore we always have to check the maximum
12997
     * amount of padding possible. (Again, the length of the record is
12998
     * public information so we can use it.) */
12999
54
    toCheck = 256; /* maximum amount of padding + 1. */
13000
54
    if (toCheck > plaintext->len) {
13001
52
        toCheck = plaintext->len;
13002
52
    }
13003
13004
3.87k
    for (i = 0; i < toCheck; i++) {
13005
        /* If i <= paddingLength then the MSB of t is zero and mask is
13006
         * 0xff.  Otherwise, mask is 0. */
13007
3.82k
        unsigned char mask = PORT_CT_LE(i, paddingLength);
13008
3.82k
        unsigned char b = plaintext->buf[plaintext->len - 1 - i];
13009
        /* The final |paddingLength+1| bytes should all have the value
13010
         * |paddingLength|. Therefore the XOR should be zero. */
13011
3.82k
        good &= ~(mask & (paddingLength ^ b));
13012
3.82k
    }
13013
13014
    /* If any of the final |paddingLength+1| bytes had the wrong value,
13015
     * one or more of the lower eight bits of |good| will be cleared. We
13016
     * AND the bottom 8 bits together and duplicate the result to all the
13017
     * bits. */
13018
54
    good &= good >> 4;
13019
54
    good &= good >> 2;
13020
54
    good &= good >> 1;
13021
54
    good <<= sizeof(good) * 8 - 1;
13022
54
    good = PORT_CT_DUPLICATE_MSB_TO_ALL(good);
13023
13024
54
    plaintext->len -= good & (paddingLength + 1);
13025
54
    return (good & SECSuccess) | (~good & SECFailure);
13026
54
}
13027
13028
/* On entry:
13029
 *   originalLength >= macSize
13030
 *   macSize <= MAX_MAC_LENGTH
13031
 *   plaintext->len >= macSize
13032
 */
13033
static void
13034
ssl_CBCExtractMAC(sslBuffer *plaintext,
13035
                  unsigned int originalLength,
13036
                  PRUint8 *out,
13037
                  unsigned int macSize)
13038
54
{
13039
54
    unsigned char rotatedMac[MAX_MAC_LENGTH];
13040
    /* macEnd is the index of |plaintext->buf| just after the end of the
13041
     * MAC. */
13042
54
    unsigned macEnd = plaintext->len;
13043
54
    unsigned macStart = macEnd - macSize;
13044
    /* scanStart contains the number of bytes that we can ignore because
13045
     * the MAC's position can only vary by 255 bytes. */
13046
54
    unsigned scanStart = 0;
13047
54
    unsigned i, j;
13048
54
    unsigned char rotateOffset;
13049
13050
54
    if (originalLength > macSize + 255 + 1) {
13051
2
        scanStart = originalLength - (macSize + 255 + 1);
13052
2
    }
13053
13054
    /* We want to compute
13055
     * rotateOffset = (macStart - scanStart) % macSize
13056
     * But the time to compute this varies based on the amount of padding. Thus
13057
     * we explicitely handle all mac sizes with (hopefully) constant time modulo
13058
     * using Barrett reduction:
13059
     *  q := (rotateOffset * m) >> k
13060
     *  rotateOffset -= q * n
13061
     *  if (n <= rotateOffset) rotateOffset -= n
13062
     */
13063
54
    rotateOffset = macStart - scanStart;
13064
    /* rotateOffset < 255 + 1 + 48 = 304 */
13065
54
    if (macSize == 16) {
13066
0
        rotateOffset &= 15;
13067
54
    } else if (macSize == 20) {
13068
        /*
13069
         * Correctness: rotateOffset * ( 1/20 - 25/2^9 ) < 1
13070
         *              with rotateOffset <= 853
13071
         */
13072
1
        unsigned q = (rotateOffset * 25) >> 9;
13073
1
        rotateOffset -= q * 20;
13074
1
        rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 20),
13075
1
                                               20, 0);
13076
53
    } else if (macSize == 32) {
13077
2
        rotateOffset &= 31;
13078
51
    } else if (macSize == 48) {
13079
        /*
13080
         * Correctness: rotateOffset * ( 1/48 - 10/2^9 ) < 1
13081
         *              with rotateOffset < 768
13082
         */
13083
51
        unsigned q = (rotateOffset * 10) >> 9;
13084
51
        rotateOffset -= q * 48;
13085
51
        rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 48),
13086
51
                                               48, 0);
13087
51
    } else {
13088
        /*
13089
         * SHA384 (macSize == 48) is the largest we support. We should never
13090
         * get here.
13091
         */
13092
0
        PORT_Assert(0);
13093
0
        rotateOffset = rotateOffset % macSize;
13094
0
    }
13095
13096
54
    memset(rotatedMac, 0, macSize);
13097
179
    for (i = scanStart; i < originalLength;) {
13098
4.01k
        for (j = 0; j < macSize && i < originalLength; i++, j++) {
13099
3.89k
            unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
13100
3.89k
            unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
13101
3.89k
            unsigned char b = 0;
13102
3.89k
            b = plaintext->buf[i];
13103
3.89k
            rotatedMac[j] |= b & macStarted & ~macEnded;
13104
3.89k
        }
13105
125
    }
13106
13107
    /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
13108
     * we could line-align |rotatedMac| and rotate in place. */
13109
54
    memset(out, 0, macSize);
13110
54
    rotateOffset = macSize - rotateOffset;
13111
54
    rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
13112
54
                                          0, rotateOffset);
13113
2.58k
    for (i = 0; i < macSize; i++) {
13114
122k
        for (j = 0; j < macSize; j++) {
13115
119k
            out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ(j, rotateOffset);
13116
119k
        }
13117
2.53k
        rotateOffset++;
13118
2.53k
        rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
13119
2.53k
                                              0, rotateOffset);
13120
2.53k
    }
13121
54
}
13122
13123
/* MAX_EXPANSION is the amount by which a record might plausibly be expanded
13124
 * when protected.  It's the worst case estimate, so the sum of block cipher
13125
 * padding (up to 256 octets), HMAC (48 octets for SHA-384), and IV (16
13126
 * octets for AES). */
13127
14.4k
#define MAX_EXPANSION (256 + 48 + 16)
13128
13129
/* Unprotect an SSL3 record and leave the result in plaintext.
13130
 *
13131
 * If SECFailure is returned, we:
13132
 * 1. Set |*alert| to the alert to be sent.
13133
 * 2. Call PORT_SetError() with an appropriate code.
13134
 *
13135
 * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
13136
 * Therefore, we MUST not call SSL3_SendAlert().
13137
 *
13138
 */
13139
static SECStatus
13140
ssl3_UnprotectRecord(sslSocket *ss,
13141
                     ssl3CipherSpec *spec,
13142
                     SSL3Ciphertext *cText, sslBuffer *plaintext,
13143
                     SSL3AlertDescription *alert)
13144
14.4k
{
13145
14.4k
    const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
13146
14.4k
    PRBool isTLS;
13147
14.4k
    unsigned int good;
13148
14.4k
    unsigned int ivLen = 0;
13149
14.4k
    SSLContentType rType;
13150
14.4k
    SSL3ProtocolVersion rVersion;
13151
14.4k
    unsigned int minLength;
13152
14.4k
    unsigned int originalLen = 0;
13153
14.4k
    PRUint8 headerBuf[13];
13154
14.4k
    sslBuffer header = SSL_BUFFER(headerBuf);
13155
14.4k
    PRUint8 hash[MAX_MAC_LENGTH];
13156
14.4k
    PRUint8 givenHashBuf[MAX_MAC_LENGTH];
13157
14.4k
    PRUint8 *givenHash;
13158
14.4k
    unsigned int hashBytes = MAX_MAC_LENGTH + 1;
13159
14.4k
    SECStatus rv;
13160
13161
14.4k
    PORT_Assert(spec->direction == ssl_secret_read);
13162
13163
14.4k
    good = ~0U;
13164
14.4k
    minLength = spec->macDef->mac_size;
13165
14.4k
    if (cipher_def->type == type_block) {
13166
        /* CBC records have a padding length byte at the end. */
13167
136
        minLength++;
13168
136
        if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
13169
            /* With >= TLS 1.1, CBC records have an explicit IV. */
13170
136
            minLength += cipher_def->iv_size;
13171
136
        }
13172
14.3k
    } else if (cipher_def->type == type_aead) {
13173
239
        minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
13174
239
    }
13175
13176
    /* We can perform this test in variable time because the record's total
13177
     * length and the ciphersuite are both public knowledge. */
13178
14.4k
    if (cText->buf->len < minLength) {
13179
77
        goto decrypt_loser;
13180
77
    }
13181
13182
14.4k
    if (cipher_def->type == type_block &&
13183
14.4k
        spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
13184
        /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
13185
         * "The receiver decrypts the entire GenericBlockCipher structure and
13186
         * then discards the first cipher block corresponding to the IV
13187
         * component." Instead, we decrypt the first cipher block and then
13188
         * discard it before decrypting the rest.
13189
         */
13190
59
        PRUint8 iv[MAX_IV_LENGTH];
13191
59
        unsigned int decoded;
13192
13193
59
        ivLen = cipher_def->iv_size;
13194
59
        if (ivLen < 8 || ivLen > sizeof(iv)) {
13195
0
            *alert = internal_error;
13196
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
13197
0
            return SECFailure;
13198
0
        }
13199
13200
59
        PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
13201
13202
        /* The decryption result is garbage, but since we just throw away
13203
         * the block it doesn't matter.  The decryption of the next block
13204
         * depends only on the ciphertext of the IV block.
13205
         */
13206
59
        rv = spec->cipher(spec->cipherContext, iv, &decoded,
13207
59
                          sizeof(iv), cText->buf->buf, ivLen);
13208
13209
59
        good &= SECStatusToMask(rv);
13210
59
    }
13211
13212
14.4k
    PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
13213
14.4k
                   cText->buf->len - ivLen));
13214
13215
    /* Check if the ciphertext can be valid if we assume maximum plaintext and
13216
     * add the maximum possible ciphersuite expansion.
13217
     * This way we detect overlong plaintexts/padding before decryption.
13218
     * This check enforces size limitations more strict than the RFC.
13219
     * [RFC5246, Section 6.2.3] */
13220
14.4k
    if (cText->buf->len > (spec->recordSizeLimit + MAX_EXPANSION)) {
13221
6
        *alert = record_overflow;
13222
6
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13223
6
        return SECFailure;
13224
6
    }
13225
13226
14.4k
    isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
13227
14.4k
    rType = (SSLContentType)cText->hdr[0];
13228
14.4k
    rVersion = ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
13229
14.4k
               (SSL3ProtocolVersion)cText->hdr[2];
13230
14.4k
    if (cipher_def->type == type_aead) {
13231
        /* XXX For many AEAD ciphers, the plaintext is shorter than the
13232
         * ciphertext by a fixed byte count, but it is not true in general.
13233
         * Each AEAD cipher should provide a function that returns the
13234
         * plaintext length for a given ciphertext. */
13235
239
        const unsigned int explicitNonceLen = cipher_def->explicit_nonce_size;
13236
239
        const unsigned int tagLen = cipher_def->tag_size;
13237
239
        unsigned int nonceLen = explicitNonceLen;
13238
239
        unsigned int decryptedLen = cText->buf->len - nonceLen - tagLen;
13239
        /* even though read doesn't return and IV, we still need a space to put
13240
         * the combined iv/nonce n the gcm 1.2 case*/
13241
239
        unsigned char ivOut[MAX_IV_LENGTH];
13242
239
        unsigned char *iv = NULL;
13243
239
        unsigned char *nonce = NULL;
13244
13245
239
        ivLen = cipher_def->iv_size;
13246
13247
239
        rv = ssl3_BuildRecordPseudoHeader(
13248
239
            spec->epoch, cText->seqNum,
13249
239
            rType, isTLS, rVersion, IS_DTLS(ss), decryptedLen, &header, spec->version);
13250
239
        PORT_Assert(rv == SECSuccess);
13251
13252
        /* build the iv */
13253
239
        if (explicitNonceLen == 0) {
13254
0
            nonceLen = sizeof(cText->seqNum);
13255
0
            iv = spec->keyMaterial.iv;
13256
0
            nonce = SSL_BUFFER_BASE(&header);
13257
239
        } else {
13258
239
            PORT_Memcpy(ivOut, spec->keyMaterial.iv, ivLen);
13259
239
            PORT_Memset(ivOut + ivLen, 0, explicitNonceLen);
13260
239
            iv = ivOut;
13261
239
            nonce = cText->buf->buf;
13262
239
            nonceLen = explicitNonceLen;
13263
239
        }
13264
239
        rv = tls13_AEAD(spec->cipherContext, PR_TRUE,
13265
239
                        CKG_NO_GENERATE, 0,       /* iv generator params
13266
                                                   * (not used in decrypt)*/
13267
239
                        iv,                       /* iv in */
13268
239
                        NULL,                     /* iv out */
13269
239
                        ivLen + explicitNonceLen, /* full iv length */
13270
239
                        nonce, nonceLen,          /* nonce in */
13271
239
                        SSL_BUFFER_BASE(&header), /* aad */
13272
239
                        SSL_BUFFER_LEN(&header),  /* aadlen */
13273
239
                        plaintext->buf,           /* output  */
13274
239
                        &plaintext->len,          /* out len */
13275
239
                        plaintext->space,         /* max out */
13276
239
                        tagLen,
13277
239
                        cText->buf->buf + explicitNonceLen,  /* input */
13278
239
                        cText->buf->len - explicitNonceLen); /* input len */
13279
239
        if (rv != SECSuccess) {
13280
239
            good = 0;
13281
239
        }
13282
14.1k
    } else {
13283
14.1k
        if (cipher_def->type == type_block &&
13284
14.1k
            ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
13285
5
            goto decrypt_loser;
13286
5
        }
13287
13288
        /* decrypt from cText buf to plaintext. */
13289
14.1k
        rv = spec->cipher(
13290
14.1k
            spec->cipherContext, plaintext->buf, &plaintext->len,
13291
14.1k
            plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
13292
14.1k
        if (rv != SECSuccess) {
13293
0
            goto decrypt_loser;
13294
0
        }
13295
13296
14.1k
        PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
13297
13298
14.1k
        originalLen = plaintext->len;
13299
13300
        /* If it's a block cipher, check and strip the padding. */
13301
14.1k
        if (cipher_def->type == type_block) {
13302
54
            const unsigned int blockSize = cipher_def->block_size;
13303
54
            const unsigned int macSize = spec->macDef->mac_size;
13304
13305
54
            if (!isTLS) {
13306
0
                good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
13307
0
                    plaintext, blockSize, macSize));
13308
54
            } else {
13309
54
                good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
13310
54
                    plaintext, macSize));
13311
54
            }
13312
54
        }
13313
13314
        /* compute the MAC */
13315
14.1k
        rv = ssl3_BuildRecordPseudoHeader(
13316
14.1k
            spec->epoch, cText->seqNum,
13317
14.1k
            rType, isTLS, rVersion, IS_DTLS(ss),
13318
14.1k
            plaintext->len - spec->macDef->mac_size, &header, spec->version);
13319
14.1k
        PORT_Assert(rv == SECSuccess);
13320
14.1k
        if (cipher_def->type == type_block) {
13321
54
            rv = ssl3_ComputeRecordMACConstantTime(
13322
54
                spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
13323
54
                plaintext->buf, plaintext->len, originalLen,
13324
54
                hash, &hashBytes);
13325
13326
54
            ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
13327
54
                              spec->macDef->mac_size);
13328
54
            givenHash = givenHashBuf;
13329
13330
            /* plaintext->len will always have enough space to remove the MAC
13331
             * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
13332
             * plaintext->len if the result has enough space for the MAC and we
13333
             * tested the unadjusted size against minLength, above. */
13334
54
            plaintext->len -= spec->macDef->mac_size;
13335
14.1k
        } else {
13336
            /* This is safe because we checked the minLength above. */
13337
14.1k
            plaintext->len -= spec->macDef->mac_size;
13338
13339
14.1k
            rv = ssl3_ComputeRecordMAC(
13340
14.1k
                spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
13341
14.1k
                plaintext->buf, plaintext->len, hash, &hashBytes);
13342
13343
            /* We can read the MAC directly from the record because its location
13344
             * is public when a stream cipher is used. */
13345
14.1k
            givenHash = plaintext->buf + plaintext->len;
13346
14.1k
        }
13347
13348
14.1k
        good &= SECStatusToMask(rv);
13349
13350
14.1k
        if (hashBytes != (unsigned)spec->macDef->mac_size ||
13351
14.1k
            NSS_SecureMemcmp(givenHash, hash, spec->macDef->mac_size) != 0) {
13352
            /* We're allowed to leak whether or not the MAC check was correct */
13353
54
            good = 0;
13354
54
        }
13355
14.1k
    }
13356
13357
14.3k
    if (good == 0) {
13358
375
    decrypt_loser:
13359
        /* always log mac error, in case attacker can read server logs. */
13360
375
        PORT_SetError(SSL_ERROR_BAD_MAC_READ);
13361
375
        *alert = bad_record_mac;
13362
375
        return SECFailure;
13363
293
    }
13364
14.1k
    return SECSuccess;
13365
14.3k
}
13366
13367
SECStatus
13368
ssl3_HandleNonApplicationData(sslSocket *ss, SSLContentType rType,
13369
                              DTLSEpoch epoch, sslSequenceNumber seqNum,
13370
                              sslBuffer *databuf)
13371
16.3k
{
13372
16.3k
    SECStatus rv;
13373
13374
    /* check for Token Presence */
13375
16.3k
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13376
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13377
0
        return SECFailure;
13378
0
    }
13379
13380
16.3k
    ssl_GetSSL3HandshakeLock(ss);
13381
13382
    /* All the functions called in this switch MUST set error code if
13383
    ** they return SECFailure.
13384
    */
13385
16.3k
    switch (rType) {
13386
94
        case ssl_ct_change_cipher_spec:
13387
94
            rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
13388
94
            break;
13389
636
        case ssl_ct_alert:
13390
636
            rv = ssl3_HandleAlert(ss, databuf);
13391
636
            break;
13392
15.5k
        case ssl_ct_handshake:
13393
15.5k
            if (!IS_DTLS(ss)) {
13394
0
                rv = ssl3_HandleHandshake(ss, databuf);
13395
15.5k
            } else {
13396
15.5k
                rv = dtls_HandleHandshake(ss, epoch, seqNum, databuf);
13397
15.5k
            }
13398
15.5k
            break;
13399
6
        case ssl_ct_ack:
13400
6
            if (IS_DTLS(ss) && tls13_MaybeTls13(ss)) {
13401
0
                rv = dtls13_HandleAck(ss, databuf);
13402
0
                break;
13403
0
            }
13404
        /* Fall through. */
13405
84
        default:
13406
            /* If a TLS implementation receives an unexpected record type,
13407
             * it MUST terminate the connection with an "unexpected_message"
13408
             * alert [RFC8446, Section 5].
13409
             *
13410
             * For TLS 1.3 the outer content type is checked before in
13411
             * tls13con.c/tls13_UnprotectRecord(),
13412
             * For DTLS 1.3 the outer content type is checked before in
13413
             * ssl3gthr.c/dtls_GatherData.
13414
             * The inner content types will be checked here.
13415
             *
13416
             * In DTLS generally invalid records SHOULD be silently discarded,
13417
             * no alert is sent [RFC6347, Section 4.1.2.7].
13418
             */
13419
84
            if (!IS_DTLS(ss)) {
13420
0
                SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13421
0
            }
13422
84
            PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
13423
84
            SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
13424
84
                     SSL_GETPID(), ss->fd, rType));
13425
84
            rv = SECFailure;
13426
84
            break;
13427
16.3k
    }
13428
13429
16.3k
    ssl_ReleaseSSL3HandshakeLock(ss);
13430
16.3k
    return rv;
13431
16.3k
}
13432
13433
/* Find the cipher spec to use for a given record. For TLS, this
13434
 * is the current cipherspec. For DTLS, we look up by epoch.
13435
 * In DTLS < 1.3 this just means the current epoch or nothing,
13436
 * but in DTLS >= 1.3, we keep multiple reading cipherspecs.
13437
 * Returns NULL if no appropriate cipher spec is found.
13438
 */
13439
static ssl3CipherSpec *
13440
ssl3_GetCipherSpec(sslSocket *ss, SSL3Ciphertext *cText)
13441
22.5k
{
13442
22.5k
    ssl3CipherSpec *crSpec = ss->ssl3.crSpec;
13443
22.5k
    ssl3CipherSpec *newSpec = NULL;
13444
22.5k
    DTLSEpoch epoch;
13445
13446
22.5k
    if (!IS_DTLS(ss)) {
13447
0
        return crSpec;
13448
0
    }
13449
22.5k
    epoch = dtls_ReadEpoch(crSpec->version, crSpec->epoch, cText->hdr);
13450
22.5k
    if (crSpec->epoch == epoch) {
13451
20.8k
        return crSpec;
13452
20.8k
    }
13453
1.67k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
13454
        /* Try to find the cipher spec. */
13455
0
        newSpec = ssl_FindCipherSpecByEpoch(ss, ssl_secret_read,
13456
0
                                            epoch);
13457
0
        if (newSpec != NULL) {
13458
0
            return newSpec;
13459
0
        }
13460
0
    }
13461
1.67k
    SSL_TRC(10, ("%d: DTLS[%d]: %s couldn't find cipherspec from epoch %d",
13462
1.67k
                 SSL_GETPID(), ss->fd, SSL_ROLE(ss), epoch));
13463
1.67k
    return NULL;
13464
1.67k
}
13465
13466
/* if cText is non-null, then decipher and check the MAC of the
13467
 * SSL record from cText->buf (typically gs->inbuf)
13468
 * into databuf (typically gs->buf), and any previous contents of databuf
13469
 * is lost.  Then handle databuf according to its SSL record type,
13470
 * unless it's an application record.
13471
 *
13472
 * If cText is NULL, then the ciphertext has previously been deciphered and
13473
 * checked, and is already sitting in databuf.  It is processed as an SSL
13474
 * Handshake message.
13475
 *
13476
 * DOES NOT process the decrypted application data.
13477
 * On return, databuf contains the decrypted record.
13478
 *
13479
 * Called from ssl3_GatherCompleteHandshake
13480
 *             ssl3_RestartHandshakeAfterCertReq
13481
 *
13482
 * Caller must hold the RecvBufLock.
13483
 *
13484
 * This function aquires and releases the SSL3Handshake Lock, holding the
13485
 * lock around any calls to functions that handle records other than
13486
 * Application Data records.
13487
 */
13488
SECStatus
13489
ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText)
13490
22.5k
{
13491
22.5k
    SECStatus rv = SECFailure;
13492
22.5k
    PRBool isTLS, isTLS13;
13493
22.5k
    DTLSEpoch epoch;
13494
22.5k
    ssl3CipherSpec *spec = NULL;
13495
22.5k
    PRUint16 recordSizeLimit, cTextSizeLimit;
13496
22.5k
    PRBool outOfOrderSpec = PR_FALSE;
13497
22.5k
    SSLContentType rType;
13498
22.5k
    sslBuffer *plaintext = &ss->gs.buf;
13499
22.5k
    SSL3AlertDescription alert = internal_error;
13500
22.5k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
13501
13502
    /* check for Token Presence */
13503
22.5k
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13504
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13505
0
        return SECFailure;
13506
0
    }
13507
13508
    /* Clear out the buffer in case this exits early.  Any data then won't be
13509
     * processed twice. */
13510
22.5k
    plaintext->len = 0;
13511
13512
    /* We're waiting for another ClientHello, which will appear unencrypted.
13513
     * Use the content type to tell whether this should be discarded. */
13514
22.5k
    if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr &&
13515
22.5k
        cText->hdr[0] == ssl_ct_application_data) {
13516
0
        PORT_Assert(ss->ssl3.hs.ws == wait_client_hello);
13517
0
        return SECSuccess;
13518
0
    }
13519
13520
22.5k
    ssl_GetSpecReadLock(ss); /******************************************/
13521
22.5k
    spec = ssl3_GetCipherSpec(ss, cText);
13522
22.5k
    if (!spec) {
13523
1.67k
        PORT_Assert(IS_DTLS(ss));
13524
1.67k
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13525
1.67k
        return SECSuccess;
13526
1.67k
    }
13527
20.8k
    if (spec != ss->ssl3.crSpec) {
13528
0
        PORT_Assert(IS_DTLS(ss));
13529
0
        SSL_TRC(3, ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d",
13530
0
                    SSL_GETPID(), ss->fd, spec->epoch));
13531
0
        outOfOrderSpec = PR_TRUE;
13532
0
    }
13533
20.8k
    isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
13534
20.8k
    if (IS_DTLS(ss)) {
13535
20.8k
        if (dtls13_MaskSequenceNumber(ss, spec, cText->hdr,
13536
20.8k
                                      SSL_BUFFER_BASE(cText->buf), SSL_BUFFER_LEN(cText->buf)) != SECSuccess) {
13537
0
            ssl_ReleaseSpecReadLock(ss); /*****************************/
13538
            /* code already set. */
13539
0
            return SECFailure;
13540
0
        }
13541
20.8k
        if (!dtls_IsRelevant(ss, spec, cText, &cText->seqNum)) {
13542
1.27k
            ssl_ReleaseSpecReadLock(ss); /*****************************/
13543
1.27k
            return SECSuccess;
13544
1.27k
        }
13545
20.8k
    } else {
13546
0
        cText->seqNum = spec->nextSeqNum;
13547
0
    }
13548
19.6k
    if (cText->seqNum >= spec->cipherDef->max_records) {
13549
1
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13550
1
        SSL_TRC(3, ("%d: SSL[%d]: read sequence number at limit 0x%0llx",
13551
1
                    SSL_GETPID(), ss->fd, cText->seqNum));
13552
1
        PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
13553
1
        return SECFailure;
13554
1
    }
13555
13556
19.6k
    isTLS13 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
13557
19.6k
    recordSizeLimit = spec->recordSizeLimit;
13558
19.6k
    cTextSizeLimit = recordSizeLimit;
13559
19.6k
    cTextSizeLimit += (isTLS13) ? TLS_1_3_MAX_EXPANSION : TLS_1_2_MAX_EXPANSION;
13560
13561
    /* Check if the specified recordSizeLimit and the RFC8446 specified max
13562
     * expansion are respected. recordSizeLimit is probably at the default for
13563
     * the first (hello) handshake message and then set to a smaller size by
13564
     * the Record Size Limit Extension.
13565
     * Stricter expansion size checks dependent on implemented cipher suites
13566
     * are performed in ssl3con.c/ssl3_UnprotectRecord() OR
13567
     * tls13con.c/tls13_UnprotextRecord().
13568
     * After Decryption the plaintext size is checked (l. 13424). This also
13569
     * applies to unencrypted records. */
13570
19.6k
    if (cText->buf->len > cTextSizeLimit) {
13571
0
        ssl_ReleaseSpecReadLock(ss); /*****************************/
13572
        /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
13573
0
        if (IS_DTLS(ss)) {
13574
0
            return SECSuccess;
13575
0
        }
13576
0
        SSL3_SendAlert(ss, alert_fatal, record_overflow);
13577
0
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13578
0
        return SECFailure;
13579
0
    }
13580
13581
19.6k
#ifdef DEBUG
13582
    /* In debug builds the gather buffers are freed after the handling of each
13583
     * record for advanced ASAN coverage. Allocate the buffer again to the
13584
     * maximum possibly needed size as on gather initialization in
13585
     * ssl3gthr.c/ssl3_InitGather(). */
13586
19.6k
    PR_ASSERT(sslBuffer_Grow(plaintext, TLS_1_2_MAX_CTEXT_LENGTH) == SECSuccess);
13587
19.6k
#endif
13588
    /* This replaces a dynamic plaintext buffer size check, since the buffer is
13589
     * allocated to the maximum size in ssl3gthr.c/ssl3_InitGather(). The buffer
13590
     * was always grown to the maximum size at first record gathering before. */
13591
19.6k
    PR_ASSERT(plaintext->space >= cTextSizeLimit);
13592
13593
    /* Most record types aside from protected TLS 1.3 records carry the content
13594
     * type in the first octet. TLS 1.3 will override this value later. */
13595
19.6k
    rType = cText->hdr[0];
13596
    /* Encrypted application data records could arrive before the handshake
13597
     * completes in DTLS 1.3. These can look like valid TLS 1.2 application_data
13598
     * records in epoch 0, which is never valid. Pretend they didn't decrypt. */
13599
19.6k
    if (spec->epoch == 0 && ((IS_DTLS(ss) &&
13600
19.2k
                              dtls_IsDtls13Ciphertext(0, rType)) ||
13601
19.2k
                             rType == ssl_ct_application_data)) {
13602
2.89k
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
13603
2.89k
        alert = unexpected_message;
13604
2.89k
        rv = SECFailure;
13605
16.7k
    } else {
13606
#ifdef UNSAFE_FUZZER_MODE
13607
        rv = Null_Cipher(NULL, plaintext->buf, &plaintext->len,
13608
                         plaintext->space, cText->buf->buf, cText->buf->len);
13609
#else
13610
        /* IMPORTANT:
13611
         * Unprotect functions MUST NOT send alerts
13612
         * because we still hold the spec read lock. Instead, if they
13613
         * return SECFailure, they set *alert to the alert to be sent.
13614
         * Additionaly, this is used to silently drop DTLS encryption/record
13615
         * errors/alerts using the error handling below as suggested in the
13616
         * DTLS specification [RFC6347, Section 4.1.2.7]. */
13617
16.7k
        if (spec->cipherDef->cipher == cipher_null && cText->buf->len == 0) {
13618
            /* Handle a zero-length unprotected record
13619
             * In this case, we treat it as a no-op and let later functions decide
13620
             * whether to ignore or alert accordingly. */
13621
2.23k
            PR_ASSERT(plaintext->len == 0);
13622
2.23k
            rv = SECSuccess;
13623
14.4k
        } else if (spec->version < SSL_LIBRARY_VERSION_TLS_1_3 || spec->epoch == 0) {
13624
14.4k
            rv = ssl3_UnprotectRecord(ss, spec, cText, plaintext, &alert);
13625
14.4k
        } else {
13626
0
            rv = tls13_UnprotectRecord(ss, spec, cText, plaintext, &rType,
13627
0
                                       &alert);
13628
0
        }
13629
16.7k
#endif
13630
16.7k
    }
13631
13632
    /* Error/Alert handling for ssl3/tls13_UnprotectRecord */
13633
19.6k
    if (rv != SECSuccess) {
13634
3.27k
        ssl_ReleaseSpecReadLock(ss); /***************************/
13635
13636
3.27k
        SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
13637
13638
        /* Ensure that we don't process this data again. */
13639
3.27k
        plaintext->len = 0;
13640
13641
        /* Ignore a CCS if compatibility mode is negotiated.  Note that this
13642
         * will fail if the server fails to negotiate compatibility mode in a
13643
         * 0-RTT session that is resumed from a session that did negotiate it.
13644
         * We don't care about that corner case right now. */
13645
3.27k
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
13646
3.27k
            cText->hdr[0] == ssl_ct_change_cipher_spec &&
13647
3.27k
            ss->ssl3.hs.ws != idle_handshake &&
13648
3.27k
            cText->buf->len == 1 &&
13649
3.27k
            cText->buf->buf[0] == change_cipher_spec_choice) {
13650
0
            if (!ss->ssl3.hs.rejectCcs) {
13651
                /* Allow only the first CCS. */
13652
0
                ss->ssl3.hs.rejectCcs = PR_TRUE;
13653
0
                return SECSuccess;
13654
0
            } else {
13655
0
                alert = unexpected_message;
13656
0
                PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
13657
0
            }
13658
0
        }
13659
13660
        /* All errors/alerts that might occur during unprotection are related
13661
         * to invalid records (e.g. invalid formatting, length, MAC, ...).
13662
         * Following the DTLS specification such errors/alerts SHOULD be
13663
         * dropped silently [RFC9147, Section 4.5.2].
13664
         * This is done below. */
13665
13666
3.27k
        if ((IS_DTLS(ss) && !dtls13_AeadLimitReached(spec)) ||
13667
3.27k
            (!IS_DTLS(ss) && ss->sec.isServer &&
13668
3.27k
             ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_trial)) {
13669
            /* Silently drop the packet unless we set ss->ssl3.fatalAlertSent.
13670
             * (Manually or by using functions like
13671
             * SSL3_SendAlert(.., alert_fatal,..))
13672
             * This is not currently used in the unprotection functions since
13673
             * all TLS and DTLS errors are propagated to this handler. */
13674
3.27k
            if (ss->ssl3.fatalAlertSent) {
13675
0
                return SECFailure;
13676
0
            }
13677
3.27k
            return SECSuccess;
13678
3.27k
        }
13679
13680
0
        int errCode = PORT_GetError();
13681
0
        SSL3_SendAlert(ss, alert_fatal, alert);
13682
        /* Reset the error code in case SSL3_SendAlert called
13683
         * PORT_SetError(). */
13684
0
        PORT_SetError(errCode);
13685
0
        return SECFailure;
13686
3.27k
    }
13687
13688
    /* SECSuccess */
13689
16.3k
    if (IS_DTLS(ss)) {
13690
16.3k
        dtls_RecordSetRecvd(&spec->recvdRecords, cText->seqNum);
13691
16.3k
        spec->nextSeqNum = PR_MAX(spec->nextSeqNum, cText->seqNum + 1);
13692
16.3k
    } else {
13693
0
        ++spec->nextSeqNum;
13694
0
    }
13695
16.3k
    epoch = spec->epoch;
13696
13697
16.3k
    ssl_ReleaseSpecReadLock(ss); /*****************************************/
13698
13699
    /*
13700
     * The decrypted data is now in plaintext.
13701
     */
13702
13703
    /* IMPORTANT: We are in DTLS 1.3 mode and we have processed something
13704
     * from the wrong epoch. Divert to a divert processing function to make
13705
     * sure we don't accidentally use the data unsafely. */
13706
13707
    /* We temporary allowed reading the records from the previous epoch n-1
13708
    until the moment we get a message from the new epoch n. */
13709
13710
16.3k
    if (outOfOrderSpec) {
13711
0
        PORT_Assert(IS_DTLS(ss) && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
13712
0
        ssl_GetSSL3HandshakeLock(ss);
13713
0
        if (ss->ssl3.hs.allowPreviousEpoch && spec->epoch == ss->ssl3.crSpec->epoch - 1) {
13714
0
            SSL_TRC(30, ("%d: DTLS13[%d]: Out of order message %d is accepted",
13715
0
                         SSL_GETPID(), ss->fd, spec->epoch));
13716
0
            ssl_ReleaseSSL3HandshakeLock(ss);
13717
0
        } else {
13718
0
            ssl_ReleaseSSL3HandshakeLock(ss);
13719
0
            return dtls13_HandleOutOfEpochRecord(ss, spec, rType, plaintext);
13720
0
        }
13721
16.3k
    } else {
13722
16.3k
        ssl_GetSSL3HandshakeLock(ss);
13723
        /* Forbid (application) messages from the previous epoch.
13724
           From now, messages that arrive out of order will be discarded. */
13725
16.3k
        ss->ssl3.hs.allowPreviousEpoch = PR_FALSE;
13726
16.3k
        ssl_ReleaseSSL3HandshakeLock(ss);
13727
16.3k
    }
13728
13729
    /* Check the length of the plaintext. */
13730
16.3k
    if (isTLS && plaintext->len > recordSizeLimit) {
13731
2
        plaintext->len = 0;
13732
        /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
13733
2
        if (IS_DTLS(ss)) {
13734
2
            return SECSuccess;
13735
2
        }
13736
0
        SSL3_SendAlert(ss, alert_fatal, record_overflow);
13737
0
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13738
0
        return SECFailure;
13739
2
    }
13740
13741
    /* Application data records are processed by the caller of this
13742
    ** function, not by this function.
13743
    */
13744
16.3k
    if (rType == ssl_ct_application_data) {
13745
0
        if (ss->firstHsDone)
13746
0
            return SECSuccess;
13747
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
13748
0
            ss->sec.isServer &&
13749
0
            ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
13750
0
            return tls13_HandleEarlyApplicationData(ss, plaintext);
13751
0
        }
13752
0
        plaintext->len = 0;
13753
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13754
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
13755
0
        return SECFailure;
13756
0
    }
13757
13758
16.3k
    rv = ssl3_HandleNonApplicationData(ss, rType, epoch, cText->seqNum,
13759
16.3k
                                       plaintext);
13760
13761
16.3k
#ifdef DEBUG
13762
    /* In Debug builds free and zero gather plaintext buffer after its content
13763
     * has been used/copied for advanced ASAN coverage/utilization.
13764
     * This frees buffer for non application data records, for application data
13765
     * records it is freed in sslsecur.c/DoRecv(). */
13766
16.3k
    sslBuffer_Clear(&ss->gs.buf);
13767
16.3k
#endif
13768
13769
16.3k
    return rv;
13770
16.3k
}
13771
13772
/*
13773
 * Initialization functions
13774
 */
13775
13776
void
13777
ssl_InitSecState(sslSecurityInfo *sec)
13778
8.40k
{
13779
8.40k
    sec->authType = ssl_auth_null;
13780
8.40k
    sec->authKeyBits = 0;
13781
8.40k
    sec->signatureScheme = ssl_sig_none;
13782
8.40k
    sec->keaType = ssl_kea_null;
13783
8.40k
    sec->keaKeyBits = 0;
13784
8.40k
    sec->keaGroup = NULL;
13785
8.40k
}
13786
13787
SECStatus
13788
ssl3_InitState(sslSocket *ss)
13789
8.40k
{
13790
8.40k
    SECStatus rv;
13791
13792
8.40k
    ss->ssl3.policy = SSL_ALLOWED;
13793
13794
8.40k
    ssl_InitSecState(&ss->sec);
13795
13796
8.40k
    ssl_GetSpecWriteLock(ss);
13797
8.40k
    PR_INIT_CLIST(&ss->ssl3.hs.cipherSpecs);
13798
8.40k
    rv = ssl_SetupNullCipherSpec(ss, ssl_secret_read);
13799
8.40k
    rv |= ssl_SetupNullCipherSpec(ss, ssl_secret_write);
13800
8.40k
    ss->ssl3.pwSpec = ss->ssl3.prSpec = NULL;
13801
8.40k
    ssl_ReleaseSpecWriteLock(ss);
13802
8.40k
    if (rv != SECSuccess) {
13803
        /* Rely on ssl_CreateNullCipherSpec() to set error code. */
13804
0
        return SECFailure;
13805
0
    }
13806
13807
8.40k
    ss->ssl3.hs.sendingSCSV = PR_FALSE;
13808
8.40k
    ss->ssl3.hs.preliminaryInfo = 0;
13809
8.40k
    ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : idle_handshake;
13810
13811
8.40k
    ssl3_ResetExtensionData(&ss->xtnData, ss);
13812
8.40k
    PR_INIT_CLIST(&ss->ssl3.hs.remoteExtensions);
13813
8.40k
    PR_INIT_CLIST(&ss->ssl3.hs.echOuterExtensions);
13814
8.40k
    if (IS_DTLS(ss)) {
13815
8.40k
        ss->ssl3.hs.sendMessageSeq = 0;
13816
8.40k
        ss->ssl3.hs.recvMessageSeq = 0;
13817
8.40k
        ss->ssl3.hs.rtTimer->timeout = DTLS_RETRANSMIT_INITIAL_MS;
13818
8.40k
        ss->ssl3.hs.rtRetries = 0;
13819
8.40k
        ss->ssl3.hs.recvdHighWater = -1;
13820
8.40k
        PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
13821
8.40k
        dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
13822
8.40k
    }
13823
13824
8.40k
    ss->ssl3.hs.currentSecret = NULL;
13825
8.40k
    ss->ssl3.hs.resumptionMasterSecret = NULL;
13826
8.40k
    ss->ssl3.hs.dheSecret = NULL;
13827
8.40k
    ss->ssl3.hs.clientEarlyTrafficSecret = NULL;
13828
8.40k
    ss->ssl3.hs.clientHsTrafficSecret = NULL;
13829
8.40k
    ss->ssl3.hs.serverHsTrafficSecret = NULL;
13830
8.40k
    ss->ssl3.hs.clientTrafficSecret = NULL;
13831
8.40k
    ss->ssl3.hs.serverTrafficSecret = NULL;
13832
8.40k
    ss->ssl3.hs.echHpkeCtx = NULL;
13833
8.40k
    ss->ssl3.hs.greaseEchSize = 100;
13834
8.40k
    ss->ssl3.hs.echAccepted = PR_FALSE;
13835
8.40k
    ss->ssl3.hs.echDecided = PR_FALSE;
13836
13837
8.40k
    ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
13838
8.40k
    ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
13839
13840
8.40k
    PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
13841
8.40k
    ss->ssl3.hs.messages.buf = NULL;
13842
8.40k
    ss->ssl3.hs.messages.space = 0;
13843
13844
8.40k
    ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
13845
8.40k
    PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0,
13846
8.40k
                sizeof(ss->ssl3.hs.newSessionTicket));
13847
13848
8.40k
    ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
13849
8.40k
    return SECSuccess;
13850
8.40k
}
13851
13852
/* record the export policy for this cipher suite */
13853
SECStatus
13854
ssl3_SetPolicy(ssl3CipherSuite which, int policy)
13855
0
{
13856
0
    ssl3CipherSuiteCfg *suite;
13857
13858
0
    suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
13859
0
    if (suite == NULL) {
13860
0
        return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13861
0
    }
13862
0
    suite->policy = policy;
13863
13864
0
    return SECSuccess;
13865
0
}
13866
13867
SECStatus
13868
ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
13869
0
{
13870
0
    const ssl3CipherSuiteCfg *suite;
13871
0
    PRInt32 policy;
13872
0
    SECStatus rv;
13873
13874
0
    suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13875
0
    if (suite) {
13876
0
        policy = suite->policy;
13877
0
        rv = SECSuccess;
13878
0
    } else {
13879
0
        policy = SSL_NOT_ALLOWED;
13880
0
        rv = SECFailure; /* err code was set by Lookup. */
13881
0
    }
13882
0
    *oPolicy = policy;
13883
0
    return rv;
13884
0
}
13885
13886
/* record the user preference for this suite */
13887
SECStatus
13888
ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
13889
0
{
13890
0
    ssl3CipherSuiteCfg *suite;
13891
13892
0
    suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
13893
0
    if (suite == NULL) {
13894
0
        return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13895
0
    }
13896
0
    suite->enabled = enabled;
13897
0
    return SECSuccess;
13898
0
}
13899
13900
/* return the user preference for this suite */
13901
SECStatus
13902
ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
13903
0
{
13904
0
    const ssl3CipherSuiteCfg *suite;
13905
0
    PRBool pref;
13906
0
    SECStatus rv;
13907
13908
0
    suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13909
0
    if (suite) {
13910
0
        pref = suite->enabled;
13911
0
        rv = SECSuccess;
13912
0
    } else {
13913
0
        pref = SSL_NOT_ALLOWED;
13914
0
        rv = SECFailure; /* err code was set by Lookup. */
13915
0
    }
13916
0
    *enabled = pref;
13917
0
    return rv;
13918
0
}
13919
13920
SECStatus
13921
ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
13922
42.6k
{
13923
42.6k
    ssl3CipherSuiteCfg *suite;
13924
13925
42.6k
    suite = ssl_LookupCipherSuiteCfgMutable(which, ss->cipherSuites);
13926
42.6k
    if (suite == NULL) {
13927
0
        return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13928
0
    }
13929
42.6k
    suite->enabled = enabled;
13930
42.6k
    return SECSuccess;
13931
42.6k
}
13932
13933
SECStatus
13934
ssl3_CipherPrefGet(const sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
13935
1.06k
{
13936
1.06k
    const ssl3CipherSuiteCfg *suite;
13937
1.06k
    PRBool pref;
13938
1.06k
    SECStatus rv;
13939
13940
1.06k
    suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
13941
1.06k
    if (suite) {
13942
1.06k
        pref = suite->enabled;
13943
1.06k
        rv = SECSuccess;
13944
1.06k
    } else {
13945
0
        pref = SSL_NOT_ALLOWED;
13946
0
        rv = SECFailure; /* err code was set by Lookup. */
13947
0
    }
13948
1.06k
    *enabled = pref;
13949
1.06k
    return rv;
13950
1.06k
}
13951
13952
SECStatus
13953
SSL_SignatureSchemePrefSet(PRFileDesc *fd, const SSLSignatureScheme *schemes,
13954
                           unsigned int count)
13955
0
{
13956
0
    sslSocket *ss;
13957
0
    unsigned int i;
13958
0
    unsigned int supported = 0;
13959
13960
0
    ss = ssl_FindSocket(fd);
13961
0
    if (!ss) {
13962
0
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefSet",
13963
0
                 SSL_GETPID(), fd));
13964
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
13965
0
        return SECFailure;
13966
0
    }
13967
13968
0
    if (!count) {
13969
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
13970
0
        return SECFailure;
13971
0
    }
13972
13973
0
    for (i = 0; i < count; ++i) {
13974
0
        if (ssl_IsSupportedSignatureScheme(schemes[i])) {
13975
0
            ++supported;
13976
0
        }
13977
0
    }
13978
    /* We don't check for duplicates, so it's possible to get too many. */
13979
0
    if (supported > MAX_SIGNATURE_SCHEMES) {
13980
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
13981
0
        return SECFailure;
13982
0
    }
13983
13984
0
    ss->ssl3.signatureSchemeCount = 0;
13985
0
    for (i = 0; i < count; ++i) {
13986
0
        if (!ssl_IsSupportedSignatureScheme(schemes[i])) {
13987
0
            SSL_DBG(("%d: SSL[%d]: invalid signature scheme %d ignored",
13988
0
                     SSL_GETPID(), fd, schemes[i]));
13989
0
            continue;
13990
0
        }
13991
13992
0
        ss->ssl3.signatureSchemes[ss->ssl3.signatureSchemeCount++] = schemes[i];
13993
0
    }
13994
13995
0
    if (ss->ssl3.signatureSchemeCount == 0) {
13996
0
        PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
13997
0
        return SECFailure;
13998
0
    }
13999
0
    return SECSuccess;
14000
0
}
14001
14002
SECStatus
14003
SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms,
14004
                     unsigned int count)
14005
0
{
14006
0
    SSLSignatureScheme schemes[MAX_SIGNATURE_SCHEMES];
14007
0
    unsigned int i;
14008
14009
0
    count = PR_MIN(PR_ARRAY_SIZE(schemes), count);
14010
0
    for (i = 0; i < count; ++i) {
14011
0
        schemes[i] = (algorithms[i].hashAlg << 8) | algorithms[i].sigAlg;
14012
0
    }
14013
0
    return SSL_SignatureSchemePrefSet(fd, schemes, count);
14014
0
}
14015
14016
SECStatus
14017
SSL_SignatureSchemePrefGet(PRFileDesc *fd, SSLSignatureScheme *schemes,
14018
                           unsigned int *count, unsigned int maxCount)
14019
0
{
14020
0
    sslSocket *ss;
14021
14022
0
    ss = ssl_FindSocket(fd);
14023
0
    if (!ss) {
14024
0
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefGet",
14025
0
                 SSL_GETPID(), fd));
14026
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14027
0
        return SECFailure;
14028
0
    }
14029
14030
0
    if (!schemes || !count ||
14031
0
        maxCount < ss->ssl3.signatureSchemeCount) {
14032
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14033
0
        return SECFailure;
14034
0
    }
14035
14036
0
    PORT_Memcpy(schemes, ss->ssl3.signatureSchemes,
14037
0
                ss->ssl3.signatureSchemeCount * sizeof(SSLSignatureScheme));
14038
0
    *count = ss->ssl3.signatureSchemeCount;
14039
0
    return SECSuccess;
14040
0
}
14041
14042
SECStatus
14043
SSL_SignaturePrefGet(PRFileDesc *fd, SSLSignatureAndHashAlg *algorithms,
14044
                     unsigned int *count, unsigned int maxCount)
14045
0
{
14046
0
    sslSocket *ss;
14047
0
    unsigned int i;
14048
14049
0
    ss = ssl_FindSocket(fd);
14050
0
    if (!ss) {
14051
0
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignaturePrefGet",
14052
0
                 SSL_GETPID(), fd));
14053
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14054
0
        return SECFailure;
14055
0
    }
14056
14057
0
    if (!algorithms || !count ||
14058
0
        maxCount < ss->ssl3.signatureSchemeCount) {
14059
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
14060
0
        return SECFailure;
14061
0
    }
14062
14063
0
    for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
14064
0
        algorithms[i].hashAlg = (ss->ssl3.signatureSchemes[i] >> 8) & 0xff;
14065
0
        algorithms[i].sigAlg = ss->ssl3.signatureSchemes[i] & 0xff;
14066
0
    }
14067
0
    *count = ss->ssl3.signatureSchemeCount;
14068
0
    return SECSuccess;
14069
0
}
14070
14071
unsigned int
14072
SSL_SignatureMaxCount(void)
14073
0
{
14074
0
    return MAX_SIGNATURE_SCHEMES;
14075
0
}
14076
14077
/* copy global default policy into socket. */
14078
void
14079
ssl3_InitSocketPolicy(sslSocket *ss)
14080
8.40k
{
14081
8.40k
    PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof(cipherSuites));
14082
8.40k
    PORT_Memcpy(ss->ssl3.signatureSchemes, defaultSignatureSchemes,
14083
8.40k
                sizeof(defaultSignatureSchemes));
14084
8.40k
    ss->ssl3.signatureSchemeCount = PR_ARRAY_SIZE(defaultSignatureSchemes);
14085
8.40k
}
14086
14087
/*
14088
** If ssl3 socket has completed the first handshake, and is in idle state,
14089
** then start a new handshake.
14090
** If flushCache is true, the SID cache will be flushed first, forcing a
14091
** "Full" handshake (not a session restart handshake), to be done.
14092
**
14093
** called from SSL_RedoHandshake(), which already holds the handshake locks.
14094
*/
14095
SECStatus
14096
ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
14097
0
{
14098
0
    sslSessionID *sid = ss->sec.ci.sid;
14099
0
    SECStatus rv;
14100
14101
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
14102
14103
0
    if (!ss->firstHsDone || (ss->ssl3.hs.ws != idle_handshake)) {
14104
0
        PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
14105
0
        return SECFailure;
14106
0
    }
14107
14108
0
    if (IS_DTLS(ss)) {
14109
0
        dtls_RehandshakeCleanup(ss);
14110
0
    }
14111
14112
0
    if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER ||
14113
0
        ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
14114
0
        PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
14115
0
        return SECFailure;
14116
0
    }
14117
0
    if (ss->version > ss->vrange.max || ss->version < ss->vrange.min) {
14118
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
14119
0
        return SECFailure;
14120
0
    }
14121
14122
0
    if (sid && flushCache) {
14123
0
        ssl_UncacheSessionID(ss); /* remove it from whichever cache it's in. */
14124
0
        ssl_FreeSID(sid);         /* dec ref count and free if zero. */
14125
0
        ss->sec.ci.sid = NULL;
14126
0
    }
14127
14128
0
    ssl_GetXmitBufLock(ss); /**************************************/
14129
14130
    /* start off a new handshake. */
14131
0
    if (ss->sec.isServer) {
14132
0
        rv = ssl3_SendHelloRequest(ss);
14133
0
    } else {
14134
0
        rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
14135
0
    }
14136
14137
0
    ssl_ReleaseXmitBufLock(ss); /**************************************/
14138
0
    return rv;
14139
0
}
14140
14141
/* Called from ssl_DestroySocketContents() in sslsock.c */
14142
void
14143
ssl3_DestroySSL3Info(sslSocket *ss)
14144
8.40k
{
14145
14146
8.40k
    if (ss->ssl3.clientCertificate != NULL)
14147
0
        CERT_DestroyCertificate(ss->ssl3.clientCertificate);
14148
14149
8.40k
    if (ss->ssl3.clientPrivateKey != NULL)
14150
0
        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
14151
14152
8.40k
    if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL) {
14153
0
        PORT_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
14154
0
        ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
14155
0
        ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
14156
0
    }
14157
14158
8.40k
    if (ss->ssl3.peerCertArena != NULL)
14159
3
        ssl3_CleanupPeerCerts(ss);
14160
14161
8.40k
    if (ss->ssl3.clientCertChain != NULL) {
14162
0
        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
14163
0
        ss->ssl3.clientCertChain = NULL;
14164
0
    }
14165
8.40k
    if (ss->ssl3.ca_list) {
14166
0
        CERT_FreeDistNames(ss->ssl3.ca_list);
14167
0
    }
14168
14169
    /* clean up handshake */
14170
8.40k
    if (ss->ssl3.hs.md5) {
14171
0
        PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
14172
0
    }
14173
8.40k
    if (ss->ssl3.hs.sha) {
14174
0
        PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
14175
0
    }
14176
8.40k
    if (ss->ssl3.hs.shaEchInner) {
14177
0
        PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
14178
0
    }
14179
8.40k
    if (ss->ssl3.hs.shaPostHandshake) {
14180
0
        PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
14181
0
    }
14182
8.40k
    if (ss->ssl3.hs.messages.buf) {
14183
6.10k
        sslBuffer_Clear(&ss->ssl3.hs.messages);
14184
6.10k
    }
14185
8.40k
    if (ss->ssl3.hs.echInnerMessages.buf) {
14186
0
        sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
14187
0
    }
14188
8.40k
    if (ss->ssl3.hs.dtls13ClientMessageBuffer.buf) {
14189
0
        sslBuffer_Clear(&ss->ssl3.hs.dtls13ClientMessageBuffer);
14190
0
    }
14191
14192
    /* free the SSL3Buffer (msg_body) */
14193
8.40k
    PORT_Free(ss->ssl3.hs.msg_body.buf);
14194
14195
8.40k
    SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
14196
8.40k
    SECITEM_FreeItem(&ss->ssl3.hs.srvVirtName, PR_FALSE);
14197
8.40k
    SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
14198
14199
    /* Destroy the DTLS data */
14200
8.40k
    if (IS_DTLS(ss)) {
14201
8.40k
        dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
14202
8.40k
        if (ss->ssl3.hs.recvdFragments.buf) {
14203
177
            PORT_Free(ss->ssl3.hs.recvdFragments.buf);
14204
177
        }
14205
8.40k
    }
14206
14207
    /* Destroy remote extensions */
14208
8.40k
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
14209
8.40k
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.echOuterExtensions);
14210
8.40k
    ssl3_DestroyExtensionData(&ss->xtnData);
14211
14212
    /* Destroy cipher specs */
14213
8.40k
    ssl_DestroyCipherSpecs(&ss->ssl3.hs.cipherSpecs);
14214
14215
    /* Destroy TLS 1.3 keys */
14216
8.40k
    if (ss->ssl3.hs.currentSecret)
14217
0
        PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
14218
8.40k
    if (ss->ssl3.hs.resumptionMasterSecret)
14219
0
        PK11_FreeSymKey(ss->ssl3.hs.resumptionMasterSecret);
14220
8.40k
    if (ss->ssl3.hs.dheSecret)
14221
0
        PK11_FreeSymKey(ss->ssl3.hs.dheSecret);
14222
8.40k
    if (ss->ssl3.hs.clientEarlyTrafficSecret)
14223
0
        PK11_FreeSymKey(ss->ssl3.hs.clientEarlyTrafficSecret);
14224
8.40k
    if (ss->ssl3.hs.clientHsTrafficSecret)
14225
0
        PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
14226
8.40k
    if (ss->ssl3.hs.serverHsTrafficSecret)
14227
0
        PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
14228
8.40k
    if (ss->ssl3.hs.clientTrafficSecret)
14229
0
        PK11_FreeSymKey(ss->ssl3.hs.clientTrafficSecret);
14230
8.40k
    if (ss->ssl3.hs.serverTrafficSecret)
14231
0
        PK11_FreeSymKey(ss->ssl3.hs.serverTrafficSecret);
14232
8.40k
    if (ss->ssl3.hs.earlyExporterSecret)
14233
0
        PK11_FreeSymKey(ss->ssl3.hs.earlyExporterSecret);
14234
8.40k
    if (ss->ssl3.hs.exporterSecret)
14235
0
        PK11_FreeSymKey(ss->ssl3.hs.exporterSecret);
14236
14237
8.40k
    ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
14238
    /* Destroy TLS 1.3 buffered early data. */
14239
8.40k
    tls13_DestroyEarlyData(&ss->ssl3.hs.bufferedEarlyData);
14240
14241
    /* Destroy TLS 1.3 PSKs. */
14242
8.40k
    tls13_DestroyPskList(&ss->ssl3.hs.psks);
14243
14244
    /* TLS 1.3 ECH state. */
14245
8.40k
    PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE);
14246
8.40k
    PORT_Free((void *)ss->ssl3.hs.echPublicName); /* CONST */
14247
8.40k
    sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
14248
14249
    /* TLS 1.3 GREASE (client) state. */
14250
8.40k
    tls13_ClientGreaseDestroy(ss);
14251
14252
    /* TLS ClientHello Extension Permutation state. */
14253
8.40k
    tls_ClientHelloExtensionPermutationDestroy(ss);
14254
8.40k
}
14255
14256
/* check if the current cipher spec is FIPS. We only need to
14257
 * check the contexts here, if the kea, prf or keys were not FIPS,
14258
 * that status would have been rolled up in the create context
14259
 * call */
14260
static PRBool
14261
ssl_cipherSpecIsFips(ssl3CipherSpec *spec)
14262
0
{
14263
0
    if (!spec || !spec->cipherDef) {
14264
0
        return PR_FALSE;
14265
0
    }
14266
14267
0
    if (spec->cipherDef->type != type_aead) {
14268
0
        if (spec->keyMaterial.macContext == NULL) {
14269
0
            return PR_FALSE;
14270
0
        }
14271
0
        if (!PK11_ContextGetFIPSStatus(spec->keyMaterial.macContext)) {
14272
0
            return PR_FALSE;
14273
0
        }
14274
0
    }
14275
0
    if (!spec->cipherContext) {
14276
0
        return PR_FALSE;
14277
0
    }
14278
0
    return PK11_ContextGetFIPSStatus(spec->cipherContext);
14279
0
}
14280
14281
/* return true if the current operation is running in FIPS mode */
14282
PRBool
14283
ssl_isFIPS(sslSocket *ss)
14284
0
{
14285
0
    if (!ssl_cipherSpecIsFips(ss->ssl3.crSpec)) {
14286
0
        return PR_FALSE;
14287
0
    }
14288
0
    return ssl_cipherSpecIsFips(ss->ssl3.cwSpec);
14289
0
}
14290
14291
/*
14292
 * parse the policy value for a single algorithm in a cipher_suite,
14293
 *   return TRUE if we disallow by the cipher suite by policy
14294
 *   (we don't have to parse any more algorithm policies on this cipher suite),
14295
 *  otherwise return FALSE.
14296
 *   1. If we don't have the required policy, disable by default, disallow by
14297
 *      policy and return TRUE (no more processing needed).
14298
 *   2. If we have the required policy, and we are disabled, return FALSE,
14299
 *      (if we are disabled, we only need to parse policy, not default).
14300
 *   3. If we have the required policy, and we aren't adjusting the defaults
14301
 *      return FALSE. (only parsing the policy, not default).
14302
 *   4. We have the required policy and we are adjusting the defaults.
14303
 *      If we are setting default = FALSE, set isDisabled to true so that
14304
 *      we don't try to re-enable the cipher suite based on a different
14305
 *      algorithm.
14306
 */
14307
PRBool
14308
ssl_HandlePolicy(int cipher_suite, SECOidTag policyOid,
14309
                 PRUint32 requiredPolicy, PRBool *isDisabled)
14310
0
{
14311
0
    PRUint32 policy;
14312
0
    SECStatus rv;
14313
14314
    /* first fetch the policy for this algorithm */
14315
0
    rv = NSS_GetAlgorithmPolicy(policyOid, &policy);
14316
0
    if (rv != SECSuccess) {
14317
0
        return PR_FALSE; /* no policy value, continue to the next algorithm */
14318
0
    }
14319
    /* first, are we allowed by policy, if not turn off allow and disable */
14320
0
    if (!(policy & requiredPolicy)) {
14321
0
        ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE);
14322
0
        ssl_CipherPolicySet(cipher_suite, SSL_NOT_ALLOWED);
14323
0
        return PR_TRUE;
14324
0
    }
14325
    /* If we are already disabled, or the policy isn't setting a default
14326
     * we are done processing this algorithm */
14327
0
    if (*isDisabled || (policy & NSS_USE_DEFAULT_NOT_VALID)) {
14328
0
        return PR_FALSE;
14329
0
    }
14330
    /* set the default value for the cipher suite. If we disable the cipher
14331
     * suite, remember that so we don't process the next default. This has
14332
     * the effect of disabling the whole cipher suite if any of the
14333
     * algorithms it uses are disabled by default. We still have to
14334
     * process the upper level because the cipher suite is still allowed
14335
     * by policy, and we may still have to disallow it based on other
14336
     * algorithms in the cipher suite. */
14337
0
    if (policy & NSS_USE_DEFAULT_SSL_ENABLE) {
14338
0
        ssl_CipherPrefSetDefault(cipher_suite, PR_TRUE);
14339
0
    } else {
14340
0
        *isDisabled = PR_TRUE;
14341
0
        ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE);
14342
0
    }
14343
0
    return PR_FALSE;
14344
0
}
14345
14346
0
#define MAP_NULL(x) (((x) != 0) ? (x) : SEC_OID_NULL_CIPHER)
14347
14348
SECStatus
14349
ssl3_ApplyNSSPolicy(void)
14350
1
{
14351
1
    unsigned i;
14352
1
    SECStatus rv;
14353
1
    PRUint32 policy = 0;
14354
14355
1
    rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy);
14356
1
    if (rv != SECSuccess || !(policy & NSS_USE_POLICY_IN_SSL)) {
14357
1
        return SECSuccess; /* do nothing */
14358
1
    }
14359
14360
    /* disable every ciphersuite */
14361
0
    for (i = 1; i < PR_ARRAY_SIZE(cipher_suite_defs); ++i) {
14362
0
        const ssl3CipherSuiteDef *suite = &cipher_suite_defs[i];
14363
0
        SECOidTag policyOid;
14364
0
        PRBool isDisabled = PR_FALSE;
14365
14366
        /* if we haven't explicitly disabled it below enable by policy */
14367
0
        ssl_CipherPolicySet(suite->cipher_suite, SSL_ALLOWED);
14368
14369
        /* now check the various key exchange, ciphers and macs and
14370
         * if we ever disallow by policy, we are done, go to the next cipher
14371
         */
14372
0
        policyOid = MAP_NULL(kea_defs[suite->key_exchange_alg].oid);
14373
0
        if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14374
0
                             NSS_USE_ALG_IN_SSL_KX, &isDisabled)) {
14375
0
            continue;
14376
0
        }
14377
14378
0
        policyOid = MAP_NULL(ssl_GetBulkCipherDef(suite)->oid);
14379
0
        if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14380
0
                             NSS_USE_ALG_IN_SSL, &isDisabled)) {
14381
0
            continue;
14382
0
        }
14383
14384
0
        if (ssl_GetBulkCipherDef(suite)->type != type_aead) {
14385
0
            policyOid = MAP_NULL(ssl_GetMacDefByAlg(suite->mac_alg)->oid);
14386
0
            if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14387
0
                                 NSS_USE_ALG_IN_SSL, &isDisabled)) {
14388
0
                continue;
14389
0
            }
14390
0
        }
14391
0
    }
14392
14393
0
    rv = ssl3_ConstrainRangeByPolicy();
14394
14395
0
    return rv;
14396
1
}
14397
14398
/* End of ssl3con.c */