Coverage Report

Created: 2018-09-25 14:53

/src/mozilla-central/security/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 "prtime.h"
25
#include "prinrval.h"
26
#include "prerror.h"
27
#include "pratom.h"
28
#include "prthread.h"
29
#include "nss.h"
30
#include "nssoptions.h"
31
32
#include "pk11func.h"
33
#include "secmod.h"
34
#include "blapi.h"
35
36
#include <stdio.h>
37
38
static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
39
                                       PK11SlotInfo *serverKeySlot);
40
static SECStatus ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
41
                                          PK11SymKey **msp);
42
static SECStatus ssl3_DeriveConnectionKeys(sslSocket *ss,
43
                                           PK11SymKey *masterSecret);
44
static SECStatus ssl3_HandshakeFailure(sslSocket *ss);
45
static SECStatus ssl3_SendCertificate(sslSocket *ss);
46
static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
47
static SECStatus ssl3_SendNextProto(sslSocket *ss);
48
static SECStatus ssl3_SendFinished(sslSocket *ss, PRInt32 flags);
49
static SECStatus ssl3_SendServerHelloDone(sslSocket *ss);
50
static SECStatus ssl3_SendServerKeyExchange(sslSocket *ss);
51
static SECStatus ssl3_HandleClientHelloPart2(sslSocket *ss,
52
                                             SECItem *suites,
53
                                             sslSessionID *sid,
54
                                             const PRUint8 *msg,
55
                                             unsigned int len);
56
static SECStatus ssl3_HandleServerHelloPart2(sslSocket *ss,
57
                                             const SECItem *sidBytes,
58
                                             int *retErrCode);
59
static SECStatus ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss,
60
                                                      PRUint8 *b,
61
                                                      PRUint32 length);
62
static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
63
64
static CK_MECHANISM_TYPE ssl3_GetHashMechanismByHashType(SSLHashType hashType);
65
static CK_MECHANISM_TYPE ssl3_GetMgfMechanismByHashType(SSLHashType hash);
66
PRBool ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme);
67
68
const PRUint8 ssl_hello_retry_random[] = {
69
    0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
70
    0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
71
    0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
72
    0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
73
};
74
PR_STATIC_ASSERT(PR_ARRAY_SIZE(ssl_hello_retry_random) == SSL3_RANDOM_LENGTH);
75
76
/* This list of SSL3 cipher suites is sorted in descending order of
77
 * precedence (desirability).  It only includes cipher suites we implement.
78
 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
79
 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
80
 *
81
 * Important: See bug 946147 before enabling, reordering, or adding any cipher
82
 * suites to this list.
83
 */
84
/* clang-format off */
85
static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
86
   /*      cipher_suite                     policy       enabled   isPresent */
87
 /* Special TLS 1.3 suites. */
88
 { TLS_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE },
89
 { TLS_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE },
90
 { TLS_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE },
91
92
 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
93
 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,   SSL_ALLOWED, PR_TRUE, PR_FALSE},
94
 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
95
 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,   SSL_ALLOWED, PR_TRUE, PR_FALSE},
96
 { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE},
97
 { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
98
   /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around
99
    * bug 946147.
100
    */
101
 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,    SSL_ALLOWED, PR_TRUE, PR_FALSE},
102
 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,    SSL_ALLOWED, PR_TRUE, PR_FALSE},
103
 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,      SSL_ALLOWED, PR_TRUE, PR_FALSE},
104
 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
105
 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,   SSL_ALLOWED, PR_TRUE, PR_FALSE},
106
 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,      SSL_ALLOWED, PR_TRUE, PR_FALSE},
107
 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE},
108
 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
109
 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
110
 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
111
 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,        SSL_ALLOWED, PR_FALSE, PR_FALSE},
112
 { TLS_ECDHE_RSA_WITH_RC4_128_SHA,          SSL_ALLOWED, PR_FALSE, PR_FALSE},
113
114
 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
115
 { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,SSL_ALLOWED,PR_TRUE,  PR_FALSE},
116
 { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
117
 { TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
118
 { TLS_DHE_DSS_WITH_AES_256_GCM_SHA384,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
119
 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
120
 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
121
 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
122
 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
123
 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
124
 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
125
 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
126
 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
127
 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
128
 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
129
 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
130
 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
131
 { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,       SSL_ALLOWED, PR_TRUE,  PR_FALSE},
132
 { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,       SSL_ALLOWED, PR_TRUE,  PR_FALSE},
133
 { TLS_DHE_DSS_WITH_RC4_128_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
134
135
 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
136
 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
137
 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
138
 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
139
 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,    SSL_ALLOWED, PR_FALSE, PR_FALSE},
140
 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
141
 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA,         SSL_ALLOWED, PR_FALSE, PR_FALSE},
142
 { TLS_ECDH_RSA_WITH_RC4_128_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
143
144
 /* RSA */
145
 { TLS_RSA_WITH_AES_128_GCM_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
146
 { TLS_RSA_WITH_AES_256_GCM_SHA384,         SSL_ALLOWED, PR_FALSE, PR_FALSE},
147
 { TLS_RSA_WITH_AES_128_CBC_SHA,            SSL_ALLOWED, PR_TRUE,  PR_FALSE},
148
 { TLS_RSA_WITH_AES_128_CBC_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
149
 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
150
 { TLS_RSA_WITH_AES_256_CBC_SHA,            SSL_ALLOWED, PR_TRUE,  PR_FALSE},
151
 { TLS_RSA_WITH_AES_256_CBC_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
152
 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
153
 { TLS_RSA_WITH_SEED_CBC_SHA,               SSL_ALLOWED, PR_FALSE, PR_FALSE},
154
 { TLS_RSA_WITH_3DES_EDE_CBC_SHA,           SSL_ALLOWED, PR_TRUE,  PR_FALSE},
155
 { TLS_RSA_WITH_RC4_128_SHA,                SSL_ALLOWED, PR_TRUE,  PR_FALSE},
156
 { TLS_RSA_WITH_RC4_128_MD5,                SSL_ALLOWED, PR_TRUE,  PR_FALSE},
157
158
 /* 56-bit DES "domestic" cipher suites */
159
 { TLS_DHE_RSA_WITH_DES_CBC_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
160
 { TLS_DHE_DSS_WITH_DES_CBC_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
161
 { TLS_RSA_WITH_DES_CBC_SHA,                SSL_ALLOWED, PR_FALSE, PR_FALSE},
162
163
 /* ciphersuites with no encryption */
164
 { TLS_ECDHE_ECDSA_WITH_NULL_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
165
 { TLS_ECDHE_RSA_WITH_NULL_SHA,             SSL_ALLOWED, PR_FALSE, PR_FALSE},
166
 { TLS_ECDH_RSA_WITH_NULL_SHA,              SSL_ALLOWED, PR_FALSE, PR_FALSE},
167
 { TLS_ECDH_ECDSA_WITH_NULL_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
168
 { TLS_RSA_WITH_NULL_SHA,                   SSL_ALLOWED, PR_FALSE, PR_FALSE},
169
 { TLS_RSA_WITH_NULL_SHA256,                SSL_ALLOWED, PR_FALSE, PR_FALSE},
170
 { TLS_RSA_WITH_NULL_MD5,                   SSL_ALLOWED, PR_FALSE, PR_FALSE},
171
};
172
/* clang-format on */
173
174
/* This is the default supported set of signature schemes.  The order of the
175
 * hashes here is all that is important, since that will (sometimes) determine
176
 * which hash we use.  The key pair (i.e., cert) is the primary thing that
177
 * determines what we use and this doesn't affect how we select key pairs.  The
178
 * order of signature types is based on the same rules for ordering we use for
179
 * cipher suites just for consistency.
180
 */
181
static const SSLSignatureScheme defaultSignatureSchemes[] = {
182
    ssl_sig_ecdsa_secp256r1_sha256,
183
    ssl_sig_ecdsa_secp384r1_sha384,
184
    ssl_sig_ecdsa_secp521r1_sha512,
185
    ssl_sig_ecdsa_sha1,
186
    ssl_sig_rsa_pss_rsae_sha256,
187
    ssl_sig_rsa_pss_rsae_sha384,
188
    ssl_sig_rsa_pss_rsae_sha512,
189
    ssl_sig_rsa_pkcs1_sha256,
190
    ssl_sig_rsa_pkcs1_sha384,
191
    ssl_sig_rsa_pkcs1_sha512,
192
    ssl_sig_rsa_pkcs1_sha1,
193
    ssl_sig_dsa_sha256,
194
    ssl_sig_dsa_sha384,
195
    ssl_sig_dsa_sha512,
196
    ssl_sig_dsa_sha1
197
};
198
PR_STATIC_ASSERT(PR_ARRAY_SIZE(defaultSignatureSchemes) <=
199
                 MAX_SIGNATURE_SCHEMES);
200
201
/* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order.
202
 */
203
#ifdef DEBUG
204
void
205
ssl3_CheckCipherSuiteOrderConsistency()
206
{
207
    unsigned int i;
208
209
    PORT_Assert(SSL_NumImplementedCiphers == PR_ARRAY_SIZE(cipherSuites));
210
211
    for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) {
212
        PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite);
213
    }
214
}
215
#endif
216
217
static const /*SSL3ClientCertificateType */ PRUint8 certificate_types[] = {
218
    ct_RSA_sign,
219
    ct_ECDSA_sign,
220
    ct_DSS_sign,
221
};
222
223
static SSL3Statistics ssl3stats;
224
225
static const ssl3KEADef kea_defs[] =
226
    {
227
      /* indexed by SSL3KeyExchangeAlgorithm */
228
      /* kea            exchKeyType signKeyType authKeyType ephemeral  oid */
229
      { kea_null, ssl_kea_null, nullKey, ssl_auth_null, PR_FALSE, 0 },
230
      { kea_rsa, ssl_kea_rsa, nullKey, ssl_auth_rsa_decrypt, PR_FALSE, SEC_OID_TLS_RSA },
231
      { kea_dh_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_FALSE, SEC_OID_TLS_DH_DSS },
232
      { kea_dh_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_FALSE, SEC_OID_TLS_DH_RSA },
233
      { kea_dhe_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_TRUE, SEC_OID_TLS_DHE_DSS },
234
      { kea_dhe_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_DHE_RSA },
235
      { kea_dh_anon, ssl_kea_dh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_DH_ANON },
236
      { kea_ecdh_ecdsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_ecdsa, PR_FALSE, SEC_OID_TLS_ECDH_ECDSA },
237
      { kea_ecdhe_ecdsa, ssl_kea_ecdh, ecKey, ssl_auth_ecdsa, PR_TRUE, SEC_OID_TLS_ECDHE_ECDSA },
238
      { kea_ecdh_rsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_rsa, PR_FALSE, SEC_OID_TLS_ECDH_RSA },
239
      { kea_ecdhe_rsa, ssl_kea_ecdh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_ECDHE_RSA },
240
      { kea_ecdh_anon, ssl_kea_ecdh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_ECDH_ANON },
241
      { kea_ecdhe_psk, ssl_kea_ecdh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_ECDHE_PSK },
242
      { kea_dhe_psk, ssl_kea_dh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_DHE_PSK },
243
      { kea_tls13_any, ssl_kea_tls13_any, nullKey, ssl_auth_tls13_any, PR_TRUE, SEC_OID_TLS13_KEA_ANY },
244
    };
245
246
/* must use ssl_LookupCipherSuiteDef to access */
247
static const ssl3CipherSuiteDef cipher_suite_defs[] =
248
    {
249
      /*  cipher_suite                    bulk_cipher_alg mac_alg key_exchange_alg prf_hash */
250
      /*  Note that the prf_hash_alg is the hash function used by the PRF, see sslimpl.h.  */
251
252
      { TLS_NULL_WITH_NULL_NULL, cipher_null, ssl_mac_null, kea_null, ssl_hash_none },
253
      { TLS_RSA_WITH_NULL_MD5, cipher_null, ssl_mac_md5, kea_rsa, ssl_hash_none },
254
      { TLS_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_rsa, ssl_hash_none },
255
      { TLS_RSA_WITH_NULL_SHA256, cipher_null, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
256
      { TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, ssl_mac_md5, kea_rsa, ssl_hash_none },
257
      { TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_rsa, ssl_hash_none },
258
      { TLS_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_rsa, ssl_hash_none },
259
      { TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_rsa, ssl_hash_none },
260
      { TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
261
      { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
262
        cipher_3des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
263
      { TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
264
      { TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
265
      { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
266
        cipher_3des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
267
268
      /* New TLS cipher suites */
269
      { TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
270
      { TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
271
      { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
272
      { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
273
      { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
274
      { TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
275
      { TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
276
      { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
277
      { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
278
      { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
279
      { TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha384 },
280
281
      { TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, ssl_mac_sha, kea_rsa, ssl_hash_none },
282
283
      { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
284
      { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
285
        cipher_camellia_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
286
      { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
287
        cipher_camellia_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
288
      { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
289
      { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
290
        cipher_camellia_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
291
      { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
292
        cipher_camellia_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
293
294
      { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
295
      { TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha256 },
296
297
      { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
298
      { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
299
      { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha384 },
300
      { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha384 },
301
      { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_ecdsa, ssl_hash_sha384 },
302
      { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_rsa, ssl_hash_sha384 },
303
      { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha256 },
304
      { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
305
      { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
306
      { TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha384 },
307
      { TLS_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha384 },
308
309
      { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
310
311
      { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
312
      { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
313
314
      { TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
315
      { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
316
      { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
317
      { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
318
      { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
319
320
      { TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
321
      { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
322
      { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
323
      { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
324
      { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_ecdsa, ssl_hash_sha256 },
325
      { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
326
327
      { TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
328
      { TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
329
      { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
330
      { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
331
      { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
332
333
      { TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
334
      { TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
335
      { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
336
      { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
337
      { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_rsa, ssl_hash_sha256 },
338
      { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
339
340
      { TLS_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
341
      { TLS_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
342
      { TLS_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha384 },
343
    };
344
345
static const CK_MECHANISM_TYPE auth_alg_defs[] = {
346
    CKM_INVALID_MECHANISM, /* ssl_auth_null */
347
    CKM_RSA_PKCS,          /* ssl_auth_rsa_decrypt */
348
    CKM_DSA, /* ? _SHA1 */ /* ssl_auth_dsa */
349
    CKM_INVALID_MECHANISM, /* ssl_auth_kea (unused) */
350
    CKM_ECDSA,             /* ssl_auth_ecdsa */
351
    CKM_ECDH1_DERIVE,      /* ssl_auth_ecdh_rsa */
352
    CKM_ECDH1_DERIVE,      /* ssl_auth_ecdh_ecdsa */
353
    CKM_RSA_PKCS,          /* ssl_auth_rsa_sign */
354
    CKM_RSA_PKCS_PSS,      /* ssl_auth_rsa_pss */
355
    CKM_NSS_HKDF_SHA256,   /* ssl_auth_psk (just check for HKDF) */
356
    CKM_INVALID_MECHANISM  /* ssl_auth_tls13_any */
357
};
358
PR_STATIC_ASSERT(PR_ARRAY_SIZE(auth_alg_defs) == ssl_auth_size);
359
360
static const CK_MECHANISM_TYPE kea_alg_defs[] = {
361
    CKM_INVALID_MECHANISM, /* ssl_kea_null */
362
    CKM_RSA_PKCS,          /* ssl_kea_rsa */
363
    CKM_DH_PKCS_DERIVE,    /* ssl_kea_dh */
364
    CKM_INVALID_MECHANISM, /* ssl_kea_fortezza (unused) */
365
    CKM_ECDH1_DERIVE,      /* ssl_kea_ecdh */
366
    CKM_ECDH1_DERIVE,      /* ssl_kea_ecdh_psk */
367
    CKM_DH_PKCS_DERIVE,    /* ssl_kea_dh_psk */
368
    CKM_INVALID_MECHANISM, /* ssl_kea_tls13_any */
369
};
370
PR_STATIC_ASSERT(PR_ARRAY_SIZE(kea_alg_defs) == ssl_kea_size);
371
372
typedef struct SSLCipher2MechStr {
373
    SSLCipherAlgorithm calg;
374
    CK_MECHANISM_TYPE cmech;
375
} SSLCipher2Mech;
376
377
/* indexed by type SSLCipherAlgorithm */
378
static const SSLCipher2Mech alg2Mech[] = {
379
    /* calg,          cmech  */
380
    { ssl_calg_null, CKM_INVALID_MECHANISM },
381
    { ssl_calg_rc4, CKM_RC4 },
382
    { ssl_calg_rc2, CKM_RC2_CBC },
383
    { ssl_calg_des, CKM_DES_CBC },
384
    { ssl_calg_3des, CKM_DES3_CBC },
385
    { ssl_calg_idea, CKM_IDEA_CBC },
386
    { ssl_calg_fortezza, CKM_SKIPJACK_CBC64 },
387
    { ssl_calg_aes, CKM_AES_CBC },
388
    { ssl_calg_camellia, CKM_CAMELLIA_CBC },
389
    { ssl_calg_seed, CKM_SEED_CBC },
390
    { ssl_calg_aes_gcm, CKM_AES_GCM },
391
    { ssl_calg_chacha20, CKM_NSS_CHACHA20_POLY1305 },
392
};
393
394
const PRUint8 tls13_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
395
                                           0x47, 0x52, 0x44, 0x01 };
396
const PRUint8 tls12_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
397
                                           0x47, 0x52, 0x44, 0x00 };
398
PR_STATIC_ASSERT(sizeof(tls13_downgrade_random) ==
399
                 sizeof(tls13_downgrade_random));
400
401
/* The ECCWrappedKeyInfo structure defines how various pieces of
402
 * information are laid out within wrappedSymmetricWrappingkey
403
 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
404
 * a 512-byte buffer (see sslimpl.h), the variable length field
405
 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
406
 *
407
 * XXX For now, NSS only supports named elliptic curves of size 571 bits
408
 * or smaller. The public value will fit within 145 bytes and EC params
409
 * will fit within 12 bytes. We'll need to revisit this when NSS
410
 * supports arbitrary curves.
411
 */
412
0
#define MAX_EC_WRAPPED_KEY_BUFLEN 504
413
414
typedef struct ECCWrappedKeyInfoStr {
415
    PRUint16 size;                          /* EC public key size in bits */
416
    PRUint16 encodedParamLen;               /* length (in bytes) of DER encoded EC params */
417
    PRUint16 pubValueLen;                   /* length (in bytes) of EC public value */
418
    PRUint16 wrappedKeyLen;                 /* length (in bytes) of the wrapped key */
419
    PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
420
    /* EC public-key params, the EC public value and the wrapped key  */
421
} ECCWrappedKeyInfo;
422
423
CK_MECHANISM_TYPE
424
ssl3_Alg2Mech(SSLCipherAlgorithm calg)
425
0
{
426
0
    PORT_Assert(alg2Mech[calg].calg == calg);
427
0
    return alg2Mech[calg].cmech;
428
0
}
429
430
#if defined(TRACE)
431
432
static char *
433
ssl3_DecodeHandshakeType(int msgType)
434
{
435
    char *rv;
436
    static char line[40];
437
438
    switch (msgType) {
439
        case ssl_hs_hello_request:
440
            rv = "hello_request (0)";
441
            break;
442
        case ssl_hs_client_hello:
443
            rv = "client_hello  (1)";
444
            break;
445
        case ssl_hs_server_hello:
446
            rv = "server_hello  (2)";
447
            break;
448
        case ssl_hs_hello_verify_request:
449
            rv = "hello_verify_request (3)";
450
            break;
451
        case ssl_hs_new_session_ticket:
452
            rv = "new_session_ticket (4)";
453
            break;
454
        case ssl_hs_end_of_early_data:
455
            rv = "end_of_early_data (5)";
456
            break;
457
        case ssl_hs_hello_retry_request:
458
            rv = "hello_retry_request (6)";
459
            break;
460
        case ssl_hs_encrypted_extensions:
461
            rv = "encrypted_extensions (8)";
462
            break;
463
        case ssl_hs_certificate:
464
            rv = "certificate  (11)";
465
            break;
466
        case ssl_hs_server_key_exchange:
467
            rv = "server_key_exchange (12)";
468
            break;
469
        case ssl_hs_certificate_request:
470
            rv = "certificate_request (13)";
471
            break;
472
        case ssl_hs_server_hello_done:
473
            rv = "server_hello_done   (14)";
474
            break;
475
        case ssl_hs_certificate_verify:
476
            rv = "certificate_verify  (15)";
477
            break;
478
        case ssl_hs_client_key_exchange:
479
            rv = "client_key_exchange (16)";
480
            break;
481
        case ssl_hs_finished:
482
            rv = "finished     (20)";
483
            break;
484
        case ssl_hs_certificate_status:
485
            rv = "certificate_status  (22)";
486
            break;
487
        case ssl_hs_key_update:
488
            rv = "key_update   (24)";
489
            break;
490
        default:
491
            sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType);
492
            rv = line;
493
    }
494
    return rv;
495
}
496
497
static char *
498
ssl3_DecodeContentType(int msgType)
499
{
500
    char *rv;
501
    static char line[40];
502
503
    switch (msgType) {
504
        case ssl_ct_change_cipher_spec:
505
            rv = "change_cipher_spec (20)";
506
            break;
507
        case ssl_ct_alert:
508
            rv = "alert      (21)";
509
            break;
510
        case ssl_ct_handshake:
511
            rv = "handshake  (22)";
512
            break;
513
        case ssl_ct_application_data:
514
            rv = "application_data (23)";
515
            break;
516
        case ssl_ct_ack:
517
            rv = "ack (25)";
518
            break;
519
        default:
520
            sprintf(line, "*UNKNOWN* record type! (%d)", msgType);
521
            rv = line;
522
    }
523
    return rv;
524
}
525
526
#endif
527
528
SSL3Statistics *
529
SSL_GetStatistics(void)
530
0
{
531
0
    return &ssl3stats;
532
0
}
533
534
typedef struct tooLongStr {
535
#if defined(IS_LITTLE_ENDIAN)
536
    PRInt32 low;
537
    PRInt32 high;
538
#else
539
    PRInt32 high;
540
    PRInt32 low;
541
#endif
542
} tooLong;
543
544
void
545
SSL_AtomicIncrementLong(long *x)
546
0
{
547
0
    if ((sizeof *x) == sizeof(PRInt32)) {
548
0
        PR_ATOMIC_INCREMENT((PRInt32 *)x);
549
0
    } else {
550
0
        tooLong *tl = (tooLong *)x;
551
0
        if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
552
0
            PR_ATOMIC_INCREMENT(&tl->high);
553
0
    }
554
0
}
555
556
static PRBool
557
ssl3_CipherSuiteAllowedForVersionRange(
558
    ssl3CipherSuite cipherSuite,
559
    const SSLVersionRange *vrange)
560
0
{
561
0
    switch (cipherSuite) {
562
0
        case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
563
0
        case TLS_RSA_WITH_AES_256_CBC_SHA256:
564
0
        case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
565
0
        case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
566
0
        case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
567
0
        case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
568
0
        case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
569
0
        case TLS_RSA_WITH_AES_128_CBC_SHA256:
570
0
        case TLS_RSA_WITH_AES_128_GCM_SHA256:
571
0
        case TLS_RSA_WITH_AES_256_GCM_SHA384:
572
0
        case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
573
0
        case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
574
0
        case TLS_RSA_WITH_NULL_SHA256:
575
0
        case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
576
0
        case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
577
0
        case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
578
0
        case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
579
0
        case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
580
0
        case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
581
0
        case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
582
0
        case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
583
0
        case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
584
0
        case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
585
0
        case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
586
0
            return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2 &&
587
0
                   vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
588
0
589
0
        /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and
590
0
         * point formats.*/
591
0
        case TLS_ECDH_ECDSA_WITH_NULL_SHA:
592
0
        case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
593
0
        case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
594
0
        case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
595
0
        case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
596
0
        case TLS_ECDHE_ECDSA_WITH_NULL_SHA:
597
0
        case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
598
0
        case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
599
0
        case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
600
0
        case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
601
0
        case TLS_ECDH_RSA_WITH_NULL_SHA:
602
0
        case TLS_ECDH_RSA_WITH_RC4_128_SHA:
603
0
        case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
604
0
        case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
605
0
        case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
606
0
        case TLS_ECDHE_RSA_WITH_NULL_SHA:
607
0
        case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
608
0
        case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
609
0
        case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
610
0
        case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
611
0
            return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0 &&
612
0
                   vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
613
0
614
0
        case TLS_AES_128_GCM_SHA256:
615
0
        case TLS_AES_256_GCM_SHA384:
616
0
        case TLS_CHACHA20_POLY1305_SHA256:
617
0
            return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_3;
618
0
619
0
        default:
620
0
            return vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
621
0
    }
622
0
}
623
624
/* return pointer to ssl3CipherSuiteDef for suite, or NULL */
625
/* XXX This does a linear search.  A binary search would be better. */
626
const ssl3CipherSuiteDef *
627
ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
628
0
{
629
0
    int cipher_suite_def_len =
630
0
        sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
631
0
    int i;
632
0
633
0
    for (i = 0; i < cipher_suite_def_len; i++) {
634
0
        if (cipher_suite_defs[i].cipher_suite == suite)
635
0
            return &cipher_suite_defs[i];
636
0
    }
637
0
    PORT_Assert(PR_FALSE); /* We should never get here. */
638
0
    PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
639
0
    return NULL;
640
0
}
641
642
/* Find the cipher configuration struct associate with suite */
643
/* XXX This does a linear search.  A binary search would be better. */
644
static ssl3CipherSuiteCfg *
645
ssl_LookupCipherSuiteCfgMutable(ssl3CipherSuite suite,
646
                                ssl3CipherSuiteCfg *suites)
647
0
{
648
0
    int i;
649
0
650
0
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
651
0
        if (suites[i].cipher_suite == suite)
652
0
            return &suites[i];
653
0
    }
654
0
    /* return NULL and let the caller handle it.  */
655
0
    PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
656
0
    return NULL;
657
0
}
658
659
const static ssl3CipherSuiteCfg *
660
ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, const ssl3CipherSuiteCfg *suites)
661
0
{
662
0
    return ssl_LookupCipherSuiteCfgMutable(suite,
663
0
                                           CONST_CAST(ssl3CipherSuiteCfg, suites));
664
0
}
665
666
static PRBool
667
ssl_NamedGroupTypeEnabled(const sslSocket *ss, SSLKEAType keaType)
668
0
{
669
0
    unsigned int i;
670
0
    for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
671
0
        if (ss->namedGroupPreferences[i] &&
672
0
            ss->namedGroupPreferences[i]->keaType == keaType) {
673
0
            return PR_TRUE;
674
0
        }
675
0
    }
676
0
    return PR_FALSE;
677
0
}
678
679
static PRBool
680
ssl_KEAEnabled(const sslSocket *ss, SSLKEAType keaType)
681
0
{
682
0
    switch (keaType) {
683
0
        case ssl_kea_rsa:
684
0
            return PR_TRUE;
685
0
686
0
        case ssl_kea_dh:
687
0
        case ssl_kea_dh_psk: {
688
0
            if (ss->sec.isServer && !ss->opt.enableServerDhe) {
689
0
                return PR_FALSE;
690
0
            }
691
0
692
0
            if (ss->sec.isServer) {
693
0
                /* If the server requires named FFDHE groups, then the client
694
0
                 * must have included an FFDHE group. peerSupportsFfdheGroups
695
0
                 * is set to true in ssl_HandleSupportedGroupsXtn(). */
696
0
                if (ss->opt.requireDHENamedGroups &&
697
0
                    !ss->xtnData.peerSupportsFfdheGroups) {
698
0
                    return PR_FALSE;
699
0
                }
700
0
701
0
                /* We can use the weak DH group if all of these are true:
702
0
                 * 1. We don't require named groups.
703
0
                 * 2. The peer doesn't support named groups.
704
0
                 * 3. This isn't TLS 1.3.
705
0
                 * 4. The weak group is enabled. */
706
0
                if (!ss->opt.requireDHENamedGroups &&
707
0
                    !ss->xtnData.peerSupportsFfdheGroups &&
708
0
                    ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
709
0
                    ss->ssl3.dheWeakGroupEnabled) {
710
0
                    return PR_TRUE;
711
0
                }
712
0
            } else {
713
0
                if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
714
0
                    !ss->opt.requireDHENamedGroups) {
715
0
                    /* The client enables DHE cipher suites even if no DHE groups
716
0
                     * are enabled. Only if this isn't TLS 1.3 and named groups
717
0
                     * are not required. */
718
0
                    return PR_TRUE;
719
0
                }
720
0
            }
721
0
            return ssl_NamedGroupTypeEnabled(ss, ssl_kea_dh);
722
0
        }
723
0
724
0
        case ssl_kea_ecdh:
725
0
        case ssl_kea_ecdh_psk:
726
0
            return ssl_NamedGroupTypeEnabled(ss, ssl_kea_ecdh);
727
0
728
0
        case ssl_kea_tls13_any:
729
0
            return PR_TRUE;
730
0
731
0
        case ssl_kea_fortezza:
732
0
        default:
733
0
            PORT_Assert(0);
734
0
    }
735
0
    return PR_FALSE;
736
0
}
737
738
static PRBool
739
ssl_HasCert(const sslSocket *ss, SSLAuthType authType)
740
0
{
741
0
    PRCList *cursor;
742
0
    if (authType == ssl_auth_null || authType == ssl_auth_psk || authType == ssl_auth_tls13_any) {
743
0
        return PR_TRUE;
744
0
    }
745
0
    for (cursor = PR_NEXT_LINK(&ss->serverCerts);
746
0
         cursor != &ss->serverCerts;
747
0
         cursor = PR_NEXT_LINK(cursor)) {
748
0
        sslServerCert *cert = (sslServerCert *)cursor;
749
0
        if (!cert->serverKeyPair ||
750
0
            !cert->serverKeyPair->privKey ||
751
0
            !cert->serverCertChain ||
752
0
            !SSL_CERT_IS(cert, authType)) {
753
0
            continue;
754
0
        }
755
0
        /* When called from ssl3_config_match_init(), all the EC curves will be
756
0
         * enabled, so this will essentially do nothing (unless we implement
757
0
         * curve configuration).  However, once we have seen the
758
0
         * supported_groups extension and this is called from config_match(),
759
0
         * this will filter out certificates with an unsupported curve. */
760
0
        if ((authType == ssl_auth_ecdsa ||
761
0
             authType == ssl_auth_ecdh_ecdsa ||
762
0
             authType == ssl_auth_ecdh_rsa) &&
763
0
            !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
764
0
            continue;
765
0
        }
766
0
        return PR_TRUE;
767
0
    }
768
0
    if (authType == ssl_auth_rsa_sign) {
769
0
        return ssl_HasCert(ss, ssl_auth_rsa_pss);
770
0
    }
771
0
    return PR_FALSE;
772
0
}
773
774
/* Initialize the suite->isPresent value for config_match
775
 * Returns count of enabled ciphers supported by extant tokens,
776
 * regardless of policy or user preference.
777
 * If this returns zero, the user cannot do SSL v3.
778
 */
779
unsigned int
780
ssl3_config_match_init(sslSocket *ss)
781
0
{
782
0
    ssl3CipherSuiteCfg *suite;
783
0
    const ssl3CipherSuiteDef *cipher_def;
784
0
    SSLCipherAlgorithm cipher_alg;
785
0
    CK_MECHANISM_TYPE cipher_mech;
786
0
    SSLAuthType authType;
787
0
    SSLKEAType keaType;
788
0
    unsigned int i;
789
0
    unsigned int numPresent = 0;
790
0
    unsigned int numEnabled = 0;
791
0
792
0
    PORT_Assert(ss);
793
0
    if (!ss) {
794
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
795
0
        return 0;
796
0
    }
797
0
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
798
0
        return 0;
799
0
    }
800
0
801
0
    ssl_FilterSupportedGroups(ss);
802
0
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
803
0
        suite = &ss->cipherSuites[i];
804
0
        if (suite->enabled) {
805
0
            ++numEnabled;
806
0
            /* We need the cipher defs to see if we have a token that can handle
807
0
             * this cipher.  It isn't part of the static definition.
808
0
             */
809
0
            cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
810
0
            if (!cipher_def) {
811
0
                suite->isPresent = PR_FALSE;
812
0
                continue;
813
0
            }
814
0
            cipher_alg = ssl_GetBulkCipherDef(cipher_def)->calg;
815
0
            cipher_mech = ssl3_Alg2Mech(cipher_alg);
816
0
817
0
            /* Mark the suites that are backed by real tokens, certs and keys */
818
0
            suite->isPresent = PR_TRUE;
819
0
820
0
            authType = kea_defs[cipher_def->key_exchange_alg].authKeyType;
821
0
            if (authType != ssl_auth_null && authType != ssl_auth_tls13_any) {
822
0
                if (ss->sec.isServer && !ssl_HasCert(ss, authType)) {
823
0
                    suite->isPresent = PR_FALSE;
824
0
                }
825
0
                if (!PK11_TokenExists(auth_alg_defs[authType])) {
826
0
                    suite->isPresent = PR_FALSE;
827
0
                }
828
0
            }
829
0
830
0
            keaType = kea_defs[cipher_def->key_exchange_alg].exchKeyType;
831
0
            if (keaType != ssl_kea_null &&
832
0
                keaType != ssl_kea_tls13_any &&
833
0
                !PK11_TokenExists(kea_alg_defs[keaType])) {
834
0
                suite->isPresent = PR_FALSE;
835
0
            }
836
0
837
0
            if (cipher_alg != ssl_calg_null &&
838
0
                !PK11_TokenExists(cipher_mech)) {
839
0
                suite->isPresent = PR_FALSE;
840
0
            }
841
0
842
0
            if (suite->isPresent) {
843
0
                ++numPresent;
844
0
            }
845
0
        }
846
0
    }
847
0
    PORT_Assert(numPresent > 0 || numEnabled == 0);
848
0
    if (numPresent == 0) {
849
0
        PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
850
0
    }
851
0
    return numPresent;
852
0
}
853
854
/* Return PR_TRUE if suite is usable.  This if the suite is permitted by policy,
855
 * enabled, has a certificate (as needed), has a viable key agreement method, is
856
 * usable with the negotiated TLS version, and is otherwise usable. */
857
static PRBool
858
config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy,
859
             const SSLVersionRange *vrange, const sslSocket *ss)
860
0
{
861
0
    const ssl3CipherSuiteDef *cipher_def;
862
0
    const ssl3KEADef *kea_def;
863
0
864
0
    PORT_Assert(policy != SSL_NOT_ALLOWED);
865
0
    if (policy == SSL_NOT_ALLOWED)
866
0
        return PR_FALSE;
867
0
868
0
    if (!suite->enabled || !suite->isPresent)
869
0
        return PR_FALSE;
870
0
871
0
    if ((suite->policy == SSL_NOT_ALLOWED) ||
872
0
        (suite->policy > policy))
873
0
        return PR_FALSE;
874
0
875
0
    PORT_Assert(ss != NULL);
876
0
    cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
877
0
    PORT_Assert(cipher_def != NULL);
878
0
    kea_def = &kea_defs[cipher_def->key_exchange_alg];
879
0
    PORT_Assert(kea_def != NULL);
880
0
    if (!ssl_KEAEnabled(ss, kea_def->exchKeyType)) {
881
0
        return PR_FALSE;
882
0
    }
883
0
884
0
    if (ss->sec.isServer && !ssl_HasCert(ss, kea_def->authKeyType)) {
885
0
        return PR_FALSE;
886
0
    }
887
0
888
0
    return ssl3_CipherSuiteAllowedForVersionRange(suite->cipher_suite, vrange);
889
0
}
890
891
/* Return the number of cipher suites that are usable. */
892
/* called from ssl3_SendClientHello */
893
static unsigned int
894
count_cipher_suites(sslSocket *ss, PRUint8 policy)
895
0
{
896
0
    unsigned int i, count = 0;
897
0
898
0
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
899
0
        return 0;
900
0
    }
901
0
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
902
0
        if (config_match(&ss->cipherSuites[i], policy, &ss->vrange, ss))
903
0
            count++;
904
0
    }
905
0
    if (count == 0) {
906
0
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
907
0
    }
908
0
    return count;
909
0
}
910
911
/*
912
 * Null compression, mac and encryption functions
913
 */
914
SECStatus
915
Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen,
916
            const unsigned char *input, int inputLen)
917
0
{
918
0
    if (inputLen > maxOutputLen) {
919
0
        *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */
920
0
        PORT_SetError(SEC_ERROR_OUTPUT_LEN);
921
0
        return SECFailure;
922
0
    }
923
0
    *outputLen = inputLen;
924
0
    if (inputLen > 0 && input != output) {
925
0
        PORT_Memcpy(output, input, inputLen);
926
0
    }
927
0
    return SECSuccess;
928
0
}
929
930
/*
931
 * SSL3 Utility functions
932
 */
933
934
static void
935
ssl_SetSpecVersions(sslSocket *ss, ssl3CipherSpec *spec)
936
0
{
937
0
    spec->version = ss->version;
938
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
939
0
        tls13_SetSpecRecordVersion(ss, spec);
940
0
    } else if (IS_DTLS(ss)) {
941
0
        spec->recordVersion = dtls_TLSVersionToDTLSVersion(ss->version);
942
0
    } else {
943
0
        spec->recordVersion = ss->version;
944
0
    }
945
0
}
946
947
/* allowLargerPeerVersion controls whether the function will select the
948
 * highest enabled SSL version or fail when peerVersion is greater than the
949
 * highest enabled version.
950
 *
951
 * If allowLargerPeerVersion is true, peerVersion is the peer's highest
952
 * enabled version rather than the peer's selected version.
953
 */
954
SECStatus
955
ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
956
                      PRBool allowLargerPeerVersion)
957
0
{
958
0
    SSL3ProtocolVersion negotiated;
959
0
960
0
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
961
0
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
962
0
        return SECFailure;
963
0
    }
964
0
965
0
    if (peerVersion < ss->vrange.min ||
966
0
        (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
967
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
968
0
        return SECFailure;
969
0
    }
970
0
971
0
    negotiated = PR_MIN(peerVersion, ss->vrange.max);
972
0
    PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, negotiated));
973
0
    if (ss->firstHsDone && ss->version != negotiated) {
974
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
975
0
        return SECFailure;
976
0
    }
977
0
978
0
    ss->version = negotiated;
979
0
    return SECSuccess;
980
0
}
981
982
/* Used by the client when the server produces a version number.
983
 * This reads, validates, and normalizes the value. */
984
SECStatus
985
ssl_ClientReadVersion(sslSocket *ss, PRUint8 **b, unsigned int *len,
986
                      SSL3ProtocolVersion *version)
987
0
{
988
0
    SSL3ProtocolVersion v;
989
0
    PRUint32 temp;
990
0
    SECStatus rv;
991
0
992
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, b, len);
993
0
    if (rv != SECSuccess) {
994
0
        return SECFailure; /* alert has been sent */
995
0
    }
996
0
    v = (SSL3ProtocolVersion)temp;
997
0
998
0
    if (IS_DTLS(ss)) {
999
0
        v = dtls_DTLSVersionToTLSVersion(v);
1000
0
        /* Check for failure. */
1001
0
        if (!v || v > SSL_LIBRARY_VERSION_MAX_SUPPORTED) {
1002
0
            SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
1003
0
            return SECFailure;
1004
0
        }
1005
0
    }
1006
0
1007
0
    /* You can't negotiate TLS 1.3 this way. */
1008
0
    if (v >= SSL_LIBRARY_VERSION_TLS_1_3) {
1009
0
        SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
1010
0
        return SECFailure;
1011
0
    }
1012
0
    *version = v;
1013
0
    return SECSuccess;
1014
0
}
1015
1016
static SECStatus
1017
ssl3_GetNewRandom(SSL3Random random)
1018
0
{
1019
0
    SECStatus rv;
1020
0
1021
0
    rv = PK11_GenerateRandom(random, SSL3_RANDOM_LENGTH);
1022
0
    if (rv != SECSuccess) {
1023
0
        ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
1024
0
    }
1025
0
    return rv;
1026
0
}
1027
1028
/* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
1029
SECStatus
1030
ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash, SECKEYPrivateKey *key,
1031
                SECItem *buf)
1032
0
{
1033
0
    SECStatus rv = SECFailure;
1034
0
    PRBool doDerEncode = PR_FALSE;
1035
0
    PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
1036
0
    PRBool useRsaPss = ssl_IsRsaPssSignatureScheme(ss->ssl3.hs.signatureScheme);
1037
0
    SECItem hashItem;
1038
0
1039
0
    buf->data = NULL;
1040
0
1041
0
    switch (SECKEY_GetPrivateKeyType(key)) {
1042
0
        case rsaKey:
1043
0
            hashItem.data = hash->u.raw;
1044
0
            hashItem.len = hash->len;
1045
0
            break;
1046
0
        case dsaKey:
1047
0
            doDerEncode = isTLS;
1048
0
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1049
0
             * In that case, we use just the SHA1 part. */
1050
0
            if (hash->hashAlg == ssl_hash_none) {
1051
0
                hashItem.data = hash->u.s.sha;
1052
0
                hashItem.len = sizeof(hash->u.s.sha);
1053
0
            } else {
1054
0
                hashItem.data = hash->u.raw;
1055
0
                hashItem.len = hash->len;
1056
0
            }
1057
0
            break;
1058
0
        case ecKey:
1059
0
            doDerEncode = PR_TRUE;
1060
0
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1061
0
             * In that case, we use just the SHA1 part. */
1062
0
            if (hash->hashAlg == ssl_hash_none) {
1063
0
                hashItem.data = hash->u.s.sha;
1064
0
                hashItem.len = sizeof(hash->u.s.sha);
1065
0
            } else {
1066
0
                hashItem.data = hash->u.raw;
1067
0
                hashItem.len = hash->len;
1068
0
            }
1069
0
            break;
1070
0
        default:
1071
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
1072
0
            goto done;
1073
0
    }
1074
0
    PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
1075
0
1076
0
    if (useRsaPss || hash->hashAlg == ssl_hash_none) {
1077
0
        CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1078
0
        int signatureLen = PK11_SignatureLen(key);
1079
0
1080
0
        SECItem *params = NULL;
1081
0
        CK_RSA_PKCS_PSS_PARAMS pssParams;
1082
0
        SECItem pssParamsItem = { siBuffer,
1083
0
                                  (unsigned char *)&pssParams,
1084
0
                                  sizeof(pssParams) };
1085
0
1086
0
        if (signatureLen <= 0) {
1087
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
1088
0
            goto done;
1089
0
        }
1090
0
1091
0
        buf->len = (unsigned)signatureLen;
1092
0
        buf->data = (unsigned char *)PORT_Alloc(signatureLen);
1093
0
        if (!buf->data)
1094
0
            goto done; /* error code was set. */
1095
0
1096
0
        if (useRsaPss) {
1097
0
            pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1098
0
            pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1099
0
            pssParams.sLen = hashItem.len;
1100
0
            params = &pssParamsItem;
1101
0
            mech = CKM_RSA_PKCS_PSS;
1102
0
        }
1103
0
1104
0
        rv = PK11_SignWithMechanism(key, mech, params, buf, &hashItem);
1105
0
    } else {
1106
0
        SECOidTag hashOID = ssl3_HashTypeToOID(hash->hashAlg);
1107
0
        rv = SGN_Digest(key, hashOID, buf, &hashItem);
1108
0
    }
1109
0
    if (rv != SECSuccess) {
1110
0
        ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
1111
0
    } else if (doDerEncode) {
1112
0
        SECItem derSig = { siBuffer, NULL, 0 };
1113
0
1114
0
        /* This also works for an ECDSA signature */
1115
0
        rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
1116
0
        if (rv == SECSuccess) {
1117
0
            PORT_Free(buf->data); /* discard unencoded signature. */
1118
0
            *buf = derSig;        /* give caller encoded signature. */
1119
0
        } else if (derSig.data) {
1120
0
            PORT_Free(derSig.data);
1121
0
        }
1122
0
    }
1123
0
1124
0
    if (ss->sec.isServer) {
1125
0
        ss->sec.signatureScheme = ss->ssl3.hs.signatureScheme;
1126
0
        ss->sec.authType =
1127
0
            ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme);
1128
0
    }
1129
0
    PRINT_BUF(60, (NULL, "signed hashes", (unsigned char *)buf->data, buf->len));
1130
0
done:
1131
0
    if (rv != SECSuccess && buf->data) {
1132
0
        PORT_Free(buf->data);
1133
0
        buf->data = NULL;
1134
0
    }
1135
0
    return rv;
1136
0
}
1137
1138
/* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
1139
SECStatus
1140
ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme, SSL3Hashes *hash,
1141
                        SECItem *buf)
1142
0
{
1143
0
    SECKEYPublicKey *key;
1144
0
    SECItem *signature = NULL;
1145
0
    SECStatus rv = SECFailure;
1146
0
    SECItem hashItem;
1147
0
    SECOidTag encAlg;
1148
0
    SECOidTag hashAlg;
1149
0
    void *pwArg = ss->pkcs11PinArg;
1150
0
    PRBool isRsaPssScheme = ssl_IsRsaPssSignatureScheme(scheme);
1151
0
1152
0
    PRINT_BUF(60, (NULL, "check signed hashes",
1153
0
                   buf->data, buf->len));
1154
0
1155
0
    key = CERT_ExtractPublicKey(ss->sec.peerCert);
1156
0
    if (key == NULL) {
1157
0
        ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
1158
0
        return SECFailure;
1159
0
    }
1160
0
1161
0
    hashAlg = ssl3_HashTypeToOID(hash->hashAlg);
1162
0
    switch (SECKEY_GetPublicKeyType(key)) {
1163
0
        case rsaKey:
1164
0
            encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
1165
0
            hashItem.data = hash->u.raw;
1166
0
            hashItem.len = hash->len;
1167
0
            if (scheme == ssl_sig_none) {
1168
0
                scheme = ssl_sig_rsa_pkcs1_sha1md5;
1169
0
            }
1170
0
            break;
1171
0
        case dsaKey:
1172
0
            encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
1173
0
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1174
0
             * In that case, we use just the SHA1 part. */
1175
0
            if (hash->hashAlg == ssl_hash_none) {
1176
0
                hashItem.data = hash->u.s.sha;
1177
0
                hashItem.len = sizeof(hash->u.s.sha);
1178
0
            } else {
1179
0
                hashItem.data = hash->u.raw;
1180
0
                hashItem.len = hash->len;
1181
0
            }
1182
0
            /* Allow DER encoded DSA signatures in SSL 3.0 */
1183
0
            if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0 ||
1184
0
                buf->len != SECKEY_SignatureLen(key)) {
1185
0
                signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key));
1186
0
                if (!signature) {
1187
0
                    PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1188
0
                    goto loser;
1189
0
                }
1190
0
                buf = signature;
1191
0
            }
1192
0
            if (scheme == ssl_sig_none) {
1193
0
                scheme = ssl_sig_dsa_sha1;
1194
0
            }
1195
0
            break;
1196
0
1197
0
        case ecKey:
1198
0
            encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
1199
0
            /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1200
0
             * In that case, we use just the SHA1 part.
1201
0
             * ECDSA signatures always encode the integers r and s using ASN.1
1202
0
             * (unlike DSA where ASN.1 encoding is used with TLS but not with
1203
0
             * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
1204
0
             */
1205
0
            if (hash->hashAlg == ssl_hash_none) {
1206
0
                hashAlg = SEC_OID_SHA1;
1207
0
                hashItem.data = hash->u.s.sha;
1208
0
                hashItem.len = sizeof(hash->u.s.sha);
1209
0
            } else {
1210
0
                hashItem.data = hash->u.raw;
1211
0
                hashItem.len = hash->len;
1212
0
            }
1213
0
            if (scheme == ssl_sig_none) {
1214
0
                scheme = ssl_sig_ecdsa_sha1;
1215
0
            }
1216
0
            break;
1217
0
1218
0
        default:
1219
0
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
1220
0
            goto loser;
1221
0
    }
1222
0
1223
0
    PRINT_BUF(60, (NULL, "hash(es) to be verified",
1224
0
                   hashItem.data, hashItem.len));
1225
0
1226
0
    if (isRsaPssScheme ||
1227
0
        hashAlg == SEC_OID_UNKNOWN ||
1228
0
        SECKEY_GetPublicKeyType(key) == dsaKey) {
1229
0
        /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1230
0
         * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1231
0
         * above always removes the DER encoding of DSA signatures when
1232
0
         * present. Thus DSA signatures are always verified with PK11_Verify.
1233
0
         */
1234
0
        CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1235
0
1236
0
        SECItem *params = NULL;
1237
0
        CK_RSA_PKCS_PSS_PARAMS pssParams;
1238
0
        SECItem pssParamsItem = { siBuffer,
1239
0
                                  (unsigned char *)&pssParams,
1240
0
                                  sizeof(pssParams) };
1241
0
1242
0
        if (isRsaPssScheme) {
1243
0
            pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1244
0
            pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1245
0
            pssParams.sLen = hashItem.len;
1246
0
            params = &pssParamsItem;
1247
0
            mech = CKM_RSA_PKCS_PSS;
1248
0
        }
1249
0
1250
0
        rv = PK11_VerifyWithMechanism(key, mech, params, buf, &hashItem, pwArg);
1251
0
    } else {
1252
0
        rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
1253
0
                                    pwArg);
1254
0
    }
1255
0
    if (signature) {
1256
0
        SECITEM_FreeItem(signature, PR_TRUE);
1257
0
    }
1258
0
    if (rv != SECSuccess) {
1259
0
        ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1260
0
    }
1261
0
    if (!ss->sec.isServer) {
1262
0
        ss->sec.signatureScheme = scheme;
1263
0
        ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
1264
0
    }
1265
0
1266
0
loser:
1267
0
    SECKEY_DestroyPublicKey(key);
1268
#ifdef UNSAFE_FUZZER_MODE
1269
    rv = SECSuccess;
1270
    PORT_SetError(0);
1271
#endif
1272
    return rv;
1273
0
}
1274
1275
/* Caller must set hiLevel error code. */
1276
/* Called from ssl3_ComputeDHKeyHash
1277
 * which are called from ssl3_HandleServerKeyExchange.
1278
 *
1279
 * hashAlg: ssl_hash_none indicates the pre-1.2, MD5/SHA1 combination hash.
1280
 */
1281
SECStatus
1282
ssl3_ComputeCommonKeyHash(SSLHashType hashAlg,
1283
                          PRUint8 *hashBuf, unsigned int bufLen,
1284
                          SSL3Hashes *hashes)
1285
0
{
1286
0
    SECStatus rv;
1287
0
    SECOidTag hashOID;
1288
0
1289
0
    if (hashAlg == ssl_hash_none) {
1290
0
        rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen);
1291
0
        if (rv != SECSuccess) {
1292
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
1293
0
            return rv;
1294
0
        }
1295
0
        rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen);
1296
0
        if (rv != SECSuccess) {
1297
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
1298
0
            return rv;
1299
0
        }
1300
0
        hashes->len = MD5_LENGTH + SHA1_LENGTH;
1301
0
    } else {
1302
0
        hashOID = ssl3_HashTypeToOID(hashAlg);
1303
0
        hashes->len = HASH_ResultLenByOidTag(hashOID);
1304
0
        if (hashes->len == 0 || hashes->len > sizeof(hashes->u.raw)) {
1305
0
            ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1306
0
            return SECFailure;
1307
0
        }
1308
0
        rv = PK11_HashBuf(hashOID, hashes->u.raw, hashBuf, bufLen);
1309
0
        if (rv != SECSuccess) {
1310
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
1311
0
            return rv;
1312
0
        }
1313
0
    }
1314
0
    hashes->hashAlg = hashAlg;
1315
0
    return SECSuccess;
1316
0
}
1317
1318
/* Caller must set hiLevel error code. */
1319
/* Called from ssl3_HandleServerKeyExchange. */
1320
static SECStatus
1321
ssl3_ComputeDHKeyHash(sslSocket *ss, SSLHashType hashAlg, SSL3Hashes *hashes,
1322
                      SECItem dh_p, SECItem dh_g, SECItem dh_Ys, PRBool padY)
1323
0
{
1324
0
    sslBuffer buf = SSL_BUFFER_EMPTY;
1325
0
    SECStatus rv;
1326
0
    unsigned int yLen;
1327
0
    unsigned int i;
1328
0
1329
0
    PORT_Assert(dh_p.data);
1330
0
    PORT_Assert(dh_g.data);
1331
0
    PORT_Assert(dh_Ys.data);
1332
0
1333
0
    rv = sslBuffer_Append(&buf, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
1334
0
    if (rv != SECSuccess) {
1335
0
        goto loser;
1336
0
    }
1337
0
    rv = sslBuffer_Append(&buf, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
1338
0
    if (rv != SECSuccess) {
1339
0
        goto loser;
1340
0
    }
1341
0
    /* p */
1342
0
    rv = sslBuffer_AppendVariable(&buf, dh_p.data, dh_p.len, 2);
1343
0
    if (rv != SECSuccess) {
1344
0
        goto loser;
1345
0
    }
1346
0
    /* g */
1347
0
    rv = sslBuffer_AppendVariable(&buf, dh_g.data, dh_g.len, 2);
1348
0
    if (rv != SECSuccess) {
1349
0
        goto loser;
1350
0
    }
1351
0
    /* y - complicated by padding */
1352
0
    yLen = padY ? dh_p.len : dh_Ys.len;
1353
0
    rv = sslBuffer_AppendNumber(&buf, yLen, 2);
1354
0
    if (rv != SECSuccess) {
1355
0
        goto loser;
1356
0
    }
1357
0
    /* If we're padding Y, dh_Ys can't be longer than dh_p. */
1358
0
    PORT_Assert(!padY || dh_p.len >= dh_Ys.len);
1359
0
    for (i = dh_Ys.len; i < yLen; ++i) {
1360
0
        rv = sslBuffer_AppendNumber(&buf, 0, 1);
1361
0
        if (rv != SECSuccess) {
1362
0
            goto loser;
1363
0
        }
1364
0
    }
1365
0
    rv = sslBuffer_Append(&buf, dh_Ys.data, dh_Ys.len);
1366
0
    if (rv != SECSuccess) {
1367
0
        goto loser;
1368
0
    }
1369
0
1370
0
    rv = ssl3_ComputeCommonKeyHash(hashAlg, SSL_BUFFER_BASE(&buf),
1371
0
                                   SSL_BUFFER_LEN(&buf), hashes);
1372
0
    if (rv != SECSuccess) {
1373
0
        goto loser;
1374
0
    }
1375
0
1376
0
    PRINT_BUF(95, (NULL, "DHkey hash: ", SSL_BUFFER_BASE(&buf),
1377
0
                   SSL_BUFFER_LEN(&buf)));
1378
0
    if (hashAlg == ssl_hash_none) {
1379
0
        PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",
1380
0
                       hashes->u.s.md5, MD5_LENGTH));
1381
0
        PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",
1382
0
                       hashes->u.s.sha, SHA1_LENGTH));
1383
0
    } else {
1384
0
        PRINT_BUF(95, (NULL, "DHkey hash: result",
1385
0
                       hashes->u.raw, hashes->len));
1386
0
    }
1387
0
1388
0
    sslBuffer_Clear(&buf);
1389
0
    return SECSuccess;
1390
0
1391
0
loser:
1392
0
    sslBuffer_Clear(&buf);
1393
0
    return SECFailure;
1394
0
}
1395
1396
static SECStatus
1397
ssl3_SetupPendingCipherSpec(sslSocket *ss, CipherSpecDirection direction,
1398
                            const ssl3CipherSuiteDef *suiteDef,
1399
                            ssl3CipherSpec **specp)
1400
0
{
1401
0
    ssl3CipherSpec *spec;
1402
0
    const ssl3CipherSpec *prev;
1403
0
1404
0
    prev = (direction == CipherSpecWrite) ? ss->ssl3.cwSpec : ss->ssl3.crSpec;
1405
0
    if (prev->epoch == PR_UINT16_MAX) {
1406
0
        PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
1407
0
        return SECFailure;
1408
0
    }
1409
0
1410
0
    spec = ssl_CreateCipherSpec(ss, direction);
1411
0
    if (!spec) {
1412
0
        return SECFailure;
1413
0
    }
1414
0
1415
0
    spec->cipherDef = ssl_GetBulkCipherDef(suiteDef);
1416
0
    spec->macDef = ssl_GetMacDef(ss, suiteDef);
1417
0
1418
0
    spec->epoch = prev->epoch + 1;
1419
0
    spec->nextSeqNum = 0;
1420
0
    if (IS_DTLS(ss) && direction == CipherSpecRead) {
1421
0
        dtls_InitRecvdRecords(&spec->recvdRecords);
1422
0
    }
1423
0
    ssl_SetSpecVersions(ss, spec);
1424
0
1425
0
    ssl_SaveCipherSpec(ss, spec);
1426
0
    *specp = spec;
1427
0
    return SECSuccess;
1428
0
}
1429
1430
/* Fill in the pending cipher spec with info from the selected ciphersuite.
1431
** This is as much initialization as we can do without having key material.
1432
** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1433
** Caller must hold the ssl3 handshake lock.
1434
** Acquires & releases SpecWriteLock.
1435
*/
1436
SECStatus
1437
ssl3_SetupBothPendingCipherSpecs(sslSocket *ss)
1438
0
{
1439
0
    ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
1440
0
    SSL3KeyExchangeAlgorithm kea;
1441
0
    const ssl3CipherSuiteDef *suiteDef;
1442
0
    SECStatus rv;
1443
0
1444
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1445
0
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
1446
0
1447
0
    ssl_GetSpecWriteLock(ss); /*******************************/
1448
0
1449
0
    /* This hack provides maximal interoperability with SSL 3 servers. */
1450
0
    if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
1451
0
        /* SSL records are not being MACed. */
1452
0
        ss->ssl3.cwSpec->version = ss->version;
1453
0
    }
1454
0
1455
0
    SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1456
0
                SSL_GETPID(), ss->fd, suite));
1457
0
1458
0
    suiteDef = ssl_LookupCipherSuiteDef(suite);
1459
0
    if (suiteDef == NULL) {
1460
0
        goto loser;
1461
0
    }
1462
0
1463
0
    if (IS_DTLS(ss)) {
1464
0
        /* Double-check that we did not pick an RC4 suite */
1465
0
        PORT_Assert(suiteDef->bulk_cipher_alg != cipher_rc4);
1466
0
    }
1467
0
1468
0
    ss->ssl3.hs.suite_def = suiteDef;
1469
0
1470
0
    kea = suiteDef->key_exchange_alg;
1471
0
    ss->ssl3.hs.kea_def = &kea_defs[kea];
1472
0
    PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
1473
0
1474
0
    rv = ssl3_SetupPendingCipherSpec(ss, CipherSpecRead, suiteDef,
1475
0
                                     &ss->ssl3.prSpec);
1476
0
    if (rv != SECSuccess) {
1477
0
        goto loser;
1478
0
    }
1479
0
    rv = ssl3_SetupPendingCipherSpec(ss, CipherSpecWrite, suiteDef,
1480
0
                                     &ss->ssl3.pwSpec);
1481
0
    if (rv != SECSuccess) {
1482
0
        goto loser;
1483
0
    }
1484
0
1485
0
    if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) {
1486
0
        ss->ssl3.prSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,
1487
0
                                                  ss->opt.recordSizeLimit);
1488
0
        ss->ssl3.pwSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,
1489
0
                                                  ss->xtnData.recordSizeLimit);
1490
0
    }
1491
0
1492
0
    ssl_ReleaseSpecWriteLock(ss); /*******************************/
1493
0
    return SECSuccess;
1494
0
1495
0
loser:
1496
0
    ssl_ReleaseSpecWriteLock(ss);
1497
0
    return SECFailure;
1498
0
}
1499
1500
/* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data which
1501
 * is included in the MAC or AEAD additional data) to |buf|. See
1502
 * https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the definition of the
1503
 * AEAD additional data.
1504
 *
1505
 * TLS pseudo-header includes the record's version field, SSL's doesn't. Which
1506
 * pseudo-header definition to use should be decided based on the version of
1507
 * the protocol that was negotiated when the cipher spec became current, NOT
1508
 * based on the version value in the record itself, and the decision is passed
1509
 * to this function as the |includesVersion| argument. But, the |version|
1510
 * argument should be the record's version value.
1511
 */
1512
static SECStatus
1513
ssl3_BuildRecordPseudoHeader(DTLSEpoch epoch,
1514
                             sslSequenceNumber seqNum,
1515
                             SSLContentType ct,
1516
                             PRBool includesVersion,
1517
                             SSL3ProtocolVersion version,
1518
                             PRBool isDTLS,
1519
                             int length,
1520
                             sslBuffer *buf)
1521
0
{
1522
0
    SECStatus rv;
1523
0
    if (isDTLS) {
1524
0
        rv = sslBuffer_AppendNumber(buf, epoch, 2);
1525
0
        if (rv != SECSuccess) {
1526
0
            return SECFailure;
1527
0
        }
1528
0
        rv = sslBuffer_AppendNumber(buf, seqNum, 6);
1529
0
    } else {
1530
0
        rv = sslBuffer_AppendNumber(buf, seqNum, 8);
1531
0
    }
1532
0
    if (rv != SECSuccess) {
1533
0
        return SECFailure;
1534
0
    }
1535
0
    rv = sslBuffer_AppendNumber(buf, ct, 1);
1536
0
    if (rv != SECSuccess) {
1537
0
        return SECFailure;
1538
0
    }
1539
0
1540
0
    /* SSL3 MAC doesn't include the record's version field. */
1541
0
    if (includesVersion) {
1542
0
        /* TLS MAC and AEAD additional data include version. */
1543
0
        rv = sslBuffer_AppendNumber(buf, version, 2);
1544
0
        if (rv != SECSuccess) {
1545
0
            return SECFailure;
1546
0
        }
1547
0
    }
1548
0
    rv = sslBuffer_AppendNumber(buf, length, 2);
1549
0
    if (rv != SECSuccess) {
1550
0
        return SECFailure;
1551
0
    }
1552
0
1553
0
    return SECSuccess;
1554
0
}
1555
1556
static SECStatus
1557
ssl3_AESGCM(ssl3KeyMaterial *keys,
1558
            PRBool doDecrypt,
1559
            unsigned char *out,
1560
            int *outlen,
1561
            int maxout,
1562
            const unsigned char *in,
1563
            int inlen,
1564
            const unsigned char *additionalData,
1565
            int additionalDataLen)
1566
0
{
1567
0
    SECItem param;
1568
0
    SECStatus rv = SECFailure;
1569
0
    unsigned char nonce[12];
1570
0
    unsigned int uOutLen;
1571
0
    CK_GCM_PARAMS gcmParams;
1572
0
1573
0
    const int tagSize = 16;
1574
0
    const int explicitNonceLen = 8;
1575
0
1576
0
    /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the
1577
0
     * nonce is formed. */
1578
0
    memcpy(nonce, keys->iv, 4);
1579
0
    if (doDecrypt) {
1580
0
        memcpy(nonce + 4, in, explicitNonceLen);
1581
0
        in += explicitNonceLen;
1582
0
        inlen -= explicitNonceLen;
1583
0
        *outlen = 0;
1584
0
    } else {
1585
0
        if (maxout < explicitNonceLen) {
1586
0
            PORT_SetError(SEC_ERROR_INPUT_LEN);
1587
0
            return SECFailure;
1588
0
        }
1589
0
        /* Use the 64-bit sequence number as the explicit nonce. */
1590
0
        memcpy(nonce + 4, additionalData, explicitNonceLen);
1591
0
        memcpy(out, additionalData, explicitNonceLen);
1592
0
        out += explicitNonceLen;
1593
0
        maxout -= explicitNonceLen;
1594
0
        *outlen = explicitNonceLen;
1595
0
    }
1596
0
1597
0
    param.type = siBuffer;
1598
0
    param.data = (unsigned char *)&gcmParams;
1599
0
    param.len = sizeof(gcmParams);
1600
0
    gcmParams.pIv = nonce;
1601
0
    gcmParams.ulIvLen = sizeof(nonce);
1602
0
    gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */
1603
0
    gcmParams.ulAADLen = additionalDataLen;
1604
0
    gcmParams.ulTagBits = tagSize * 8;
1605
0
1606
0
    if (doDecrypt) {
1607
0
        rv = PK11_Decrypt(keys->key, CKM_AES_GCM, &param, out, &uOutLen,
1608
0
                          maxout, in, inlen);
1609
0
    } else {
1610
0
        rv = PK11_Encrypt(keys->key, CKM_AES_GCM, &param, out, &uOutLen,
1611
0
                          maxout, in, inlen);
1612
0
    }
1613
0
    *outlen += (int)uOutLen;
1614
0
1615
0
    return rv;
1616
0
}
1617
1618
static SECStatus
1619
ssl3_ChaCha20Poly1305(ssl3KeyMaterial *keys, PRBool doDecrypt,
1620
                      unsigned char *out, int *outlen, int maxout,
1621
                      const unsigned char *in, int inlen,
1622
                      const unsigned char *additionalData,
1623
                      int additionalDataLen)
1624
0
{
1625
0
    size_t i;
1626
0
    SECItem param;
1627
0
    SECStatus rv = SECFailure;
1628
0
    unsigned int uOutLen;
1629
0
    unsigned char nonce[12];
1630
0
    CK_NSS_AEAD_PARAMS aeadParams;
1631
0
1632
0
    const int tagSize = 16;
1633
0
1634
0
    /* See
1635
0
     * https://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305-04#section-2
1636
0
     * for details of how the nonce is formed. */
1637
0
    PORT_Memcpy(nonce, keys->iv, 12);
1638
0
1639
0
    /* XOR the last 8 bytes of the IV with the sequence number. */
1640
0
    PORT_Assert(additionalDataLen >= 8);
1641
0
    for (i = 0; i < 8; ++i) {
1642
0
        nonce[4 + i] ^= additionalData[i];
1643
0
    }
1644
0
1645
0
    param.type = siBuffer;
1646
0
    param.len = sizeof(aeadParams);
1647
0
    param.data = (unsigned char *)&aeadParams;
1648
0
    memset(&aeadParams, 0, sizeof(aeadParams));
1649
0
    aeadParams.pNonce = nonce;
1650
0
    aeadParams.ulNonceLen = sizeof(nonce);
1651
0
    aeadParams.pAAD = (unsigned char *)additionalData;
1652
0
    aeadParams.ulAADLen = additionalDataLen;
1653
0
    aeadParams.ulTagLen = tagSize;
1654
0
1655
0
    if (doDecrypt) {
1656
0
        rv = PK11_Decrypt(keys->key, CKM_NSS_CHACHA20_POLY1305, &param,
1657
0
                          out, &uOutLen, maxout, in, inlen);
1658
0
    } else {
1659
0
        rv = PK11_Encrypt(keys->key, CKM_NSS_CHACHA20_POLY1305, &param,
1660
0
                          out, &uOutLen, maxout, in, inlen);
1661
0
    }
1662
0
    *outlen = (int)uOutLen;
1663
0
1664
0
    return rv;
1665
0
}
1666
1667
/* Initialize encryption and MAC contexts for pending spec.
1668
 * Master Secret already is derived.
1669
 * Caller holds Spec write lock.
1670
 */
1671
static SECStatus
1672
ssl3_InitPendingContexts(sslSocket *ss, ssl3CipherSpec *spec)
1673
0
{
1674
0
    CK_MECHANISM_TYPE encMechanism;
1675
0
    CK_ATTRIBUTE_TYPE encMode;
1676
0
    SECItem macParam;
1677
0
    CK_ULONG macLength;
1678
0
    SECItem iv;
1679
0
    SSLCipherAlgorithm calg;
1680
0
1681
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1682
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1683
0
1684
0
    macLength = spec->macDef->mac_size;
1685
0
    calg = spec->cipherDef->calg;
1686
0
    PORT_Assert(alg2Mech[calg].calg == calg);
1687
0
1688
0
    if (spec->cipherDef->type == type_aead) {
1689
0
        spec->cipher = NULL;
1690
0
        spec->cipherContext = NULL;
1691
0
        switch (calg) {
1692
0
            case ssl_calg_aes_gcm:
1693
0
                spec->aead = ssl3_AESGCM;
1694
0
                break;
1695
0
            case ssl_calg_chacha20:
1696
0
                spec->aead = ssl3_ChaCha20Poly1305;
1697
0
                break;
1698
0
            default:
1699
0
                PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1700
0
                return SECFailure;
1701
0
        }
1702
0
        return SECSuccess;
1703
0
    }
1704
0
1705
0
    /*
1706
0
    ** Now setup the MAC contexts,
1707
0
    **   crypto contexts are setup below.
1708
0
    */
1709
0
    macParam.data = (unsigned char *)&macLength;
1710
0
    macParam.len = sizeof(macLength);
1711
0
    macParam.type = siBuffer;
1712
0
1713
0
    spec->keyMaterial.macContext = PK11_CreateContextBySymKey(
1714
0
        spec->macDef->mmech, CKA_SIGN, spec->keyMaterial.macKey, &macParam);
1715
0
    if (!spec->keyMaterial.macContext) {
1716
0
        ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1717
0
        return SECFailure;
1718
0
    }
1719
0
1720
0
    /*
1721
0
    ** Now setup the crypto contexts.
1722
0
    */
1723
0
    if (calg == ssl_calg_null) {
1724
0
        spec->cipher = Null_Cipher;
1725
0
        return SECSuccess;
1726
0
    }
1727
0
1728
0
    spec->cipher = (SSLCipher)PK11_CipherOp;
1729
0
    encMechanism = ssl3_Alg2Mech(calg);
1730
0
    encMode = (spec->direction == CipherSpecWrite) ? CKA_ENCRYPT : CKA_DECRYPT;
1731
0
1732
0
    /*
1733
0
     * build the context
1734
0
     */
1735
0
    iv.data = spec->keyMaterial.iv;
1736
0
    iv.len = spec->cipherDef->iv_size;
1737
0
    spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode,
1738
0
                                                     spec->keyMaterial.key,
1739
0
                                                     &iv);
1740
0
    if (!spec->cipherContext) {
1741
0
        ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1742
0
        return SECFailure;
1743
0
    }
1744
0
1745
0
    return SECSuccess;
1746
0
}
1747
1748
/* Complete the initialization of all keys, ciphers, MACs and their contexts
1749
 * for the pending Cipher Spec.
1750
 * Called from: ssl3_SendClientKeyExchange  (for Full handshake)
1751
 *              ssl3_HandleRSAClientKeyExchange (for Full handshake)
1752
 *              ssl3_HandleServerHello      (for session restart)
1753
 *              ssl3_HandleClientHello      (for session restart)
1754
 * Sets error code, but caller probably should override to disambiguate.
1755
 *
1756
 * If |secret| is a master secret from a previous connection is reused, |derive|
1757
 * is PR_FALSE.  If the secret is a pre-master secret, then |derive| is PR_TRUE
1758
 * and the master secret is derived from |secret|.
1759
 */
1760
SECStatus
1761
ssl3_InitPendingCipherSpecs(sslSocket *ss, PK11SymKey *secret, PRBool derive)
1762
0
{
1763
0
    PK11SymKey *masterSecret;
1764
0
    ssl3CipherSpec *pwSpec;
1765
0
    ssl3CipherSpec *prSpec;
1766
0
    SECStatus rv;
1767
0
1768
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1769
0
    PORT_Assert(secret);
1770
0
1771
0
    ssl_GetSpecWriteLock(ss); /**************************************/
1772
0
1773
0
    PORT_Assert(ss->ssl3.pwSpec);
1774
0
    PORT_Assert(ss->ssl3.cwSpec->epoch == ss->ssl3.crSpec->epoch);
1775
0
    prSpec = ss->ssl3.prSpec;
1776
0
    pwSpec = ss->ssl3.pwSpec;
1777
0
1778
0
    if (ss->ssl3.cwSpec->epoch == PR_UINT16_MAX) {
1779
0
        /* The problem here is that we have rehandshaked too many
1780
0
         * times (you are not allowed to wrap the epoch). The
1781
0
         * spec says you should be discarding the connection
1782
0
         * and start over, so not much we can do here. */
1783
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1784
0
        goto loser;
1785
0
    }
1786
0
1787
0
    if (derive) {
1788
0
        rv = ssl3_ComputeMasterSecret(ss, secret, &masterSecret);
1789
0
        if (rv != SECSuccess) {
1790
0
            goto loser;
1791
0
        }
1792
0
    } else {
1793
0
        masterSecret = secret;
1794
0
    }
1795
0
1796
0
    PORT_Assert(masterSecret);
1797
0
    rv = ssl3_DeriveConnectionKeys(ss, masterSecret);
1798
0
    if (rv != SECSuccess) {
1799
0
        if (derive) {
1800
0
            /* masterSecret was created here. */
1801
0
            PK11_FreeSymKey(masterSecret);
1802
0
        }
1803
0
        goto loser;
1804
0
    }
1805
0
1806
0
    /* Both cipher specs maintain a reference to the master secret, since each
1807
0
     * is managed and freed independently. */
1808
0
    prSpec->masterSecret = masterSecret;
1809
0
    pwSpec->masterSecret = PK11_ReferenceSymKey(masterSecret);
1810
0
    rv = ssl3_InitPendingContexts(ss, ss->ssl3.prSpec);
1811
0
    if (rv != SECSuccess) {
1812
0
        goto loser;
1813
0
    }
1814
0
1815
0
    rv = ssl3_InitPendingContexts(ss, ss->ssl3.pwSpec);
1816
0
    if (rv != SECSuccess) {
1817
0
        goto loser;
1818
0
    }
1819
0
1820
0
    ssl_ReleaseSpecWriteLock(ss); /******************************/
1821
0
    return SECSuccess;
1822
0
1823
0
loser:
1824
0
    ssl_ReleaseSpecWriteLock(ss); /******************************/
1825
0
    ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
1826
0
    return SECFailure;
1827
0
}
1828
1829
/*
1830
 * 60 bytes is 3 times the maximum length MAC size that is supported.
1831
 */
1832
static const unsigned char mac_pad_1[60] = {
1833
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1834
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1835
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1836
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1837
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1838
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1839
    0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1840
    0x36, 0x36, 0x36, 0x36
1841
};
1842
static const unsigned char mac_pad_2[60] = {
1843
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1844
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1845
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1846
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1847
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1848
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1849
    0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1850
    0x5c, 0x5c, 0x5c, 0x5c
1851
};
1852
1853
/* Called from: ssl3_SendRecord()
1854
** Caller must already hold the SpecReadLock. (wish we could assert that!)
1855
*/
1856
static SECStatus
1857
ssl3_ComputeRecordMAC(
1858
    ssl3CipherSpec *spec,
1859
    const unsigned char *header,
1860
    unsigned int headerLen,
1861
    const PRUint8 *input,
1862
    int inputLen,
1863
    unsigned char *outbuf,
1864
    unsigned int *outLen)
1865
0
{
1866
0
    PK11Context *context;
1867
0
    int macSize = spec->macDef->mac_size;
1868
0
    SECStatus rv;
1869
0
1870
0
    PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen));
1871
0
    PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLen));
1872
0
1873
0
    if (spec->macDef->mac == ssl_mac_null) {
1874
0
        *outLen = 0;
1875
0
        return SECSuccess;
1876
0
    }
1877
0
1878
0
    context = spec->keyMaterial.macContext;
1879
0
    rv = PK11_DigestBegin(context);
1880
0
    rv |= PK11_DigestOp(context, header, headerLen);
1881
0
    rv |= PK11_DigestOp(context, input, inputLen);
1882
0
    rv |= PK11_DigestFinal(context, outbuf, outLen, macSize);
1883
0
    PORT_Assert(rv != SECSuccess || *outLen == (unsigned)macSize);
1884
0
1885
0
    PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLen));
1886
0
1887
0
    if (rv != SECSuccess) {
1888
0
        rv = SECFailure;
1889
0
        ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
1890
0
    }
1891
0
    return rv;
1892
0
}
1893
1894
/* Called from: ssl3_HandleRecord()
1895
 * Caller must already hold the SpecReadLock. (wish we could assert that!)
1896
 *
1897
 * On entry:
1898
 *   originalLen >= inputLen >= MAC size
1899
*/
1900
static SECStatus
1901
ssl3_ComputeRecordMACConstantTime(
1902
    ssl3CipherSpec *spec,
1903
    const unsigned char *header,
1904
    unsigned int headerLen,
1905
    const PRUint8 *input,
1906
    int inputLen,
1907
    int originalLen,
1908
    unsigned char *outbuf,
1909
    unsigned int *outLen)
1910
0
{
1911
0
    CK_MECHANISM_TYPE macType;
1912
0
    CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
1913
0
    SECItem param, inputItem, outputItem;
1914
0
    int macSize = spec->macDef->mac_size;
1915
0
    SECStatus rv;
1916
0
1917
0
    PORT_Assert(inputLen >= spec->macDef->mac_size);
1918
0
    PORT_Assert(originalLen >= inputLen);
1919
0
1920
0
    if (spec->macDef->mac == ssl_mac_null) {
1921
0
        *outLen = 0;
1922
0
        return SECSuccess;
1923
0
    }
1924
0
1925
0
    macType = CKM_NSS_HMAC_CONSTANT_TIME;
1926
0
    if (spec->version == SSL_LIBRARY_VERSION_3_0) {
1927
0
        macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME;
1928
0
    }
1929
0
1930
0
    params.macAlg = spec->macDef->mmech;
1931
0
    params.ulBodyTotalLen = originalLen;
1932
0
    params.pHeader = (unsigned char *)header; /* const cast */
1933
0
    params.ulHeaderLen = headerLen;
1934
0
1935
0
    param.data = (unsigned char *)&params;
1936
0
    param.len = sizeof(params);
1937
0
    param.type = 0;
1938
0
1939
0
    inputItem.data = (unsigned char *)input;
1940
0
    inputItem.len = inputLen;
1941
0
    inputItem.type = 0;
1942
0
1943
0
    outputItem.data = outbuf;
1944
0
    outputItem.len = *outLen;
1945
0
    outputItem.type = 0;
1946
0
1947
0
    rv = PK11_SignWithSymKey(spec->keyMaterial.macKey, macType, &param,
1948
0
                             &outputItem, &inputItem);
1949
0
    if (rv != SECSuccess) {
1950
0
        if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) {
1951
0
            /* ssl3_ComputeRecordMAC() expects the MAC to have been removed
1952
0
             * from the input length already. */
1953
0
            return ssl3_ComputeRecordMAC(spec, header, headerLen,
1954
0
                                         input, inputLen - macSize,
1955
0
                                         outbuf, outLen);
1956
0
        }
1957
0
1958
0
        *outLen = 0;
1959
0
        rv = SECFailure;
1960
0
        ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
1961
0
        return rv;
1962
0
    }
1963
0
1964
0
    PORT_Assert(outputItem.len == (unsigned)macSize);
1965
0
    *outLen = outputItem.len;
1966
0
1967
0
    return rv;
1968
0
}
1969
1970
static PRBool
1971
ssl3_ClientAuthTokenPresent(sslSessionID *sid)
1972
0
{
1973
0
    PK11SlotInfo *slot = NULL;
1974
0
    PRBool isPresent = PR_TRUE;
1975
0
1976
0
    /* we only care if we are doing client auth */
1977
0
    if (!sid || !sid->u.ssl3.clAuthValid) {
1978
0
        return PR_TRUE;
1979
0
    }
1980
0
1981
0
    /* get the slot */
1982
0
    slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
1983
0
                             sid->u.ssl3.clAuthSlotID);
1984
0
    if (slot == NULL ||
1985
0
        !PK11_IsPresent(slot) ||
1986
0
        sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) ||
1987
0
        sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) ||
1988
0
        sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) ||
1989
0
        (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
1990
0
        isPresent = PR_FALSE;
1991
0
    }
1992
0
    if (slot) {
1993
0
        PK11_FreeSlot(slot);
1994
0
    }
1995
0
    return isPresent;
1996
0
}
1997
1998
/* Caller must hold the spec read lock. */
1999
SECStatus
2000
ssl3_MACEncryptRecord(ssl3CipherSpec *cwSpec,
2001
                      PRBool isServer,
2002
                      PRBool isDTLS,
2003
                      SSLContentType ct,
2004
                      const PRUint8 *pIn,
2005
                      PRUint32 contentLen,
2006
                      sslBuffer *wrBuf)
2007
0
{
2008
0
    SECStatus rv;
2009
0
    PRUint32 macLen = 0;
2010
0
    PRUint32 fragLen;
2011
0
    PRUint32 p1Len, p2Len, oddLen = 0;
2012
0
    unsigned int ivLen = 0;
2013
0
    unsigned char pseudoHeaderBuf[13];
2014
0
    sslBuffer pseudoHeader = SSL_BUFFER(pseudoHeaderBuf);
2015
0
    int len;
2016
0
2017
0
    if (cwSpec->cipherDef->type == type_block &&
2018
0
        cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
2019
0
        /* Prepend the per-record explicit IV using technique 2b from
2020
0
         * RFC 4346 section 6.2.3.2: The IV is a cryptographically
2021
0
         * strong random number XORed with the CBC residue from the previous
2022
0
         * record.
2023
0
         */
2024
0
        ivLen = cwSpec->cipherDef->iv_size;
2025
0
        if (ivLen > SSL_BUFFER_SPACE(wrBuf)) {
2026
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2027
0
            return SECFailure;
2028
0
        }
2029
0
        rv = PK11_GenerateRandom(SSL_BUFFER_NEXT(wrBuf), ivLen);
2030
0
        if (rv != SECSuccess) {
2031
0
            ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
2032
0
            return rv;
2033
0
        }
2034
0
        rv = cwSpec->cipher(cwSpec->cipherContext,
2035
0
                            SSL_BUFFER_NEXT(wrBuf), /* output */
2036
0
                            &len,                   /* outlen */
2037
0
                            ivLen,                  /* max outlen */
2038
0
                            SSL_BUFFER_NEXT(wrBuf), /* input */
2039
0
                            ivLen);                 /* input len */
2040
0
        if (rv != SECSuccess || len != ivLen) {
2041
0
            PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2042
0
            return SECFailure;
2043
0
        }
2044
0
2045
0
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2046
0
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2047
0
    }
2048
0
2049
0
    rv = ssl3_BuildRecordPseudoHeader(
2050
0
        cwSpec->epoch, cwSpec->nextSeqNum, ct,
2051
0
        cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->recordVersion,
2052
0
        isDTLS, contentLen, &pseudoHeader);
2053
0
    PORT_Assert(rv == SECSuccess);
2054
0
    if (cwSpec->cipherDef->type == type_aead) {
2055
0
        const int nonceLen = cwSpec->cipherDef->explicit_nonce_size;
2056
0
        const int tagLen = cwSpec->cipherDef->tag_size;
2057
0
2058
0
        if (nonceLen + contentLen + tagLen > SSL_BUFFER_SPACE(wrBuf)) {
2059
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2060
0
            return SECFailure;
2061
0
        }
2062
0
2063
0
        rv = cwSpec->aead(
2064
0
            &cwSpec->keyMaterial,
2065
0
            PR_FALSE,                /* do encrypt */
2066
0
            SSL_BUFFER_NEXT(wrBuf),  /* output  */
2067
0
            &len,                    /* out len */
2068
0
            SSL_BUFFER_SPACE(wrBuf), /* max out */
2069
0
            pIn, contentLen,         /* input   */
2070
0
            SSL_BUFFER_BASE(&pseudoHeader), SSL_BUFFER_LEN(&pseudoHeader));
2071
0
        if (rv != SECSuccess) {
2072
0
            PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2073
0
            return SECFailure;
2074
0
        }
2075
0
2076
0
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2077
0
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2078
0
    } else {
2079
0
        int blockSize = cwSpec->cipherDef->block_size;
2080
0
2081
0
        /*
2082
0
         * Add the MAC
2083
0
         */
2084
0
        rv = ssl3_ComputeRecordMAC(cwSpec, SSL_BUFFER_BASE(&pseudoHeader),
2085
0
                                   SSL_BUFFER_LEN(&pseudoHeader),
2086
0
                                   pIn, contentLen,
2087
0
                                   SSL_BUFFER_NEXT(wrBuf) + contentLen, &macLen);
2088
0
        if (rv != SECSuccess) {
2089
0
            ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2090
0
            return SECFailure;
2091
0
        }
2092
0
        p1Len = contentLen;
2093
0
        p2Len = macLen;
2094
0
        fragLen = contentLen + macLen; /* needs to be encrypted */
2095
0
        PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
2096
0
2097
0
        /*
2098
0
         * Pad the text (if we're doing a block cipher)
2099
0
         * then Encrypt it
2100
0
         */
2101
0
        if (cwSpec->cipherDef->type == type_block) {
2102
0
            unsigned char *pBuf;
2103
0
            int padding_length;
2104
0
            int i;
2105
0
2106
0
            oddLen = contentLen % blockSize;
2107
0
            /* Assume blockSize is a power of two */
2108
0
            padding_length = blockSize - 1 - ((fragLen) & (blockSize - 1));
2109
0
            fragLen += padding_length + 1;
2110
0
            PORT_Assert((fragLen % blockSize) == 0);
2111
0
2112
0
            /* Pad according to TLS rules (also acceptable to SSL3). */
2113
0
            pBuf = SSL_BUFFER_NEXT(wrBuf) + fragLen - 1;
2114
0
            for (i = padding_length + 1; i > 0; --i) {
2115
0
                *pBuf-- = padding_length;
2116
0
            }
2117
0
            /* now, if contentLen is not a multiple of block size, fix it */
2118
0
            p2Len = fragLen - p1Len;
2119
0
        }
2120
0
        if (p1Len < 256) {
2121
0
            oddLen = p1Len;
2122
0
            p1Len = 0;
2123
0
        } else {
2124
0
            p1Len -= oddLen;
2125
0
        }
2126
0
        if (oddLen) {
2127
0
            p2Len += oddLen;
2128
0
            PORT_Assert((blockSize < 2) ||
2129
0
                        (p2Len % blockSize) == 0);
2130
0
            memmove(SSL_BUFFER_NEXT(wrBuf) + p1Len, pIn + p1Len, oddLen);
2131
0
        }
2132
0
        if (p1Len > 0) {
2133
0
            int cipherBytesPart1 = -1;
2134
0
            rv = cwSpec->cipher(cwSpec->cipherContext,
2135
0
                                SSL_BUFFER_NEXT(wrBuf), /* output */
2136
0
                                &cipherBytesPart1,      /* actual outlen */
2137
0
                                p1Len,                  /* max outlen */
2138
0
                                pIn,
2139
0
                                p1Len); /* input, and inputlen */
2140
0
            PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int)p1Len);
2141
0
            if (rv != SECSuccess || cipherBytesPart1 != (int)p1Len) {
2142
0
                PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2143
0
                return SECFailure;
2144
0
            }
2145
0
            rv = sslBuffer_Skip(wrBuf, p1Len, NULL);
2146
0
            PORT_Assert(rv == SECSuccess);
2147
0
        }
2148
0
        if (p2Len > 0) {
2149
0
            int cipherBytesPart2 = -1;
2150
0
            rv = cwSpec->cipher(cwSpec->cipherContext,
2151
0
                                SSL_BUFFER_NEXT(wrBuf),
2152
0
                                &cipherBytesPart2, /* output and actual outLen */
2153
0
                                p2Len,             /* max outlen */
2154
0
                                SSL_BUFFER_NEXT(wrBuf),
2155
0
                                p2Len); /* input and inputLen*/
2156
0
            PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int)p2Len);
2157
0
            if (rv != SECSuccess || cipherBytesPart2 != (int)p2Len) {
2158
0
                PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2159
0
                return SECFailure;
2160
0
            }
2161
0
            rv = sslBuffer_Skip(wrBuf, p2Len, NULL);
2162
0
            PORT_Assert(rv == SECSuccess);
2163
0
        }
2164
0
    }
2165
0
2166
0
    return SECSuccess;
2167
0
}
2168
2169
/* Note: though this can report failure, it shouldn't. */
2170
SECStatus
2171
ssl_InsertRecordHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec,
2172
                       SSLContentType contentType, sslBuffer *wrBuf,
2173
                       PRBool *needsLength)
2174
0
{
2175
0
    SECStatus rv;
2176
0
2177
0
#ifndef UNSAFE_FUZZER_MODE
2178
0
    if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
2179
0
        cwSpec->epoch > TrafficKeyClearText) {
2180
0
        if (IS_DTLS(ss)) {
2181
0
            return dtls13_InsertCipherTextHeader(ss, cwSpec, wrBuf,
2182
0
                                                 needsLength);
2183
0
        }
2184
0
        contentType = ssl_ct_application_data;
2185
0
    }
2186
0
#endif
2187
0
    rv = sslBuffer_AppendNumber(wrBuf, contentType, 1);
2188
0
    if (rv != SECSuccess) {
2189
0
        return SECFailure;
2190
0
    }
2191
0
2192
0
    rv = sslBuffer_AppendNumber(wrBuf, cwSpec->recordVersion, 2);
2193
0
    if (rv != SECSuccess) {
2194
0
        return SECFailure;
2195
0
    }
2196
0
    if (IS_DTLS(ss)) {
2197
0
        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->epoch, 2);
2198
0
        if (rv != SECSuccess) {
2199
0
            return SECFailure;
2200
0
        }
2201
0
        rv = sslBuffer_AppendNumber(wrBuf, cwSpec->nextSeqNum, 6);
2202
0
        if (rv != SECSuccess) {
2203
0
            return SECFailure;
2204
0
        }
2205
0
    }
2206
0
    *needsLength = PR_TRUE;
2207
0
    return SECSuccess;
2208
0
}
2209
2210
SECStatus
2211
ssl_ProtectRecord(sslSocket *ss, ssl3CipherSpec *cwSpec, SSLContentType ct,
2212
                  const PRUint8 *pIn, PRUint32 contentLen, sslBuffer *wrBuf)
2213
0
{
2214
0
    PRBool needsLength;
2215
0
    unsigned int lenOffset;
2216
0
    SECStatus rv;
2217
0
2218
0
    PORT_Assert(cwSpec->direction == CipherSpecWrite);
2219
0
    PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
2220
0
    PORT_Assert(cwSpec->cipherDef->max_records <= RECORD_SEQ_MAX);
2221
0
2222
0
    if (cwSpec->nextSeqNum >= cwSpec->cipherDef->max_records) {
2223
0
        /* We should have automatically updated before here in TLS 1.3. */
2224
0
        PORT_Assert(cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_3);
2225
0
        SSL_TRC(3, ("%d: SSL[-]: write sequence number at limit 0x%0llx",
2226
0
                    SSL_GETPID(), cwSpec->nextSeqNum));
2227
0
        PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
2228
0
        return SECFailure;
2229
0
    }
2230
0
2231
0
    rv = ssl_InsertRecordHeader(ss, cwSpec, ct, wrBuf, &needsLength);
2232
0
    if (rv != SECSuccess) {
2233
0
        return SECFailure;
2234
0
    }
2235
0
    if (needsLength) {
2236
0
        rv = sslBuffer_Skip(wrBuf, 2, &lenOffset);
2237
0
        if (rv != SECSuccess) {
2238
0
            return SECFailure;
2239
0
        }
2240
0
    }
2241
0
2242
#ifdef UNSAFE_FUZZER_MODE
2243
    {
2244
        int len;
2245
        rv = Null_Cipher(NULL, SSL_BUFFER_NEXT(wrBuf), &len,
2246
                         SSL_BUFFER_SPACE(wrBuf), pIn, contentLen);
2247
        if (rv != SECSuccess) {
2248
            return SECFailure; /* error was set */
2249
        }
2250
        rv = sslBuffer_Skip(wrBuf, len, NULL);
2251
        PORT_Assert(rv == SECSuccess); /* Can't fail. */
2252
    }
2253
#else
2254
0
    if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
2255
0
        rv = tls13_ProtectRecord(ss, cwSpec, ct, pIn, contentLen, wrBuf);
2256
0
    } else {
2257
0
        rv = ssl3_MACEncryptRecord(cwSpec, ss->sec.isServer, IS_DTLS(ss), ct,
2258
0
                                   pIn, contentLen, wrBuf);
2259
0
    }
2260
0
#endif
2261
0
    if (rv != SECSuccess) {
2262
0
        return SECFailure; /* error was set */
2263
0
    }
2264
0
2265
0
    if (needsLength) {
2266
0
        /* Insert the length. */
2267
0
        rv = sslBuffer_InsertLength(wrBuf, lenOffset, 2);
2268
0
        if (rv != SECSuccess) {
2269
0
            PORT_Assert(0); /* Can't fail. */
2270
0
            return SECFailure;
2271
0
        }
2272
0
    }
2273
0
2274
0
    ++cwSpec->nextSeqNum;
2275
0
    return SECSuccess;
2276
0
}
2277
2278
SECStatus
2279
ssl_ProtectNextRecord(sslSocket *ss, ssl3CipherSpec *spec, SSLContentType ct,
2280
                      const PRUint8 *pIn, unsigned int nIn,
2281
                      unsigned int *written)
2282
0
{
2283
0
    sslBuffer *wrBuf = &ss->sec.writeBuf;
2284
0
    unsigned int contentLen;
2285
0
    unsigned int spaceNeeded;
2286
0
    SECStatus rv;
2287
0
2288
0
    contentLen = PR_MIN(nIn, spec->recordSizeLimit);
2289
0
    spaceNeeded = contentLen + SSL3_BUFFER_FUDGE;
2290
0
    if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
2291
0
        spec->cipherDef->type == type_block) {
2292
0
        spaceNeeded += spec->cipherDef->iv_size;
2293
0
    }
2294
0
    if (spaceNeeded > SSL_BUFFER_SPACE(wrBuf)) {
2295
0
        rv = sslBuffer_Grow(wrBuf, spaceNeeded);
2296
0
        if (rv != SECSuccess) {
2297
0
            SSL_DBG(("%d: SSL3[%d]: failed to expand write buffer to %d",
2298
0
                     SSL_GETPID(), ss->fd, spaceNeeded));
2299
0
            return SECFailure;
2300
0
        }
2301
0
    }
2302
0
2303
0
    rv = ssl_ProtectRecord(ss, spec, ct, pIn, contentLen, wrBuf);
2304
0
    if (rv != SECSuccess) {
2305
0
        return SECFailure;
2306
0
    }
2307
0
    PRINT_BUF(50, (ss, "send (encrypted) record data:",
2308
0
                   SSL_BUFFER_BASE(wrBuf), SSL_BUFFER_LEN(wrBuf)));
2309
0
    *written = contentLen;
2310
0
    return SECSuccess;
2311
0
}
2312
2313
/* Process the plain text before sending it.
2314
 * Returns the number of bytes of plaintext that were successfully sent
2315
 *  plus the number of bytes of plaintext that were copied into the
2316
 *  output (write) buffer.
2317
 * Returns SECFailure on a hard IO error, memory error, or crypto error.
2318
 * Does NOT return SECWouldBlock.
2319
 *
2320
 * Notes on the use of the private ssl flags:
2321
 * (no private SSL flags)
2322
 *    Attempt to make and send SSL records for all plaintext
2323
 *    If non-blocking and a send gets WOULD_BLOCK,
2324
 *    or if the pending (ciphertext) buffer is not empty,
2325
 *    then buffer remaining bytes of ciphertext into pending buf,
2326
 *    and continue to do that for all succssive records until all
2327
 *    bytes are used.
2328
 * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2329
 *    As above, except this suppresses all write attempts, and forces
2330
 *    all ciphertext into the pending ciphertext buffer.
2331
 * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
2332
 *    Forces the use of the provided epoch
2333
 */
2334
PRInt32
2335
ssl3_SendRecord(sslSocket *ss,
2336
                ssl3CipherSpec *cwSpec, /* non-NULL for DTLS retransmits */
2337
                SSLContentType ct,
2338
                const PRUint8 *pIn, /* input buffer */
2339
                PRInt32 nIn,        /* bytes of input */
2340
                PRInt32 flags)
2341
0
{
2342
0
    sslBuffer *wrBuf = &ss->sec.writeBuf;
2343
0
    ssl3CipherSpec *spec;
2344
0
    SECStatus rv;
2345
0
    PRInt32 totalSent = 0;
2346
0
2347
0
    SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
2348
0
                SSL_GETPID(), ss->fd, ssl3_DecodeContentType(ct),
2349
0
                nIn));
2350
0
    PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn));
2351
0
2352
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2353
0
    PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
2354
0
2355
0
    if (ss->ssl3.fatalAlertSent) {
2356
0
        SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent",
2357
0
                    SSL_GETPID(), ss->fd));
2358
0
        if (ct != ssl_ct_alert) {
2359
0
            /* If we are sending an alert, then we already have an
2360
0
             * error, so don't overwrite. */
2361
0
            PORT_SetError(SSL_ERROR_HANDSHAKE_FAILED);
2362
0
        }
2363
0
        return SECFailure;
2364
0
    }
2365
0
2366
0
    /* check for Token Presence */
2367
0
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
2368
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
2369
0
        return SECFailure;
2370
0
    }
2371
0
2372
0
    if (cwSpec) {
2373
0
        /* cwSpec can only be set for retransmissions of the DTLS handshake. */
2374
0
        PORT_Assert(IS_DTLS(ss) &&
2375
0
                    (ct == ssl_ct_handshake ||
2376
0
                     ct == ssl_ct_change_cipher_spec));
2377
0
        spec = cwSpec;
2378
0
    } else {
2379
0
        spec = ss->ssl3.cwSpec;
2380
0
    }
2381
0
2382
0
    while (nIn > 0) {
2383
0
        unsigned int written = 0;
2384
0
        PRInt32 sent;
2385
0
2386
0
        ssl_GetSpecReadLock(ss);
2387
0
        rv = ssl_ProtectNextRecord(ss, spec, ct, pIn, nIn, &written);
2388
0
        ssl_ReleaseSpecReadLock(ss);
2389
0
        if (rv != SECSuccess) {
2390
0
            goto loser;
2391
0
        }
2392
0
2393
0
        PORT_Assert(written > 0);
2394
0
        /* DTLS should not fragment non-application data here. */
2395
0
        if (IS_DTLS(ss) && ct != ssl_ct_application_data) {
2396
0
            PORT_Assert(written == nIn);
2397
0
        }
2398
0
2399
0
        pIn += written;
2400
0
        nIn -= written;
2401
0
        PORT_Assert(nIn >= 0);
2402
0
2403
0
        /* If there's still some previously saved ciphertext,
2404
0
         * or the caller doesn't want us to send the data yet,
2405
0
         * then add all our new ciphertext to the amount previously saved.
2406
0
         */
2407
0
        if ((ss->pendingBuf.len > 0) ||
2408
0
            (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2409
0
2410
0
            rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf),
2411
0
                                   SSL_BUFFER_LEN(wrBuf));
2412
0
            if (rv != SECSuccess) {
2413
0
                /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2414
0
                goto loser;
2415
0
            }
2416
0
2417
0
            if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
2418
0
                ss->handshakeBegun = 1;
2419
0
                sent = ssl_SendSavedWriteData(ss);
2420
0
                if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
2421
0
                    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2422
0
                    goto loser;
2423
0
                }
2424
0
                if (ss->pendingBuf.len) {
2425
0
                    flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2426
0
                }
2427
0
            }
2428
0
        } else {
2429
0
            PORT_Assert(SSL_BUFFER_LEN(wrBuf) > 0);
2430
0
            ss->handshakeBegun = 1;
2431
0
            sent = ssl_DefSend(ss, SSL_BUFFER_BASE(wrBuf),
2432
0
                               SSL_BUFFER_LEN(wrBuf),
2433
0
                               flags & ~ssl_SEND_FLAG_MASK);
2434
0
            if (sent < 0) {
2435
0
                if (PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
2436
0
                    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2437
0
                    goto loser;
2438
0
                }
2439
0
                /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
2440
0
                sent = 0;
2441
0
            }
2442
0
            if (SSL_BUFFER_LEN(wrBuf) > (unsigned int)sent) {
2443
0
                if (IS_DTLS(ss)) {
2444
0
                    /* DTLS just says no in this case. No buffering */
2445
0
                    PORT_SetError(PR_WOULD_BLOCK_ERROR);
2446
0
                    goto loser;
2447
0
                }
2448
0
                /* now take all the remaining unsent new ciphertext and
2449
0
                 * append it to the buffer of previously unsent ciphertext.
2450
0
                 */
2451
0
                rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf) + sent,
2452
0
                                       SSL_BUFFER_LEN(wrBuf) - sent);
2453
0
                if (rv != SECSuccess) {
2454
0
                    /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2455
0
                    goto loser;
2456
0
                }
2457
0
            }
2458
0
        }
2459
0
        wrBuf->len = 0;
2460
0
        totalSent += written;
2461
0
    }
2462
0
    return totalSent;
2463
0
2464
0
loser:
2465
0
    /* Don't leave bits of buffer lying around. */
2466
0
    wrBuf->len = 0;
2467
0
    return -1;
2468
0
}
2469
2470
0
#define SSL3_PENDING_HIGH_WATER 1024
2471
2472
/* Attempt to send the content of "in" in an SSL application_data record.
2473
 * Returns "len" or SECFailure,   never SECWouldBlock, nor SECSuccess.
2474
 */
2475
int
2476
ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
2477
                         PRInt32 len, PRInt32 flags)
2478
0
{
2479
0
    PRInt32 totalSent = 0;
2480
0
    PRInt32 discarded = 0;
2481
0
    PRBool splitNeeded = PR_FALSE;
2482
0
2483
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2484
0
    /* These flags for internal use only */
2485
0
    PORT_Assert(!(flags & ssl_SEND_FLAG_NO_RETRANSMIT));
2486
0
    if (len < 0 || !in) {
2487
0
        PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2488
0
        return SECFailure;
2489
0
    }
2490
0
2491
0
    if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
2492
0
        !ssl_SocketIsBlocking(ss)) {
2493
0
        PORT_Assert(!ssl_SocketIsBlocking(ss));
2494
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
2495
0
        return SECFailure;
2496
0
    }
2497
0
2498
0
    if (ss->appDataBuffered && len) {
2499
0
        PORT_Assert(in[0] == (unsigned char)(ss->appDataBuffered));
2500
0
        if (in[0] != (unsigned char)(ss->appDataBuffered)) {
2501
0
            PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2502
0
            return SECFailure;
2503
0
        }
2504
0
        in++;
2505
0
        len--;
2506
0
        discarded = 1;
2507
0
    }
2508
0
2509
0
    /* We will split the first byte of the record into its own record, as
2510
0
     * explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h.
2511
0
     */
2512
0
    if (len > 1 && ss->opt.cbcRandomIV &&
2513
0
        ss->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
2514
0
        ss->ssl3.cwSpec->cipherDef->type == type_block /* CBC */) {
2515
0
        splitNeeded = PR_TRUE;
2516
0
    }
2517
0
2518
0
    while (len > totalSent) {
2519
0
        PRInt32 sent, toSend;
2520
0
2521
0
        if (totalSent > 0) {
2522
0
            /*
2523
0
             * The thread yield is intended to give the reader thread a
2524
0
             * chance to get some cycles while the writer thread is in
2525
0
             * the middle of a large application data write.  (See
2526
0
             * Bugzilla bug 127740, comment #1.)
2527
0
             */
2528
0
            ssl_ReleaseXmitBufLock(ss);
2529
0
            PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */
2530
0
            ssl_GetXmitBufLock(ss);
2531
0
        }
2532
0
2533
0
        if (splitNeeded) {
2534
0
            toSend = 1;
2535
0
            splitNeeded = PR_FALSE;
2536
0
        } else {
2537
0
            toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
2538
0
        }
2539
0
2540
0
        /*
2541
0
         * Note that the 0 epoch is OK because flags will never require
2542
0
         * its use, as guaranteed by the PORT_Assert above.
2543
0
         */
2544
0
        sent = ssl3_SendRecord(ss, NULL, ssl_ct_application_data,
2545
0
                               in + totalSent, toSend, flags);
2546
0
        if (sent < 0) {
2547
0
            if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
2548
0
                PORT_Assert(ss->lastWriteBlocked);
2549
0
                break;
2550
0
            }
2551
0
            return SECFailure; /* error code set by ssl3_SendRecord */
2552
0
        }
2553
0
        totalSent += sent;
2554
0
        if (ss->pendingBuf.len) {
2555
0
            /* must be a non-blocking socket */
2556
0
            PORT_Assert(!ssl_SocketIsBlocking(ss));
2557
0
            PORT_Assert(ss->lastWriteBlocked);
2558
0
            break;
2559
0
        }
2560
0
    }
2561
0
    if (ss->pendingBuf.len) {
2562
0
        /* Must be non-blocking. */
2563
0
        PORT_Assert(!ssl_SocketIsBlocking(ss));
2564
0
        if (totalSent > 0) {
2565
0
            ss->appDataBuffered = 0x100 | in[totalSent - 1];
2566
0
        }
2567
0
2568
0
        totalSent = totalSent + discarded - 1;
2569
0
        if (totalSent <= 0) {
2570
0
            PORT_SetError(PR_WOULD_BLOCK_ERROR);
2571
0
            totalSent = SECFailure;
2572
0
        }
2573
0
        return totalSent;
2574
0
    }
2575
0
    ss->appDataBuffered = 0;
2576
0
    return totalSent + discarded;
2577
0
}
2578
2579
/* Attempt to send buffered handshake messages.
2580
 * This function returns SECSuccess or SECFailure, never SECWouldBlock.
2581
 * Always set sendBuf.len to 0, even when returning SECFailure.
2582
 *
2583
 * Depending on whether we are doing DTLS or not, this either calls
2584
 *
2585
 * - ssl3_FlushHandshakeMessages if non-DTLS
2586
 * - dtls_FlushHandshakeMessages if DTLS
2587
 *
2588
 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
2589
 *             ssl3_AppendHandshake(), ssl3_SendClientHello(),
2590
 *             ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
2591
 *             ssl3_SendFinished(),
2592
 */
2593
SECStatus
2594
ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
2595
0
{
2596
0
    if (IS_DTLS(ss)) {
2597
0
        return dtls_FlushHandshakeMessages(ss, flags);
2598
0
    }
2599
0
    return ssl3_FlushHandshakeMessages(ss, flags);
2600
0
}
2601
2602
/* Attempt to send the content of sendBuf buffer in an SSL handshake record.
2603
 * This function returns SECSuccess or SECFailure, never SECWouldBlock.
2604
 * Always set sendBuf.len to 0, even when returning SECFailure.
2605
 *
2606
 * Called from ssl3_FlushHandshake
2607
 */
2608
static SECStatus
2609
ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
2610
0
{
2611
0
    static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
2612
0
    PRInt32 count = -1;
2613
0
    SECStatus rv;
2614
0
2615
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2616
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2617
0
2618
0
    if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
2619
0
        return SECSuccess;
2620
0
2621
0
    /* only these flags are allowed */
2622
0
    PORT_Assert(!(flags & ~allowedFlags));
2623
0
    if ((flags & ~allowedFlags) != 0) {
2624
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
2625
0
        return SECFailure;
2626
0
    }
2627
0
    count = ssl3_SendRecord(ss, NULL, ssl_ct_handshake,
2628
0
                            ss->sec.ci.sendBuf.buf,
2629
0
                            ss->sec.ci.sendBuf.len, flags);
2630
0
    if (count < 0) {
2631
0
        int err = PORT_GetError();
2632
0
        PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
2633
0
        if (err == PR_WOULD_BLOCK_ERROR) {
2634
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2635
0
        }
2636
0
        rv = SECFailure;
2637
0
    } else if ((unsigned int)count < ss->sec.ci.sendBuf.len) {
2638
0
        /* short write should never happen */
2639
0
        PORT_Assert((unsigned int)count >= ss->sec.ci.sendBuf.len);
2640
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2641
0
        rv = SECFailure;
2642
0
    } else {
2643
0
        rv = SECSuccess;
2644
0
    }
2645
0
2646
0
    /* Whether we succeeded or failed, toss the old handshake data. */
2647
0
    ss->sec.ci.sendBuf.len = 0;
2648
0
    return rv;
2649
0
}
2650
2651
/*
2652
 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
2653
 * the remote client sends a negative response to our certificate request.
2654
 * Returns SECFailure if the application has required client auth.
2655
 *         SECSuccess otherwise.
2656
 */
2657
SECStatus
2658
ssl3_HandleNoCertificate(sslSocket *ss)
2659
0
{
2660
0
    ssl3_CleanupPeerCerts(ss);
2661
0
2662
0
    /* If the server has required client-auth blindly but doesn't
2663
0
     * actually look at the certificate it won't know that no
2664
0
     * certificate was presented so we shutdown the socket to ensure
2665
0
     * an error.  We only do this if we haven't already completed the
2666
0
     * first handshake because if we're redoing the handshake we
2667
0
     * know the server is paying attention to the certificate.
2668
0
     */
2669
0
    if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
2670
0
        (!ss->firstHsDone &&
2671
0
         (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
2672
0
        PRFileDesc *lower;
2673
0
2674
0
        ssl_UncacheSessionID(ss);
2675
0
        SSL3_SendAlert(ss, alert_fatal, bad_certificate);
2676
0
2677
0
        lower = ss->fd->lower;
2678
#ifdef _WIN32
2679
        lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
2680
#else
2681
        lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
2682
0
#endif
2683
0
        PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
2684
0
        return SECFailure;
2685
0
    }
2686
0
    return SECSuccess;
2687
0
}
2688
2689
/************************************************************************
2690
 * Alerts
2691
 */
2692
2693
/*
2694
** Acquires both handshake and XmitBuf locks.
2695
** Called from: ssl3_IllegalParameter   <-
2696
**              ssl3_HandshakeFailure   <-
2697
**              ssl3_HandleAlert    <- ssl3_HandleRecord.
2698
**              ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
2699
**              ssl3_ConsumeHandshakeVariable <-
2700
**              ssl3_HandleHelloRequest <-
2701
**              ssl3_HandleServerHello  <-
2702
**              ssl3_HandleServerKeyExchange <-
2703
**              ssl3_HandleCertificateRequest <-
2704
**              ssl3_HandleServerHelloDone <-
2705
**              ssl3_HandleClientHello  <-
2706
**              ssl3_HandleV2ClientHello <-
2707
**              ssl3_HandleCertificateVerify <-
2708
**              ssl3_HandleClientKeyExchange <-
2709
**              ssl3_HandleCertificate  <-
2710
**              ssl3_HandleFinished <-
2711
**              ssl3_HandleHandshakeMessage <-
2712
**              ssl3_HandlePostHelloHandshakeMessage <-
2713
**              ssl3_HandleRecord   <-
2714
**
2715
*/
2716
SECStatus
2717
SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
2718
0
{
2719
0
    PRUint8 bytes[2];
2720
0
    SECStatus rv;
2721
0
    PRBool needHsLock = !ssl_HaveSSL3HandshakeLock(ss);
2722
0
2723
0
    /* Check that if I need the HS lock I also need the Xmit lock */
2724
0
    PORT_Assert(!needHsLock || !ssl_HaveXmitBufLock(ss));
2725
0
2726
0
    SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
2727
0
                SSL_GETPID(), ss->fd, level, desc));
2728
0
2729
0
    bytes[0] = level;
2730
0
    bytes[1] = desc;
2731
0
2732
0
    if (needHsLock) {
2733
0
        ssl_GetSSL3HandshakeLock(ss);
2734
0
    }
2735
0
    if (level == alert_fatal) {
2736
0
        if (ss->sec.ci.sid) {
2737
0
            ssl_UncacheSessionID(ss);
2738
0
        }
2739
0
    }
2740
0
2741
0
    rv = tls13_SetAlertCipherSpec(ss);
2742
0
    if (rv != SECSuccess) {
2743
0
        if (needHsLock) {
2744
0
            ssl_ReleaseSSL3HandshakeLock(ss);
2745
0
        }
2746
0
        return rv;
2747
0
    }
2748
0
2749
0
    ssl_GetXmitBufLock(ss);
2750
0
    rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
2751
0
    if (rv == SECSuccess) {
2752
0
        PRInt32 sent;
2753
0
        sent = ssl3_SendRecord(ss, NULL, ssl_ct_alert, bytes, 2,
2754
0
                               (desc == no_certificate) ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
2755
0
        rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
2756
0
    }
2757
0
    if (level == alert_fatal) {
2758
0
        ss->ssl3.fatalAlertSent = PR_TRUE;
2759
0
    }
2760
0
    ssl_ReleaseXmitBufLock(ss);
2761
0
    if (needHsLock) {
2762
0
        ssl_ReleaseSSL3HandshakeLock(ss);
2763
0
    }
2764
0
    if (rv == SECSuccess && ss->alertSentCallback) {
2765
0
        SSLAlert alert = { level, desc };
2766
0
        ss->alertSentCallback(ss->fd, ss->alertSentCallbackArg, &alert);
2767
0
    }
2768
0
    return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
2769
0
}
2770
2771
/*
2772
 * Send illegal_parameter alert.  Set generic error number.
2773
 */
2774
static SECStatus
2775
ssl3_IllegalParameter(sslSocket *ss)
2776
0
{
2777
0
    (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
2778
0
    PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2779
0
                                   : SSL_ERROR_BAD_SERVER);
2780
0
    return SECFailure;
2781
0
}
2782
2783
/*
2784
 * Send handshake_Failure alert.  Set generic error number.
2785
 */
2786
static SECStatus
2787
ssl3_HandshakeFailure(sslSocket *ss)
2788
0
{
2789
0
    (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
2790
0
    PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2791
0
                                   : SSL_ERROR_BAD_SERVER);
2792
0
    return SECFailure;
2793
0
}
2794
2795
void
2796
ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode)
2797
0
{
2798
0
    SSL3AlertDescription desc = bad_certificate;
2799
0
    PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
2800
0
2801
0
    switch (errCode) {
2802
0
        case SEC_ERROR_LIBRARY_FAILURE:
2803
0
            desc = unsupported_certificate;
2804
0
            break;
2805
0
        case SEC_ERROR_EXPIRED_CERTIFICATE:
2806
0
            desc = certificate_expired;
2807
0
            break;
2808
0
        case SEC_ERROR_REVOKED_CERTIFICATE:
2809
0
            desc = certificate_revoked;
2810
0
            break;
2811
0
        case SEC_ERROR_INADEQUATE_KEY_USAGE:
2812
0
        case SEC_ERROR_INADEQUATE_CERT_TYPE:
2813
0
            desc = certificate_unknown;
2814
0
            break;
2815
0
        case SEC_ERROR_UNTRUSTED_CERT:
2816
0
            desc = isTLS ? access_denied : certificate_unknown;
2817
0
            break;
2818
0
        case SEC_ERROR_UNKNOWN_ISSUER:
2819
0
        case SEC_ERROR_UNTRUSTED_ISSUER:
2820
0
            desc = isTLS ? unknown_ca : certificate_unknown;
2821
0
            break;
2822
0
        case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
2823
0
            desc = isTLS ? unknown_ca : certificate_expired;
2824
0
            break;
2825
0
2826
0
        case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
2827
0
        case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
2828
0
        case SEC_ERROR_CA_CERT_INVALID:
2829
0
        case SEC_ERROR_BAD_SIGNATURE:
2830
0
        default:
2831
0
            desc = bad_certificate;
2832
0
            break;
2833
0
    }
2834
0
    SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
2835
0
             SSL_GETPID(), ss->fd, errCode));
2836
0
2837
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
2838
0
}
2839
2840
/*
2841
 * Send decode_error alert.  Set generic error number.
2842
 */
2843
SECStatus
2844
ssl3_DecodeError(sslSocket *ss)
2845
0
{
2846
0
    (void)SSL3_SendAlert(ss, alert_fatal,
2847
0
                         ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error
2848
0
                                                               : illegal_parameter);
2849
0
    PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2850
0
                                   : SSL_ERROR_BAD_SERVER);
2851
0
    return SECFailure;
2852
0
}
2853
2854
/* Called from ssl3_HandleRecord.
2855
** Caller must hold both RecvBuf and Handshake locks.
2856
*/
2857
static SECStatus
2858
ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
2859
0
{
2860
0
    SSL3AlertLevel level;
2861
0
    SSL3AlertDescription desc;
2862
0
    int error;
2863
0
2864
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
2865
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2866
0
2867
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
2868
0
2869
0
    if (buf->len != 2) {
2870
0
        (void)ssl3_DecodeError(ss);
2871
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
2872
0
        return SECFailure;
2873
0
    }
2874
0
    level = (SSL3AlertLevel)buf->buf[0];
2875
0
    desc = (SSL3AlertDescription)buf->buf[1];
2876
0
    buf->len = 0;
2877
0
    SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
2878
0
                SSL_GETPID(), ss->fd, level, desc));
2879
0
2880
0
    if (ss->alertReceivedCallback) {
2881
0
        SSLAlert alert = { level, desc };
2882
0
        ss->alertReceivedCallback(ss->fd, ss->alertReceivedCallbackArg, &alert);
2883
0
    }
2884
0
2885
0
    switch (desc) {
2886
0
        case close_notify:
2887
0
            ss->recvdCloseNotify = 1;
2888
0
            error = SSL_ERROR_CLOSE_NOTIFY_ALERT;
2889
0
            break;
2890
0
        case unexpected_message:
2891
0
            error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
2892
0
            break;
2893
0
        case bad_record_mac:
2894
0
            error = SSL_ERROR_BAD_MAC_ALERT;
2895
0
            break;
2896
0
        case decryption_failed_RESERVED:
2897
0
            error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
2898
0
            break;
2899
0
        case record_overflow:
2900
0
            error = SSL_ERROR_RECORD_OVERFLOW_ALERT;
2901
0
            break;
2902
0
        case decompression_failure:
2903
0
            error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
2904
0
            break;
2905
0
        case handshake_failure:
2906
0
            error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
2907
0
            break;
2908
0
        case no_certificate:
2909
0
            error = SSL_ERROR_NO_CERTIFICATE;
2910
0
            break;
2911
0
        case bad_certificate:
2912
0
            error = SSL_ERROR_BAD_CERT_ALERT;
2913
0
            break;
2914
0
        case unsupported_certificate:
2915
0
            error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;
2916
0
            break;
2917
0
        case certificate_revoked:
2918
0
            error = SSL_ERROR_REVOKED_CERT_ALERT;
2919
0
            break;
2920
0
        case certificate_expired:
2921
0
            error = SSL_ERROR_EXPIRED_CERT_ALERT;
2922
0
            break;
2923
0
        case certificate_unknown:
2924
0
            error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
2925
0
            break;
2926
0
        case illegal_parameter:
2927
0
            error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;
2928
0
            break;
2929
0
        case inappropriate_fallback:
2930
0
            error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
2931
0
            break;
2932
0
2933
0
        /* All alerts below are TLS only. */
2934
0
        case unknown_ca:
2935
0
            error = SSL_ERROR_UNKNOWN_CA_ALERT;
2936
0
            break;
2937
0
        case access_denied:
2938
0
            error = SSL_ERROR_ACCESS_DENIED_ALERT;
2939
0
            break;
2940
0
        case decode_error:
2941
0
            error = SSL_ERROR_DECODE_ERROR_ALERT;
2942
0
            break;
2943
0
        case decrypt_error:
2944
0
            error = SSL_ERROR_DECRYPT_ERROR_ALERT;
2945
0
            break;
2946
0
        case export_restriction:
2947
0
            error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
2948
0
            break;
2949
0
        case protocol_version:
2950
0
            error = SSL_ERROR_PROTOCOL_VERSION_ALERT;
2951
0
            break;
2952
0
        case insufficient_security:
2953
0
            error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
2954
0
            break;
2955
0
        case internal_error:
2956
0
            error = SSL_ERROR_INTERNAL_ERROR_ALERT;
2957
0
            break;
2958
0
        case user_canceled:
2959
0
            error = SSL_ERROR_USER_CANCELED_ALERT;
2960
0
            break;
2961
0
        case no_renegotiation:
2962
0
            error = SSL_ERROR_NO_RENEGOTIATION_ALERT;
2963
0
            break;
2964
0
2965
0
        /* Alerts for TLS client hello extensions */
2966
0
        case missing_extension:
2967
0
            error = SSL_ERROR_MISSING_EXTENSION_ALERT;
2968
0
            break;
2969
0
        case unsupported_extension:
2970
0
            error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT;
2971
0
            break;
2972
0
        case certificate_unobtainable:
2973
0
            error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT;
2974
0
            break;
2975
0
        case unrecognized_name:
2976
0
            error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
2977
0
            break;
2978
0
        case bad_certificate_status_response:
2979
0
            error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT;
2980
0
            break;
2981
0
        case bad_certificate_hash_value:
2982
0
            error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT;
2983
0
            break;
2984
0
        default:
2985
0
            error = SSL_ERROR_RX_UNKNOWN_ALERT;
2986
0
            break;
2987
0
    }
2988
0
    if ((ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) &&
2989
0
        (ss->ssl3.hs.ws != wait_server_hello)) {
2990
0
        /* TLS 1.3 requires all but "end of data" alerts to be
2991
0
         * treated as fatal. */
2992
0
        switch (desc) {
2993
0
            case close_notify:
2994
0
            case user_canceled:
2995
0
                break;
2996
0
            default:
2997
0
                level = alert_fatal;
2998
0
        }
2999
0
    }
3000
0
    if (level == alert_fatal) {
3001
0
        ssl_UncacheSessionID(ss);
3002
0
        if ((ss->ssl3.hs.ws == wait_server_hello) &&
3003
0
            (desc == handshake_failure)) {
3004
0
            /* XXX This is a hack.  We're assuming that any handshake failure
3005
0
             * XXX on the client hello is a failure to match ciphers.
3006
0
             */
3007
0
            error = SSL_ERROR_NO_CYPHER_OVERLAP;
3008
0
        }
3009
0
        PORT_SetError(error);
3010
0
        return SECFailure;
3011
0
    }
3012
0
    if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
3013
0
        /* I'm a server. I've requested a client cert. He hasn't got one. */
3014
0
        SECStatus rv;
3015
0
3016
0
        PORT_Assert(ss->sec.isServer);
3017
0
        ss->ssl3.hs.ws = wait_client_key;
3018
0
        rv = ssl3_HandleNoCertificate(ss);
3019
0
        return rv;
3020
0
    }
3021
0
    return SECSuccess;
3022
0
}
3023
3024
/*
3025
 * Change Cipher Specs
3026
 * Called from ssl3_HandleServerHelloDone,
3027
 *             ssl3_HandleClientHello,
3028
 * and         ssl3_HandleFinished
3029
 *
3030
 * Acquires and releases spec write lock, to protect switching the current
3031
 * and pending write spec pointers.
3032
 */
3033
3034
SECStatus
3035
ssl3_SendChangeCipherSpecsInt(sslSocket *ss)
3036
0
{
3037
0
    PRUint8 change = change_cipher_spec_choice;
3038
0
    SECStatus rv;
3039
0
3040
0
    SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
3041
0
                SSL_GETPID(), ss->fd));
3042
0
3043
0
    rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3044
0
    if (rv != SECSuccess) {
3045
0
        return SECFailure; /* error code set by ssl3_FlushHandshake */
3046
0
    }
3047
0
3048
0
    if (!IS_DTLS(ss)) {
3049
0
        PRInt32 sent;
3050
0
        sent = ssl3_SendRecord(ss, NULL, ssl_ct_change_cipher_spec,
3051
0
                               &change, 1, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3052
0
        if (sent < 0) {
3053
0
            return SECFailure; /* error code set by ssl3_SendRecord */
3054
0
        }
3055
0
    } else {
3056
0
        rv = dtls_QueueMessage(ss, ssl_ct_change_cipher_spec, &change, 1);
3057
0
        if (rv != SECSuccess) {
3058
0
            return SECFailure;
3059
0
        }
3060
0
    }
3061
0
    return SECSuccess;
3062
0
}
3063
3064
static SECStatus
3065
ssl3_SendChangeCipherSpecs(sslSocket *ss)
3066
0
{
3067
0
    SECStatus rv;
3068
0
3069
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3070
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3071
0
3072
0
    rv = ssl3_SendChangeCipherSpecsInt(ss);
3073
0
    if (rv != SECSuccess) {
3074
0
        return rv; /* Error code set. */
3075
0
    }
3076
0
3077
0
    /* swap the pending and current write specs. */
3078
0
    ssl_GetSpecWriteLock(ss); /**************************************/
3079
0
3080
0
    ssl_CipherSpecRelease(ss->ssl3.cwSpec);
3081
0
    ss->ssl3.cwSpec = ss->ssl3.pwSpec;
3082
0
    ss->ssl3.pwSpec = NULL;
3083
0
3084
0
    SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
3085
0
                SSL_GETPID(), ss->fd));
3086
0
3087
0
    /* With DTLS, we need to set a holddown timer in case the final
3088
0
     * message got lost */
3089
0
    if (IS_DTLS(ss) && ss->ssl3.crSpec->epoch == ss->ssl3.cwSpec->epoch) {
3090
0
        rv = dtls_StartHolddownTimer(ss);
3091
0
    }
3092
0
    ssl_ReleaseSpecWriteLock(ss); /**************************************/
3093
0
3094
0
    return rv;
3095
0
}
3096
3097
/* Called from ssl3_HandleRecord.
3098
** Caller must hold both RecvBuf and Handshake locks.
3099
 *
3100
 * Acquires and releases spec write lock, to protect switching the current
3101
 * and pending write spec pointers.
3102
*/
3103
static SECStatus
3104
ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
3105
0
{
3106
0
    SSL3WaitState ws = ss->ssl3.hs.ws;
3107
0
    SSL3ChangeCipherSpecChoice change;
3108
0
3109
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3110
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3111
0
3112
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
3113
0
                SSL_GETPID(), ss->fd));
3114
0
3115
0
    /* For DTLS: Ignore this if we aren't expecting it.  Don't kill a connection
3116
0
     *           as a result of receiving trash.
3117
0
     * For TLS: Maybe ignore, but only after checking format. */
3118
0
    if (ws != wait_change_cipher && IS_DTLS(ss)) {
3119
0
        /* Ignore this because it's out of order. */
3120
0
        SSL_TRC(3, ("%d: SSL3[%d]: discard out of order "
3121
0
                    "DTLS change_cipher_spec",
3122
0
                    SSL_GETPID(), ss->fd));
3123
0
        buf->len = 0;
3124
0
        return SECSuccess;
3125
0
    }
3126
0
3127
0
    /* Handshake messages should not span ChangeCipherSpec. */
3128
0
    if (ss->ssl3.hs.header_bytes) {
3129
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3130
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3131
0
        return SECFailure;
3132
0
    }
3133
0
    if (buf->len != 1) {
3134
0
        (void)ssl3_DecodeError(ss);
3135
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3136
0
        return SECFailure;
3137
0
    }
3138
0
    change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
3139
0
    if (change != change_cipher_spec_choice) {
3140
0
        /* illegal_parameter is correct here for both SSL3 and TLS. */
3141
0
        (void)ssl3_IllegalParameter(ss);
3142
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3143
0
        return SECFailure;
3144
0
    }
3145
0
3146
0
    buf->len = 0;
3147
0
    if (ws != wait_change_cipher) {
3148
0
        /* Ignore a CCS for TLS 1.3. This only happens if the server sends a
3149
0
         * HelloRetryRequest.  In other cases, the CCS will fail decryption and
3150
0
         * will be discarded by ssl3_HandleRecord(). */
3151
0
        if (ws == wait_server_hello &&
3152
0
            ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
3153
0
            ss->ssl3.hs.helloRetry) {
3154
0
            PORT_Assert(!ss->sec.isServer);
3155
0
            return SECSuccess;
3156
0
        }
3157
0
        /* Note: For a server, we can't test ss->ssl3.hs.helloRetry or
3158
0
         * ss->version because the server might be stateless (and so it won't
3159
0
         * have set either value yet). Set a flag so that at least we will
3160
0
         * guarantee that the server will treat any ClientHello properly. */
3161
0
        if (ws == wait_client_hello &&
3162
0
            ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3 &&
3163
0
            !ss->ssl3.hs.receivedCcs) {
3164
0
            PORT_Assert(ss->sec.isServer);
3165
0
            ss->ssl3.hs.receivedCcs = PR_TRUE;
3166
0
            return SECSuccess;
3167
0
        }
3168
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3169
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3170
0
        return SECFailure;
3171
0
    }
3172
0
3173
0
    SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
3174
0
                SSL_GETPID(), ss->fd));
3175
0
    ssl_GetSpecWriteLock(ss); /*************************************/
3176
0
    PORT_Assert(ss->ssl3.prSpec);
3177
0
    ssl_CipherSpecRelease(ss->ssl3.crSpec);
3178
0
    ss->ssl3.crSpec = ss->ssl3.prSpec;
3179
0
    ss->ssl3.prSpec = NULL;
3180
0
    ssl_ReleaseSpecWriteLock(ss); /*************************************/
3181
0
3182
0
    ss->ssl3.hs.ws = wait_finished;
3183
0
    return SECSuccess;
3184
0
}
3185
3186
static CK_MECHANISM_TYPE
3187
ssl3_GetMgfMechanismByHashType(SSLHashType hash)
3188
0
{
3189
0
    switch (hash) {
3190
0
        case ssl_hash_sha256:
3191
0
            return CKG_MGF1_SHA256;
3192
0
        case ssl_hash_sha384:
3193
0
            return CKG_MGF1_SHA384;
3194
0
        case ssl_hash_sha512:
3195
0
            return CKG_MGF1_SHA512;
3196
0
        default:
3197
0
            PORT_Assert(0);
3198
0
    }
3199
0
    return CKG_MGF1_SHA256;
3200
0
}
3201
3202
/* Function valid for >= TLS 1.2, only. */
3203
static CK_MECHANISM_TYPE
3204
ssl3_GetHashMechanismByHashType(SSLHashType hashType)
3205
0
{
3206
0
    switch (hashType) {
3207
0
        case ssl_hash_sha512:
3208
0
            return CKM_SHA512;
3209
0
        case ssl_hash_sha384:
3210
0
            return CKM_SHA384;
3211
0
        case ssl_hash_sha256:
3212
0
        case ssl_hash_none:
3213
0
            /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
3214
0
            return CKM_SHA256;
3215
0
        case ssl_hash_sha1:
3216
0
            return CKM_SHA_1;
3217
0
        default:
3218
0
            PORT_Assert(0);
3219
0
    }
3220
0
    return CKM_SHA256;
3221
0
}
3222
3223
/* Function valid for >= TLS 1.2, only. */
3224
static CK_MECHANISM_TYPE
3225
ssl3_GetPrfHashMechanism(sslSocket *ss)
3226
0
{
3227
0
    return ssl3_GetHashMechanismByHashType(ss->ssl3.hs.suite_def->prf_hash);
3228
0
}
3229
3230
static SSLHashType
3231
ssl3_GetSuitePrfHash(sslSocket *ss)
3232
0
{
3233
0
    /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
3234
0
    if (ss->ssl3.hs.suite_def->prf_hash == ssl_hash_none) {
3235
0
        return ssl_hash_sha256;
3236
0
    }
3237
0
    return ss->ssl3.hs.suite_def->prf_hash;
3238
0
}
3239
3240
/* This method completes the derivation of the MS from the PMS.
3241
**
3242
** 1. Derive the MS, if possible, else return an error.
3243
**
3244
** 2. Check the version if |pms_version| is non-zero and if wrong,
3245
**    return an error.
3246
**
3247
** 3. If |msp| is nonzero, return MS in |*msp|.
3248
3249
** Called from:
3250
**   ssl3_ComputeMasterSecretInt
3251
**   tls_ComputeExtendedMasterSecretInt
3252
*/
3253
static SECStatus
3254
ssl3_ComputeMasterSecretFinish(sslSocket *ss,
3255
                               CK_MECHANISM_TYPE master_derive,
3256
                               CK_MECHANISM_TYPE key_derive,
3257
                               CK_VERSION *pms_version,
3258
                               SECItem *params, CK_FLAGS keyFlags,
3259
                               PK11SymKey *pms, PK11SymKey **msp)
3260
0
{
3261
0
    PK11SymKey *ms = NULL;
3262
0
3263
0
    ms = PK11_DeriveWithFlags(pms, master_derive,
3264
0
                              params, key_derive,
3265
0
                              CKA_DERIVE, 0, keyFlags);
3266
0
    if (!ms) {
3267
0
        ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3268
0
        return SECFailure;
3269
0
    }
3270
0
3271
0
    if (pms_version && ss->opt.detectRollBack) {
3272
0
        SSL3ProtocolVersion client_version;
3273
0
        client_version = pms_version->major << 8 | pms_version->minor;
3274
0
3275
0
        if (IS_DTLS(ss)) {
3276
0
            client_version = dtls_DTLSVersionToTLSVersion(client_version);
3277
0
        }
3278
0
3279
0
        if (client_version != ss->clientHelloVersion) {
3280
0
            /* Destroy MS.  Version roll-back detected. */
3281
0
            PK11_FreeSymKey(ms);
3282
0
            ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3283
0
            return SECFailure;
3284
0
        }
3285
0
    }
3286
0
3287
0
    if (msp) {
3288
0
        *msp = ms;
3289
0
    } else {
3290
0
        PK11_FreeSymKey(ms);
3291
0
    }
3292
0
3293
0
    return SECSuccess;
3294
0
}
3295
3296
/*  Compute the ordinary (pre draft-ietf-tls-session-hash) master
3297
 ** secret and return it in |*msp|.
3298
 **
3299
 ** Called from: ssl3_ComputeMasterSecret
3300
 */
3301
static SECStatus
3302
ssl3_ComputeMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3303
                            PK11SymKey **msp)
3304
0
{
3305
0
    PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
3306
0
    PRBool isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3307
0
    /*
3308
0
     * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
3309
0
     * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
3310
0
     * data into a 48-byte value, and does not expect to return the version.
3311
0
     */
3312
0
    PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
3313
0
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh));
3314
0
    CK_MECHANISM_TYPE master_derive;
3315
0
    CK_MECHANISM_TYPE key_derive;
3316
0
    SECItem params;
3317
0
    CK_FLAGS keyFlags;
3318
0
    CK_VERSION pms_version;
3319
0
    CK_VERSION *pms_version_ptr = NULL;
3320
0
    /* master_params may be used as a CK_SSL3_MASTER_KEY_DERIVE_PARAMS */
3321
0
    CK_TLS12_MASTER_KEY_DERIVE_PARAMS master_params;
3322
0
    unsigned int master_params_len;
3323
0
3324
0
    if (isTLS12) {
3325
0
        if (isDH)
3326
0
            master_derive = CKM_TLS12_MASTER_KEY_DERIVE_DH;
3327
0
        else
3328
0
            master_derive = CKM_TLS12_MASTER_KEY_DERIVE;
3329
0
        key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3330
0
        keyFlags = CKF_SIGN | CKF_VERIFY;
3331
0
    } else if (isTLS) {
3332
0
        if (isDH)
3333
0
            master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
3334
0
        else
3335
0
            master_derive = CKM_TLS_MASTER_KEY_DERIVE;
3336
0
        key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3337
0
        keyFlags = CKF_SIGN | CKF_VERIFY;
3338
0
    } else {
3339
0
        if (isDH)
3340
0
            master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
3341
0
        else
3342
0
            master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
3343
0
        key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3344
0
        keyFlags = 0;
3345
0
    }
3346
0
3347
0
    if (!isDH) {
3348
0
        pms_version_ptr = &pms_version;
3349
0
    }
3350
0
3351
0
    master_params.pVersion = pms_version_ptr;
3352
0
    master_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
3353
0
    master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3354
0
    master_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
3355
0
    master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3356
0
    if (isTLS12) {
3357
0
        master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3358
0
        master_params_len = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS);
3359
0
    } else {
3360
0
        /* prfHashMechanism is not relevant with this PRF */
3361
0
        master_params_len = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS);
3362
0
    }
3363
0
3364
0
    params.data = (unsigned char *)&master_params;
3365
0
    params.len = master_params_len;
3366
0
3367
0
    return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3368
0
                                          pms_version_ptr, &params,
3369
0
                                          keyFlags, pms, msp);
3370
0
}
3371
3372
/* Compute the draft-ietf-tls-session-hash master
3373
** secret and return it in |*msp|.
3374
**
3375
** Called from: ssl3_ComputeMasterSecret
3376
*/
3377
static SECStatus
3378
tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3379
                                   PK11SymKey **msp)
3380
0
{
3381
0
    ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3382
0
    CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS extended_master_params;
3383
0
    SSL3Hashes hashes;
3384
0
    /*
3385
0
     * Determine whether to use the DH/ECDH or RSA derivation modes.
3386
0
     */
3387
0
    /*
3388
0
     * TODO(ekr@rtfm.com): Verify that the slot can handle this key expansion
3389
0
     * mode. Bug 1198298 */
3390
0
    PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
3391
0
                           (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh));
3392
0
    CK_MECHANISM_TYPE master_derive;
3393
0
    CK_MECHANISM_TYPE key_derive;
3394
0
    SECItem params;
3395
0
    const CK_FLAGS keyFlags = CKF_SIGN | CKF_VERIFY;
3396
0
    CK_VERSION pms_version;
3397
0
    CK_VERSION *pms_version_ptr = NULL;
3398
0
    SECStatus rv;
3399
0
3400
0
    rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0);
3401
0
    if (rv != SECSuccess) {
3402
0
        PORT_Assert(0); /* Should never fail */
3403
0
        ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3404
0
        return SECFailure;
3405
0
    }
3406
0
3407
0
    if (isDH) {
3408
0
        master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH;
3409
0
    } else {
3410
0
        master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE;
3411
0
        pms_version_ptr = &pms_version;
3412
0
    }
3413
0
3414
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
3415
0
        /* TLS 1.2+ */
3416
0
        extended_master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3417
0
        key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3418
0
    } else {
3419
0
        /* TLS < 1.2 */
3420
0
        extended_master_params.prfHashMechanism = CKM_TLS_PRF;
3421
0
        key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3422
0
    }
3423
0
3424
0
    extended_master_params.pVersion = pms_version_ptr;
3425
0
    extended_master_params.pSessionHash = hashes.u.raw;
3426
0
    extended_master_params.ulSessionHashLen = hashes.len;
3427
0
3428
0
    params.data = (unsigned char *)&extended_master_params;
3429
0
    params.len = sizeof extended_master_params;
3430
0
3431
0
    return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3432
0
                                          pms_version_ptr, &params,
3433
0
                                          keyFlags, pms, msp);
3434
0
}
3435
3436
/* Wrapper method to compute the master secret and return it in |*msp|.
3437
**
3438
** Called from ssl3_ComputeMasterSecret
3439
*/
3440
static SECStatus
3441
ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
3442
                         PK11SymKey **msp)
3443
0
{
3444
0
    PORT_Assert(pms != NULL);
3445
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3446
0
3447
0
    if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
3448
0
        return tls_ComputeExtendedMasterSecretInt(ss, pms, msp);
3449
0
    } else {
3450
0
        return ssl3_ComputeMasterSecretInt(ss, pms, msp);
3451
0
    }
3452
0
}
3453
3454
/*
3455
 * Derive encryption and MAC Keys (and IVs) from master secret
3456
 * Sets a useful error code when returning SECFailure.
3457
 *
3458
 * Called only from ssl3_InitPendingCipherSpec(),
3459
 * which in turn is called from
3460
 *              ssl3_SendRSAClientKeyExchange    (for Full handshake)
3461
 *              ssl3_SendDHClientKeyExchange     (for Full handshake)
3462
 *              ssl3_HandleClientKeyExchange    (for Full handshake)
3463
 *              ssl3_HandleServerHello          (for session restart)
3464
 *              ssl3_HandleClientHello          (for session restart)
3465
 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
3466
 * ssl3_InitPendingCipherSpec does that.
3467
 *
3468
 */
3469
static SECStatus
3470
ssl3_DeriveConnectionKeys(sslSocket *ss, PK11SymKey *masterSecret)
3471
0
{
3472
0
    ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3473
0
    ssl3CipherSpec *prSpec = ss->ssl3.prSpec;
3474
0
    ssl3CipherSpec *clientSpec;
3475
0
    ssl3CipherSpec *serverSpec;
3476
0
    PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
3477
0
    PRBool isTLS12 =
3478
0
        (PRBool)(isTLS && ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3479
0
    const ssl3BulkCipherDef *cipher_def = pwSpec->cipherDef;
3480
0
    PK11SlotInfo *slot = NULL;
3481
0
    PK11SymKey *derivedKeyHandle = NULL;
3482
0
    void *pwArg = ss->pkcs11PinArg;
3483
0
    int keySize;
3484
0
    CK_TLS12_KEY_MAT_PARAMS key_material_params; /* may be used as a
3485
0
                                                  * CK_SSL3_KEY_MAT_PARAMS */
3486
0
    unsigned int key_material_params_len;
3487
0
    CK_SSL3_KEY_MAT_OUT returnedKeys;
3488
0
    CK_MECHANISM_TYPE key_derive;
3489
0
    CK_MECHANISM_TYPE bulk_mechanism;
3490
0
    SSLCipherAlgorithm calg;
3491
0
    SECItem params;
3492
0
    PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == ssl_calg_null);
3493
0
3494
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3495
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3496
0
    PORT_Assert(masterSecret);
3497
0
3498
0
    /* These functions operate in terms of who is writing specs. */
3499
0
    if (ss->sec.isServer) {
3500
0
        clientSpec = prSpec;
3501
0
        serverSpec = pwSpec;
3502
0
    } else {
3503
0
        clientSpec = pwSpec;
3504
0
        serverSpec = prSpec;
3505
0
    }
3506
0
3507
0
    /*
3508
0
     * generate the key material
3509
0
     */
3510
0
    if (cipher_def->type == type_block &&
3511
0
        ss->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
3512
0
        /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
3513
0
        key_material_params.ulIVSizeInBits = 0;
3514
0
        PORT_Memset(clientSpec->keyMaterial.iv, 0, cipher_def->iv_size);
3515
0
        PORT_Memset(serverSpec->keyMaterial.iv, 0, cipher_def->iv_size);
3516
0
    }
3517
0
3518
0
    key_material_params.bIsExport = PR_FALSE;
3519
0
    key_material_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
3520
0
    key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3521
0
    key_material_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
3522
0
    key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3523
0
    key_material_params.pReturnedKeyMaterial = &returnedKeys;
3524
0
3525
0
    if (skipKeysAndIVs) {
3526
0
        keySize = 0;
3527
0
        returnedKeys.pIVClient = NULL;
3528
0
        returnedKeys.pIVServer = NULL;
3529
0
        key_material_params.ulKeySizeInBits = 0;
3530
0
        key_material_params.ulIVSizeInBits = 0;
3531
0
    } else {
3532
0
        keySize = cipher_def->key_size;
3533
0
        returnedKeys.pIVClient = clientSpec->keyMaterial.iv;
3534
0
        returnedKeys.pIVServer = serverSpec->keyMaterial.iv;
3535
0
        key_material_params.ulKeySizeInBits = cipher_def->secret_key_size * BPB;
3536
0
        key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB;
3537
0
    }
3538
0
    key_material_params.ulMacSizeInBits = pwSpec->macDef->mac_size * BPB;
3539
0
3540
0
    calg = cipher_def->calg;
3541
0
    bulk_mechanism = ssl3_Alg2Mech(calg);
3542
0
3543
0
    if (isTLS12) {
3544
0
        key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3545
0
        key_material_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3546
0
        key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS);
3547
0
    } else if (isTLS) {
3548
0
        key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3549
0
        key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
3550
0
    } else {
3551
0
        key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3552
0
        key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
3553
0
    }
3554
0
3555
0
    params.data = (unsigned char *)&key_material_params;
3556
0
    params.len = key_material_params_len;
3557
0
3558
0
    /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
3559
0
     * DERIVE by DEFAULT */
3560
0
    derivedKeyHandle = PK11_Derive(masterSecret, key_derive, &params,
3561
0
                                   bulk_mechanism, CKA_ENCRYPT, keySize);
3562
0
    if (!derivedKeyHandle) {
3563
0
        ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3564
0
        return SECFailure;
3565
0
    }
3566
0
    /* we really should use the actual mac'ing mechanism here, but we
3567
0
     * don't because these types are used to map keytype anyway and both
3568
0
     * mac's map to the same keytype.
3569
0
     */
3570
0
    slot = PK11_GetSlotFromKey(derivedKeyHandle);
3571
0
3572
0
    PK11_FreeSlot(slot); /* slot is held until the key is freed */
3573
0
    clientSpec->keyMaterial.macKey =
3574
0
        PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3575
0
                              CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret,
3576
0
                              PR_TRUE, pwArg);
3577
0
    if (clientSpec->keyMaterial.macKey == NULL) {
3578
0
        goto loser; /* loser sets err */
3579
0
    }
3580
0
    serverSpec->keyMaterial.macKey =
3581
0
        PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3582
0
                              CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret,
3583
0
                              PR_TRUE, pwArg);
3584
0
    if (serverSpec->keyMaterial.macKey == NULL) {
3585
0
        goto loser; /* loser sets err */
3586
0
    }
3587
0
    if (!skipKeysAndIVs) {
3588
0
        clientSpec->keyMaterial.key =
3589
0
            PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3590
0
                                  bulk_mechanism, returnedKeys.hClientKey,
3591
0
                                  PR_TRUE, pwArg);
3592
0
        if (clientSpec->keyMaterial.key == NULL) {
3593
0
            goto loser; /* loser sets err */
3594
0
        }
3595
0
        serverSpec->keyMaterial.key =
3596
0
            PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3597
0
                                  bulk_mechanism, returnedKeys.hServerKey,
3598
0
                                  PR_TRUE, pwArg);
3599
0
        if (serverSpec->keyMaterial.key == NULL) {
3600
0
            goto loser; /* loser sets err */
3601
0
        }
3602
0
    }
3603
0
    PK11_FreeSymKey(derivedKeyHandle);
3604
0
    return SECSuccess;
3605
0
3606
0
loser:
3607
0
    PK11_FreeSymKey(derivedKeyHandle);
3608
0
    ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3609
0
    return SECFailure;
3610
0
}
3611
3612
/* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
3613
 * buffered messages in ss->ssl3.hs.messages. Called from
3614
 * ssl3_NegotiateCipherSuite(), tls13_HandleClientHelloPart2(),
3615
 * and ssl3_HandleServerHello. */
3616
SECStatus
3617
ssl3_InitHandshakeHashes(sslSocket *ss)
3618
0
{
3619
0
    SSL_TRC(30, ("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
3620
0
3621
0
    PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
3622
0
    if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
3623
0
        ss->ssl3.hs.hashType = handshake_hash_record;
3624
0
    } else {
3625
0
        PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha);
3626
0
        /*
3627
0
         * note: We should probably lookup an SSL3 slot for these
3628
0
         * handshake hashes in hopes that we wind up with the same slots
3629
0
         * that the master secret will wind up in ...
3630
0
         */
3631
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
3632
0
            /* determine the hash from the prf */
3633
0
            const SECOidData *hash_oid =
3634
0
                SECOID_FindOIDByMechanism(ssl3_GetPrfHashMechanism(ss));
3635
0
3636
0
            /* Get the PKCS #11 mechanism for the Hash from the cipher suite (prf_hash)
3637
0
             * Convert that to the OidTag. We can then use that OidTag to create our
3638
0
             * PK11Context */
3639
0
            PORT_Assert(hash_oid != NULL);
3640
0
            if (hash_oid == NULL) {
3641
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3642
0
                return SECFailure;
3643
0
            }
3644
0
3645
0
            ss->ssl3.hs.sha = PK11_CreateDigestContext(hash_oid->offset);
3646
0
            if (ss->ssl3.hs.sha == NULL) {
3647
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3648
0
                return SECFailure;
3649
0
            }
3650
0
            ss->ssl3.hs.hashType = handshake_hash_single;
3651
0
            if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3652
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3653
0
                return SECFailure;
3654
0
            }
3655
0
3656
0
        } else {
3657
0
            /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
3658
0
             * created successfully. */
3659
0
            ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
3660
0
            if (ss->ssl3.hs.md5 == NULL) {
3661
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3662
0
                return SECFailure;
3663
0
            }
3664
0
            ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
3665
0
            if (ss->ssl3.hs.sha == NULL) {
3666
0
                PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
3667
0
                ss->ssl3.hs.md5 = NULL;
3668
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3669
0
                return SECFailure;
3670
0
            }
3671
0
            ss->ssl3.hs.hashType = handshake_hash_combo;
3672
0
3673
0
            if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
3674
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3675
0
                return SECFailure;
3676
0
            }
3677
0
            if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3678
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3679
0
                return SECFailure;
3680
0
            }
3681
0
        }
3682
0
    }
3683
0
3684
0
    if (ss->ssl3.hs.hashType != handshake_hash_record &&
3685
0
        ss->ssl3.hs.messages.len > 0) {
3686
0
        if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
3687
0
                                       ss->ssl3.hs.messages.len) != SECSuccess) {
3688
0
            return SECFailure;
3689
0
        }
3690
0
        sslBuffer_Clear(&ss->ssl3.hs.messages);
3691
0
    }
3692
0
3693
0
    return SECSuccess;
3694
0
}
3695
3696
void
3697
ssl3_RestartHandshakeHashes(sslSocket *ss)
3698
0
{
3699
0
    SSL_TRC(30, ("%d: SSL3[%d]: reset handshake hashes",
3700
0
                 SSL_GETPID(), ss->fd));
3701
0
    ss->ssl3.hs.hashType = handshake_hash_unknown;
3702
0
    ss->ssl3.hs.messages.len = 0;
3703
0
    if (ss->ssl3.hs.md5) {
3704
0
        PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
3705
0
        ss->ssl3.hs.md5 = NULL;
3706
0
    }
3707
0
    if (ss->ssl3.hs.sha) {
3708
0
        PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
3709
0
        ss->ssl3.hs.sha = NULL;
3710
0
    }
3711
0
}
3712
3713
/*
3714
 * Handshake messages
3715
 */
3716
/* Called from  ssl3_InitHandshakeHashes()
3717
**      ssl3_AppendHandshake()
3718
**      ssl3_HandleV2ClientHello()
3719
**      ssl3_HandleHandshakeMessage()
3720
** Caller must hold the ssl3Handshake lock.
3721
*/
3722
SECStatus
3723
ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l)
3724
0
{
3725
0
    SECStatus rv = SECSuccess;
3726
0
3727
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3728
0
3729
0
    /* With TLS 1.3, and versions TLS.1.1 and older, we keep the hash(es)
3730
0
     * always up to date. However, we must initially buffer the handshake
3731
0
     * messages, until we know what to do.
3732
0
     * If ss->ssl3.hs.hashType != handshake_hash_unknown,
3733
0
     * it means we know what to do. We calculate (hash our input),
3734
0
     * and we stop appending to the buffer.
3735
0
     *
3736
0
     * With TLS 1.2, we always append all handshake messages,
3737
0
     * and never update the hash, because the hash function we must use for
3738
0
     * certificate_verify might be different from the hash function we use
3739
0
     * when signing other handshake hashes. */
3740
0
3741
0
    if (ss->ssl3.hs.hashType == handshake_hash_unknown ||
3742
0
        ss->ssl3.hs.hashType == handshake_hash_record) {
3743
0
        return sslBuffer_Append(&ss->ssl3.hs.messages, b, l);
3744
0
    }
3745
0
3746
0
    PRINT_BUF(90, (ss, "handshake hash input:", b, l));
3747
0
3748
0
    if (ss->ssl3.hs.hashType == handshake_hash_single) {
3749
0
        PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
3750
0
        rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
3751
0
        if (rv != SECSuccess) {
3752
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3753
0
            return rv;
3754
0
        }
3755
0
    } else if (ss->ssl3.hs.hashType == handshake_hash_combo) {
3756
0
        rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
3757
0
        if (rv != SECSuccess) {
3758
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3759
0
            return rv;
3760
0
        }
3761
0
        rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
3762
0
        if (rv != SECSuccess) {
3763
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3764
0
            return rv;
3765
0
        }
3766
0
    }
3767
0
    return rv;
3768
0
}
3769
3770
SECStatus
3771
ssl3_AppendHandshakeHeader(sslSocket *ss, SSLHandshakeType t, PRUint32 length)
3772
0
{
3773
0
    SECStatus rv;
3774
0
3775
0
    /* If we already have a message in place, we need to enqueue it.
3776
0
     * This empties the buffer. This is a convenient place to call
3777
0
     * dtls_StageHandshakeMessage to mark the message boundary.
3778
0
     */
3779
0
    if (IS_DTLS(ss)) {
3780
0
        rv = dtls_StageHandshakeMessage(ss);
3781
0
        if (rv != SECSuccess) {
3782
0
            return rv;
3783
0
        }
3784
0
    }
3785
0
3786
0
    SSL_TRC(30, ("%d: SSL3[%d]: append handshake header: type %s",
3787
0
                 SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
3788
0
3789
0
    rv = ssl3_AppendHandshakeNumber(ss, t, 1);
3790
0
    if (rv != SECSuccess) {
3791
0
        return rv; /* error code set by AppendHandshake, if applicable. */
3792
0
    }
3793
0
    rv = ssl3_AppendHandshakeNumber(ss, length, 3);
3794
0
    if (rv != SECSuccess) {
3795
0
        return rv; /* error code set by AppendHandshake, if applicable. */
3796
0
    }
3797
0
3798
0
    if (IS_DTLS(ss)) {
3799
0
        /* Note that we make an unfragmented message here. We fragment in the
3800
0
         * transmission code, if necessary */
3801
0
        rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2);
3802
0
        if (rv != SECSuccess) {
3803
0
            return rv; /* error code set by AppendHandshake, if applicable. */
3804
0
        }
3805
0
        ss->ssl3.hs.sendMessageSeq++;
3806
0
3807
0
        /* 0 is the fragment offset, because it's not fragmented yet */
3808
0
        rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
3809
0
        if (rv != SECSuccess) {
3810
0
            return rv; /* error code set by AppendHandshake, if applicable. */
3811
0
        }
3812
0
3813
0
        /* Fragment length -- set to the packet length because not fragmented */
3814
0
        rv = ssl3_AppendHandshakeNumber(ss, length, 3);
3815
0
        if (rv != SECSuccess) {
3816
0
            return rv; /* error code set by AppendHandshake, if applicable. */
3817
0
        }
3818
0
    }
3819
0
3820
0
    return rv; /* error code set by AppendHandshake, if applicable. */
3821
0
}
3822
3823
/**************************************************************************
3824
 * Consume Handshake functions.
3825
 *
3826
 * All data used in these functions is protected by two locks,
3827
 * the RecvBufLock and the SSL3HandshakeLock
3828
 **************************************************************************/
3829
3830
/* Read up the next "bytes" number of bytes from the (decrypted) input
3831
 * stream "b" (which is *length bytes long). Copy them into buffer "v".
3832
 * Reduces *length by bytes.  Advances *b by bytes.
3833
 *
3834
 * If this function returns SECFailure, it has already sent an alert,
3835
 * and has set a generic error code.  The caller should probably
3836
 * override the generic error code by setting another.
3837
 */
3838
SECStatus
3839
ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRUint32 bytes, PRUint8 **b,
3840
                      PRUint32 *length)
3841
0
{
3842
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3843
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3844
0
3845
0
    if ((PRUint32)bytes > *length) {
3846
0
        return ssl3_DecodeError(ss);
3847
0
    }
3848
0
    PORT_Memcpy(v, *b, bytes);
3849
0
    PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
3850
0
    *b += bytes;
3851
0
    *length -= bytes;
3852
0
    return SECSuccess;
3853
0
}
3854
3855
/* Read up the next "bytes" number of bytes from the (decrypted) input
3856
 * stream "b" (which is *length bytes long), and interpret them as an
3857
 * integer in network byte order.  Sets *num to the received value.
3858
 * Reduces *length by bytes.  Advances *b by bytes.
3859
 *
3860
 * On error, an alert has been sent, and a generic error code has been set.
3861
 */
3862
SECStatus
3863
ssl3_ConsumeHandshakeNumber64(sslSocket *ss, PRUint64 *num, PRUint32 bytes,
3864
                              PRUint8 **b, PRUint32 *length)
3865
0
{
3866
0
    PRUint8 *buf = *b;
3867
0
    PRUint32 i;
3868
0
3869
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3870
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3871
0
3872
0
    *num = 0;
3873
0
    if (bytes > sizeof(*num)) {
3874
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3875
0
        return SECFailure;
3876
0
    }
3877
0
3878
0
    if (bytes > *length) {
3879
0
        return ssl3_DecodeError(ss);
3880
0
    }
3881
0
    PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
3882
0
3883
0
    for (i = 0; i < bytes; i++) {
3884
0
        *num = (*num << 8) + buf[i];
3885
0
    }
3886
0
    *b += bytes;
3887
0
    *length -= bytes;
3888
0
    return SECSuccess;
3889
0
}
3890
3891
SECStatus
3892
ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRUint32 *num, PRUint32 bytes,
3893
                            PRUint8 **b, PRUint32 *length)
3894
0
{
3895
0
    PRUint64 num64;
3896
0
    SECStatus rv;
3897
0
3898
0
    PORT_Assert(bytes <= sizeof(*num));
3899
0
    if (bytes > sizeof(*num)) {
3900
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3901
0
        return SECFailure;
3902
0
    }
3903
0
    rv = ssl3_ConsumeHandshakeNumber64(ss, &num64, bytes, b, length);
3904
0
    if (rv != SECSuccess) {
3905
0
        return SECFailure;
3906
0
    }
3907
0
    *num = num64 & 0xffffffff;
3908
0
    return SECSuccess;
3909
0
}
3910
3911
/* Read in two values from the incoming decrypted byte stream "b", which is
3912
 * *length bytes long.  The first value is a number whose size is "bytes"
3913
 * bytes long.  The second value is a byte-string whose size is the value
3914
 * of the first number received.  The latter byte-string, and its length,
3915
 * is returned in the SECItem i.
3916
 *
3917
 * Returns SECFailure (-1) on failure.
3918
 * On error, an alert has been sent, and a generic error code has been set.
3919
 *
3920
 * RADICAL CHANGE for NSS 3.11.  All callers of this function make copies
3921
 * of the data returned in the SECItem *i, so making a copy of it here
3922
 * is simply wasteful.  So, This function now just sets SECItem *i to
3923
 * point to the values in the buffer **b.
3924
 */
3925
SECStatus
3926
ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRUint32 bytes,
3927
                              PRUint8 **b, PRUint32 *length)
3928
0
{
3929
0
    PRUint32 count;
3930
0
    SECStatus rv;
3931
0
3932
0
    PORT_Assert(bytes <= 3);
3933
0
    i->len = 0;
3934
0
    i->data = NULL;
3935
0
    i->type = siBuffer;
3936
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &count, bytes, b, length);
3937
0
    if (rv != SECSuccess) {
3938
0
        return SECFailure;
3939
0
    }
3940
0
    if (count > 0) {
3941
0
        if (count > *length) {
3942
0
            return ssl3_DecodeError(ss);
3943
0
        }
3944
0
        i->data = *b;
3945
0
        i->len = count;
3946
0
        *b += count;
3947
0
        *length -= count;
3948
0
    }
3949
0
    return SECSuccess;
3950
0
}
3951
3952
/* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
3953
 * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
3954
 *
3955
 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
3956
SECOidTag
3957
ssl3_HashTypeToOID(SSLHashType hashType)
3958
0
{
3959
0
    switch (hashType) {
3960
0
        case ssl_hash_sha1:
3961
0
            return SEC_OID_SHA1;
3962
0
        case ssl_hash_sha256:
3963
0
            return SEC_OID_SHA256;
3964
0
        case ssl_hash_sha384:
3965
0
            return SEC_OID_SHA384;
3966
0
        case ssl_hash_sha512:
3967
0
            return SEC_OID_SHA512;
3968
0
        default:
3969
0
            break;
3970
0
    }
3971
0
    return SEC_OID_UNKNOWN;
3972
0
}
3973
3974
SSLHashType
3975
ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme)
3976
0
{
3977
0
    switch (scheme) {
3978
0
        case ssl_sig_rsa_pkcs1_sha1:
3979
0
        case ssl_sig_dsa_sha1:
3980
0
        case ssl_sig_ecdsa_sha1:
3981
0
            return ssl_hash_sha1;
3982
0
        case ssl_sig_rsa_pkcs1_sha256:
3983
0
        case ssl_sig_ecdsa_secp256r1_sha256:
3984
0
        case ssl_sig_rsa_pss_rsae_sha256:
3985
0
        case ssl_sig_rsa_pss_pss_sha256:
3986
0
        case ssl_sig_dsa_sha256:
3987
0
            return ssl_hash_sha256;
3988
0
        case ssl_sig_rsa_pkcs1_sha384:
3989
0
        case ssl_sig_ecdsa_secp384r1_sha384:
3990
0
        case ssl_sig_rsa_pss_rsae_sha384:
3991
0
        case ssl_sig_rsa_pss_pss_sha384:
3992
0
        case ssl_sig_dsa_sha384:
3993
0
            return ssl_hash_sha384;
3994
0
        case ssl_sig_rsa_pkcs1_sha512:
3995
0
        case ssl_sig_ecdsa_secp521r1_sha512:
3996
0
        case ssl_sig_rsa_pss_rsae_sha512:
3997
0
        case ssl_sig_rsa_pss_pss_sha512:
3998
0
        case ssl_sig_dsa_sha512:
3999
0
            return ssl_hash_sha512;
4000
0
        case ssl_sig_rsa_pkcs1_sha1md5:
4001
0
            return ssl_hash_none; /* Special for TLS 1.0/1.1. */
4002
0
        case ssl_sig_none:
4003
0
        case ssl_sig_ed25519:
4004
0
        case ssl_sig_ed448:
4005
0
            break;
4006
0
    }
4007
0
    PORT_Assert(0);
4008
0
    return ssl_hash_none;
4009
0
}
4010
4011
static PRBool
4012
ssl_SignatureSchemeMatchesSpkiOid(SSLSignatureScheme scheme, SECOidTag spkiOid)
4013
0
{
4014
0
    switch (scheme) {
4015
0
        case ssl_sig_rsa_pkcs1_sha256:
4016
0
        case ssl_sig_rsa_pkcs1_sha384:
4017
0
        case ssl_sig_rsa_pkcs1_sha512:
4018
0
        case ssl_sig_rsa_pkcs1_sha1:
4019
0
        case ssl_sig_rsa_pss_rsae_sha256:
4020
0
        case ssl_sig_rsa_pss_rsae_sha384:
4021
0
        case ssl_sig_rsa_pss_rsae_sha512:
4022
0
        case ssl_sig_rsa_pkcs1_sha1md5:
4023
0
            return (spkiOid == SEC_OID_X500_RSA_ENCRYPTION) ||
4024
0
                   (spkiOid == SEC_OID_PKCS1_RSA_ENCRYPTION);
4025
0
        case ssl_sig_rsa_pss_pss_sha256:
4026
0
        case ssl_sig_rsa_pss_pss_sha384:
4027
0
        case ssl_sig_rsa_pss_pss_sha512:
4028
0
            return spkiOid == SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
4029
0
        case ssl_sig_ecdsa_secp256r1_sha256:
4030
0
        case ssl_sig_ecdsa_secp384r1_sha384:
4031
0
        case ssl_sig_ecdsa_secp521r1_sha512:
4032
0
        case ssl_sig_ecdsa_sha1:
4033
0
            return spkiOid == SEC_OID_ANSIX962_EC_PUBLIC_KEY;
4034
0
        case ssl_sig_dsa_sha256:
4035
0
        case ssl_sig_dsa_sha384:
4036
0
        case ssl_sig_dsa_sha512:
4037
0
        case ssl_sig_dsa_sha1:
4038
0
            return spkiOid == SEC_OID_ANSIX9_DSA_SIGNATURE;
4039
0
        case ssl_sig_none:
4040
0
        case ssl_sig_ed25519:
4041
0
        case ssl_sig_ed448:
4042
0
            break;
4043
0
    }
4044
0
    PORT_Assert(0);
4045
0
    return PR_FALSE;
4046
0
}
4047
4048
/* Validate that the signature scheme works for the given key type. */
4049
static PRBool
4050
ssl_SignatureSchemeValid(SSLSignatureScheme scheme, SECOidTag spkiOid,
4051
                         PRBool isTls13)
4052
0
{
4053
0
    if (!ssl_IsSupportedSignatureScheme(scheme)) {
4054
0
        return PR_FALSE;
4055
0
    }
4056
0
    if (!ssl_SignatureSchemeMatchesSpkiOid(scheme, spkiOid)) {
4057
0
        return PR_FALSE;
4058
0
    }
4059
0
    if (isTls13) {
4060
0
        if (ssl_SignatureSchemeToHashType(scheme) == ssl_hash_sha1) {
4061
0
            return PR_FALSE;
4062
0
        }
4063
0
        /* With TLS 1.3, EC keys should have been selected based on calling
4064
0
         * ssl_SignatureSchemeFromSpki(), reject them otherwise. */
4065
0
        return spkiOid != SEC_OID_ANSIX962_EC_PUBLIC_KEY;
4066
0
    }
4067
0
    return PR_TRUE;
4068
0
}
4069
4070
static SECStatus
4071
ssl_SignatureSchemeFromPssSpki(CERTSubjectPublicKeyInfo *spki,
4072
                               SSLSignatureScheme *scheme)
4073
0
{
4074
0
    SECKEYRSAPSSParams pssParam = { 0 };
4075
0
    PORTCheapArenaPool arena;
4076
0
    SECStatus rv;
4077
0
4078
0
    /* The key doesn't have parameters, boo. */
4079
0
    if (!spki->algorithm.parameters.len) {
4080
0
        *scheme = ssl_sig_none;
4081
0
        return SECSuccess;
4082
0
    }
4083
0
4084
0
    PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE);
4085
0
    rv = SEC_QuickDERDecodeItem(&arena.arena, &pssParam,
4086
0
                                SEC_ASN1_GET(SECKEY_RSAPSSParamsTemplate),
4087
0
                                &spki->algorithm.parameters);
4088
0
    if (rv != SECSuccess) {
4089
0
        goto loser;
4090
0
    }
4091
0
    /* Not having hashAlg means SHA-1 and we don't accept that. */
4092
0
    if (!pssParam.hashAlg) {
4093
0
        goto loser;
4094
0
    }
4095
0
    switch (SECOID_GetAlgorithmTag(pssParam.hashAlg)) {
4096
0
        case SEC_OID_SHA256:
4097
0
            *scheme = ssl_sig_rsa_pss_pss_sha256;
4098
0
            break;
4099
0
        case SEC_OID_SHA384:
4100
0
            *scheme = ssl_sig_rsa_pss_pss_sha384;
4101
0
            break;
4102
0
        case SEC_OID_SHA512:
4103
0
            *scheme = ssl_sig_rsa_pss_pss_sha512;
4104
0
            break;
4105
0
        default:
4106
0
            goto loser;
4107
0
    }
4108
0
4109
0
    PORT_DestroyCheapArena(&arena);
4110
0
    return SECSuccess;
4111
0
4112
0
loser:
4113
0
    PORT_DestroyCheapArena(&arena);
4114
0
    PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4115
0
    return SECFailure;
4116
0
}
4117
4118
static SECStatus
4119
ssl_SignatureSchemeFromEcSpki(CERTSubjectPublicKeyInfo *spki,
4120
                              SSLSignatureScheme *scheme)
4121
0
{
4122
0
    const sslNamedGroupDef *group;
4123
0
    SECKEYPublicKey *key;
4124
0
4125
0
    key = SECKEY_ExtractPublicKey(spki);
4126
0
    if (!key) {
4127
0
        PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4128
0
        return SECFailure;
4129
0
    }
4130
0
    group = ssl_ECPubKey2NamedGroup(key);
4131
0
    SECKEY_DestroyPublicKey(key);
4132
0
    if (!group) {
4133
0
        PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4134
0
        return SECFailure;
4135
0
    }
4136
0
    switch (group->name) {
4137
0
        case ssl_grp_ec_secp256r1:
4138
0
            *scheme = ssl_sig_ecdsa_secp256r1_sha256;
4139
0
            return SECSuccess;
4140
0
        case ssl_grp_ec_secp384r1:
4141
0
            *scheme = ssl_sig_ecdsa_secp384r1_sha384;
4142
0
            return SECSuccess;
4143
0
        case ssl_grp_ec_secp521r1:
4144
0
            *scheme = ssl_sig_ecdsa_secp521r1_sha512;
4145
0
            return SECSuccess;
4146
0
        default:
4147
0
            break;
4148
0
    }
4149
0
    PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
4150
0
    return SECFailure;
4151
0
}
4152
4153
/* Newer signature schemes are designed so that a single SPKI can be used with
4154
 * that scheme.  This determines that scheme from the SPKI. If the SPKI doesn't
4155
 * have a single scheme, |*scheme| is set to ssl_sig_none. */
4156
static SECStatus
4157
ssl_SignatureSchemeFromSpki(CERTSubjectPublicKeyInfo *spki,
4158
                            PRBool isTls13, SSLSignatureScheme *scheme)
4159
0
{
4160
0
    SECOidTag spkiOid = SECOID_GetAlgorithmTag(&spki->algorithm);
4161
0
4162
0
    if (spkiOid == SEC_OID_PKCS1_RSA_PSS_SIGNATURE) {
4163
0
        return ssl_SignatureSchemeFromPssSpki(spki, scheme);
4164
0
    }
4165
0
4166
0
    /* Only do this lookup for TLS 1.3, where the scheme can be determined from
4167
0
     * the SPKI alone because the ECDSA key size determines the hash. Earlier
4168
0
     * TLS versions allow the same EC key to be used with different hashes. */
4169
0
    if (isTls13 && spkiOid == SEC_OID_ANSIX962_EC_PUBLIC_KEY) {
4170
0
        return ssl_SignatureSchemeFromEcSpki(spki, scheme);
4171
0
    }
4172
0
4173
0
    *scheme = ssl_sig_none;
4174
0
    return SECSuccess;
4175
0
}
4176
4177
static PRBool
4178
ssl_SignatureSchemeEnabled(sslSocket *ss, SSLSignatureScheme scheme)
4179
0
{
4180
0
    unsigned int i;
4181
0
    for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
4182
0
        if (scheme == ss->ssl3.signatureSchemes[i]) {
4183
0
            return PR_TRUE;
4184
0
        }
4185
0
    }
4186
0
    return PR_FALSE;
4187
0
}
4188
4189
static PRBool
4190
ssl_SignatureKeyMatchesSpkiOid(const ssl3KEADef *keaDef, SECOidTag spkiOid)
4191
0
{
4192
0
    switch (spkiOid) {
4193
0
        case SEC_OID_X500_RSA_ENCRYPTION:
4194
0
        case SEC_OID_PKCS1_RSA_ENCRYPTION:
4195
0
        case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
4196
0
            return keaDef->signKeyType == rsaKey;
4197
0
        case SEC_OID_ANSIX9_DSA_SIGNATURE:
4198
0
            return keaDef->signKeyType == dsaKey;
4199
0
        case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
4200
0
            return keaDef->signKeyType == ecKey;
4201
0
        default:
4202
0
            break;
4203
0
    }
4204
0
    return PR_FALSE;
4205
0
}
4206
4207
/* ssl3_CheckSignatureSchemeConsistency checks that the signature algorithm
4208
 * identifier in |scheme| is consistent with the public key in |cert|. It also
4209
 * checks the hash algorithm against the configured signature algorithms.  If
4210
 * all the tests pass, SECSuccess is returned. Otherwise, PORT_SetError is
4211
 * called and SECFailure is returned. */
4212
SECStatus
4213
ssl_CheckSignatureSchemeConsistency(sslSocket *ss, SSLSignatureScheme scheme,
4214
                                    CERTCertificate *cert)
4215
0
{
4216
0
    SSLSignatureScheme spkiScheme;
4217
0
    PRBool isTLS13 = ss->version == SSL_LIBRARY_VERSION_TLS_1_3;
4218
0
    SECOidTag spkiOid;
4219
0
    SECStatus rv;
4220
0
4221
0
    rv = ssl_SignatureSchemeFromSpki(&cert->subjectPublicKeyInfo, isTLS13,
4222
0
                                     &spkiScheme);
4223
0
    if (rv != SECSuccess) {
4224
0
        return SECFailure;
4225
0
    }
4226
0
    if (spkiScheme != ssl_sig_none) {
4227
0
        /* The SPKI in the certificate can only be used for a single scheme. */
4228
0
        if (spkiScheme != scheme ||
4229
0
            !ssl_SignatureSchemeEnabled(ss, scheme)) {
4230
0
            PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4231
0
            return SECFailure;
4232
0
        }
4233
0
        return SECSuccess;
4234
0
    }
4235
0
4236
0
    spkiOid = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm);
4237
0
4238
0
    /* If we're a client, check that the signature algorithm matches the signing
4239
0
     * key type of the cipher suite. */
4240
0
    if (!isTLS13 && !ss->sec.isServer) {
4241
0
        if (!ssl_SignatureKeyMatchesSpkiOid(ss->ssl3.hs.kea_def, spkiOid)) {
4242
0
            PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4243
0
            return SECFailure;
4244
0
        }
4245
0
    }
4246
0
4247
0
    /* Verify that the signature scheme matches the signing key. */
4248
0
    if (!ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13)) {
4249
0
        PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4250
0
        return SECFailure;
4251
0
    }
4252
0
4253
0
    if (!ssl_SignatureSchemeEnabled(ss, scheme)) {
4254
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
4255
0
        return SECFailure;
4256
0
    }
4257
0
4258
0
    return SECSuccess;
4259
0
}
4260
4261
PRBool
4262
ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme)
4263
0
{
4264
0
    switch (scheme) {
4265
0
        case ssl_sig_rsa_pkcs1_sha1:
4266
0
        case ssl_sig_rsa_pkcs1_sha256:
4267
0
        case ssl_sig_rsa_pkcs1_sha384:
4268
0
        case ssl_sig_rsa_pkcs1_sha512:
4269
0
        case ssl_sig_rsa_pss_rsae_sha256:
4270
0
        case ssl_sig_rsa_pss_rsae_sha384:
4271
0
        case ssl_sig_rsa_pss_rsae_sha512:
4272
0
        case ssl_sig_rsa_pss_pss_sha256:
4273
0
        case ssl_sig_rsa_pss_pss_sha384:
4274
0
        case ssl_sig_rsa_pss_pss_sha512:
4275
0
        case ssl_sig_ecdsa_secp256r1_sha256:
4276
0
        case ssl_sig_ecdsa_secp384r1_sha384:
4277
0
        case ssl_sig_ecdsa_secp521r1_sha512:
4278
0
        case ssl_sig_dsa_sha1:
4279
0
        case ssl_sig_dsa_sha256:
4280
0
        case ssl_sig_dsa_sha384:
4281
0
        case ssl_sig_dsa_sha512:
4282
0
        case ssl_sig_ecdsa_sha1:
4283
0
            return PR_TRUE;
4284
0
4285
0
        case ssl_sig_rsa_pkcs1_sha1md5:
4286
0
        case ssl_sig_none:
4287
0
        case ssl_sig_ed25519:
4288
0
        case ssl_sig_ed448:
4289
0
            return PR_FALSE;
4290
0
    }
4291
0
    return PR_FALSE;
4292
0
}
4293
4294
PRBool
4295
ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme)
4296
0
{
4297
0
    switch (scheme) {
4298
0
        case ssl_sig_rsa_pss_rsae_sha256:
4299
0
        case ssl_sig_rsa_pss_rsae_sha384:
4300
0
        case ssl_sig_rsa_pss_rsae_sha512:
4301
0
        case ssl_sig_rsa_pss_pss_sha256:
4302
0
        case ssl_sig_rsa_pss_pss_sha384:
4303
0
        case ssl_sig_rsa_pss_pss_sha512:
4304
0
            return PR_TRUE;
4305
0
4306
0
        default:
4307
0
            return PR_FALSE;
4308
0
    }
4309
0
    return PR_FALSE;
4310
0
}
4311
4312
SSLAuthType
4313
ssl_SignatureSchemeToAuthType(SSLSignatureScheme scheme)
4314
0
{
4315
0
    switch (scheme) {
4316
0
        case ssl_sig_rsa_pkcs1_sha1:
4317
0
        case ssl_sig_rsa_pkcs1_sha1md5:
4318
0
        case ssl_sig_rsa_pkcs1_sha256:
4319
0
        case ssl_sig_rsa_pkcs1_sha384:
4320
0
        case ssl_sig_rsa_pkcs1_sha512:
4321
0
        /* We report based on the key type for PSS signatures. */
4322
0
        case ssl_sig_rsa_pss_rsae_sha256:
4323
0
        case ssl_sig_rsa_pss_rsae_sha384:
4324
0
        case ssl_sig_rsa_pss_rsae_sha512:
4325
0
            return ssl_auth_rsa_sign;
4326
0
        case ssl_sig_rsa_pss_pss_sha256:
4327
0
        case ssl_sig_rsa_pss_pss_sha384:
4328
0
        case ssl_sig_rsa_pss_pss_sha512:
4329
0
            return ssl_auth_rsa_pss;
4330
0
        case ssl_sig_ecdsa_secp256r1_sha256:
4331
0
        case ssl_sig_ecdsa_secp384r1_sha384:
4332
0
        case ssl_sig_ecdsa_secp521r1_sha512:
4333
0
        case ssl_sig_ecdsa_sha1:
4334
0
            return ssl_auth_ecdsa;
4335
0
        case ssl_sig_dsa_sha1:
4336
0
        case ssl_sig_dsa_sha256:
4337
0
        case ssl_sig_dsa_sha384:
4338
0
        case ssl_sig_dsa_sha512:
4339
0
            return ssl_auth_dsa;
4340
0
4341
0
        default:
4342
0
            PORT_Assert(0);
4343
0
    }
4344
0
    return ssl_auth_null;
4345
0
}
4346
4347
/* ssl_ConsumeSignatureScheme reads a SSLSignatureScheme (formerly
4348
 * SignatureAndHashAlgorithm) structure from |b| and puts the resulting value
4349
 * into |out|. |b| and |length| are updated accordingly.
4350
 *
4351
 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4352
SECStatus
4353
ssl_ConsumeSignatureScheme(sslSocket *ss, PRUint8 **b,
4354
                           PRUint32 *length, SSLSignatureScheme *out)
4355
0
{
4356
0
    PRUint32 tmp;
4357
0
    SECStatus rv;
4358
0
4359
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
4360
0
    if (rv != SECSuccess) {
4361
0
        return SECFailure; /* Error code set already. */
4362
0
    }
4363
0
    if (!ssl_IsSupportedSignatureScheme((SSLSignatureScheme)tmp)) {
4364
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
4365
0
        return SECFailure;
4366
0
    }
4367
0
    *out = (SSLSignatureScheme)tmp;
4368
0
    return SECSuccess;
4369
0
}
4370
4371
/**************************************************************************
4372
 * end of Consume Handshake functions.
4373
 **************************************************************************/
4374
4375
static SECStatus
4376
ssl3_ComputeHandshakeHash(unsigned char *buf, unsigned int len,
4377
                          SSLHashType hashAlg, SSL3Hashes *hashes)
4378
0
{
4379
0
    SECStatus rv = SECFailure;
4380
0
    PK11Context *hashContext = PK11_CreateDigestContext(
4381
0
        ssl3_HashTypeToOID(hashAlg));
4382
0
4383
0
    if (!hashContext) {
4384
0
        return rv;
4385
0
    }
4386
0
    rv = PK11_DigestBegin(hashContext);
4387
0
    if (rv == SECSuccess) {
4388
0
        rv = PK11_DigestOp(hashContext, buf, len);
4389
0
    }
4390
0
    if (rv == SECSuccess) {
4391
0
        rv = PK11_DigestFinal(hashContext, hashes->u.raw, &hashes->len,
4392
0
                              sizeof(hashes->u.raw));
4393
0
    }
4394
0
    if (rv == SECSuccess) {
4395
0
        hashes->hashAlg = hashAlg;
4396
0
    }
4397
0
    PK11_DestroyContext(hashContext, PR_TRUE);
4398
0
    return rv;
4399
0
}
4400
4401
/* Extract the hashes of handshake messages to this point.
4402
 * Called from ssl3_SendCertificateVerify
4403
 *             ssl3_SendFinished
4404
 *             ssl3_HandleHandshakeMessage
4405
 *
4406
 * Caller must hold the SSL3HandshakeLock.
4407
 * Caller must hold a read or write lock on the Spec R/W lock.
4408
 *  (There is presently no way to assert on a Read lock.)
4409
 */
4410
SECStatus
4411
ssl3_ComputeHandshakeHashes(sslSocket *ss,
4412
                            ssl3CipherSpec *spec, /* uses ->master_secret */
4413
                            SSL3Hashes *hashes,   /* output goes here. */
4414
                            PRUint32 sender)
4415
0
{
4416
0
    SECStatus rv = SECSuccess;
4417
0
    PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
4418
0
    unsigned int outLength;
4419
0
    PRUint8 md5_inner[MAX_MAC_LENGTH];
4420
0
    PRUint8 sha_inner[MAX_MAC_LENGTH];
4421
0
4422
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4423
0
    if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
4424
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4425
0
        return SECFailure;
4426
0
    }
4427
0
4428
0
    hashes->hashAlg = ssl_hash_none;
4429
0
4430
0
    if (ss->ssl3.hs.hashType == handshake_hash_single) {
4431
0
        PK11Context *h;
4432
0
        unsigned int stateLen;
4433
0
        unsigned char stackBuf[1024];
4434
0
        unsigned char *stateBuf = NULL;
4435
0
4436
0
        h = ss->ssl3.hs.sha;
4437
0
        stateBuf = PK11_SaveContextAlloc(h, stackBuf,
4438
0
                                         sizeof(stackBuf), &stateLen);
4439
0
        if (stateBuf == NULL) {
4440
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4441
0
            rv = SECFailure;
4442
0
            goto tls12_loser;
4443
0
        }
4444
0
        rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
4445
0
                               sizeof(hashes->u.raw));
4446
0
        if (rv != SECSuccess) {
4447
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4448
0
            rv = SECFailure;
4449
0
            goto tls12_loser;
4450
0
        }
4451
0
4452
0
        hashes->hashAlg = ssl3_GetSuitePrfHash(ss);
4453
0
4454
0
    tls12_loser:
4455
0
        if (stateBuf) {
4456
0
            if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
4457
0
                ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4458
0
                rv = SECFailure;
4459
0
            }
4460
0
            if (stateBuf != stackBuf) {
4461
0
                PORT_ZFree(stateBuf, stateLen);
4462
0
            }
4463
0
        }
4464
0
    } else if (ss->ssl3.hs.hashType == handshake_hash_record) {
4465
0
        rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
4466
0
                                       ss->ssl3.hs.messages.len,
4467
0
                                       ssl3_GetSuitePrfHash(ss),
4468
0
                                       hashes);
4469
0
    } else {
4470
0
        PK11Context *md5;
4471
0
        PK11Context *sha = NULL;
4472
0
        unsigned char *md5StateBuf = NULL;
4473
0
        unsigned char *shaStateBuf = NULL;
4474
0
        unsigned int md5StateLen, shaStateLen;
4475
0
        unsigned char md5StackBuf[256];
4476
0
        unsigned char shaStackBuf[512];
4477
0
        const int md5Pad = ssl_GetMacDefByAlg(ssl_mac_md5)->pad_size;
4478
0
        const int shaPad = ssl_GetMacDefByAlg(ssl_mac_sha)->pad_size;
4479
0
4480
0
        md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
4481
0
                                            sizeof md5StackBuf, &md5StateLen);
4482
0
        if (md5StateBuf == NULL) {
4483
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4484
0
            rv = SECFailure;
4485
0
            goto loser;
4486
0
        }
4487
0
        md5 = ss->ssl3.hs.md5;
4488
0
4489
0
        shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
4490
0
                                            sizeof shaStackBuf, &shaStateLen);
4491
0
        if (shaStateBuf == NULL) {
4492
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4493
0
            rv = SECFailure;
4494
0
            goto loser;
4495
0
        }
4496
0
        sha = ss->ssl3.hs.sha;
4497
0
4498
0
        if (!isTLS) {
4499
0
            /* compute hashes for SSL3. */
4500
0
            unsigned char s[4];
4501
0
4502
0
            if (!spec->masterSecret) {
4503
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4504
0
                rv = SECFailure;
4505
0
                goto loser;
4506
0
            }
4507
0
4508
0
            s[0] = (unsigned char)(sender >> 24);
4509
0
            s[1] = (unsigned char)(sender >> 16);
4510
0
            s[2] = (unsigned char)(sender >> 8);
4511
0
            s[3] = (unsigned char)sender;
4512
0
4513
0
            if (sender != 0) {
4514
0
                rv |= PK11_DigestOp(md5, s, 4);
4515
0
                PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
4516
0
            }
4517
0
4518
0
            PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, md5Pad));
4519
0
4520
0
            rv |= PK11_DigestKey(md5, spec->masterSecret);
4521
0
            rv |= PK11_DigestOp(md5, mac_pad_1, md5Pad);
4522
0
            rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
4523
0
            PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4524
0
            if (rv != SECSuccess) {
4525
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4526
0
                rv = SECFailure;
4527
0
                goto loser;
4528
0
            }
4529
0
4530
0
            PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
4531
0
4532
0
            if (sender != 0) {
4533
0
                rv |= PK11_DigestOp(sha, s, 4);
4534
0
                PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
4535
0
            }
4536
0
4537
0
            PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, shaPad));
4538
0
4539
0
            rv |= PK11_DigestKey(sha, spec->masterSecret);
4540
0
            rv |= PK11_DigestOp(sha, mac_pad_1, shaPad);
4541
0
            rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
4542
0
            PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4543
0
            if (rv != SECSuccess) {
4544
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4545
0
                rv = SECFailure;
4546
0
                goto loser;
4547
0
            }
4548
0
4549
0
            PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
4550
0
4551
0
            PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, md5Pad));
4552
0
            PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
4553
0
4554
0
            rv |= PK11_DigestBegin(md5);
4555
0
            rv |= PK11_DigestKey(md5, spec->masterSecret);
4556
0
            rv |= PK11_DigestOp(md5, mac_pad_2, md5Pad);
4557
0
            rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
4558
0
        }
4559
0
        rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH);
4560
0
        PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
4561
0
        if (rv != SECSuccess) {
4562
0
            ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4563
0
            rv = SECFailure;
4564
0
            goto loser;
4565
0
        }
4566
0
4567
0
        PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
4568
0
4569
0
        if (!isTLS) {
4570
0
            PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, shaPad));
4571
0
            PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
4572
0
4573
0
            rv |= PK11_DigestBegin(sha);
4574
0
            rv |= PK11_DigestKey(sha, spec->masterSecret);
4575
0
            rv |= PK11_DigestOp(sha, mac_pad_2, shaPad);
4576
0
            rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
4577
0
        }
4578
0
        rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH);
4579
0
        PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
4580
0
        if (rv != SECSuccess) {
4581
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4582
0
            rv = SECFailure;
4583
0
            goto loser;
4584
0
        }
4585
0
4586
0
        PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
4587
0
4588
0
        hashes->len = MD5_LENGTH + SHA1_LENGTH;
4589
0
4590
0
    loser:
4591
0
        if (md5StateBuf) {
4592
0
            if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) !=
4593
0
                SECSuccess) {
4594
0
                ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4595
0
                rv = SECFailure;
4596
0
            }
4597
0
            if (md5StateBuf != md5StackBuf) {
4598
0
                PORT_ZFree(md5StateBuf, md5StateLen);
4599
0
            }
4600
0
        }
4601
0
        if (shaStateBuf) {
4602
0
            if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) !=
4603
0
                SECSuccess) {
4604
0
                ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4605
0
                rv = SECFailure;
4606
0
            }
4607
0
            if (shaStateBuf != shaStackBuf) {
4608
0
                PORT_ZFree(shaStateBuf, shaStateLen);
4609
0
            }
4610
0
        }
4611
0
    }
4612
0
    return rv;
4613
0
}
4614
4615
/**************************************************************************
4616
 * end of Handshake Hash functions.
4617
 * Begin Send and Handle functions for handshakes.
4618
 **************************************************************************/
4619
4620
#ifdef TRACE
4621
#define CHTYPE(t)          \
4622
    case client_hello_##t: \
4623
        return #t;
4624
4625
static const char *
4626
ssl_ClientHelloTypeName(sslClientHelloType type)
4627
{
4628
    switch (type) {
4629
        CHTYPE(initial);
4630
        CHTYPE(retry);
4631
        CHTYPE(retransmit);    /* DTLS only */
4632
        CHTYPE(renegotiation); /* TLS <= 1.2 only */
4633
    }
4634
    PORT_Assert(0);
4635
    return NULL;
4636
}
4637
#undef CHTYPE
4638
#endif
4639
4640
PR_STATIC_ASSERT(SSL3_SESSIONID_BYTES == SSL3_RANDOM_LENGTH);
4641
static void
4642
ssl_MakeFakeSid(sslSocket *ss, PRUint8 *buf)
4643
0
{
4644
0
    PRUint8 x = 0x5a;
4645
0
    int i;
4646
0
    for (i = 0; i < SSL3_SESSIONID_BYTES; ++i) {
4647
0
        x += ss->ssl3.hs.client_random[i];
4648
0
        buf[i] = x;
4649
0
    }
4650
0
}
4651
4652
/* Set the version fields of the cipher spec for a ClientHello. */
4653
static void
4654
ssl_SetClientHelloSpecVersion(sslSocket *ss, ssl3CipherSpec *spec)
4655
0
{
4656
0
    ssl_GetSpecWriteLock(ss);
4657
0
    PORT_Assert(spec->cipherDef->cipher == cipher_null);
4658
0
    /* This is - a best guess - but it doesn't matter here. */
4659
0
    spec->version = ss->vrange.max;
4660
0
    if (IS_DTLS(ss)) {
4661
0
        spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_0_WIRE;
4662
0
    } else {
4663
0
        /* For new connections, cap the record layer version number of TLS
4664
0
         * ClientHello to { 3, 1 } (TLS 1.0). Some TLS 1.0 servers (which seem
4665
0
         * to use F5 BIG-IP) ignore ClientHello.client_version and use the
4666
0
         * record layer version number (TLSPlaintext.version) instead when
4667
0
         * negotiating protocol versions. In addition, if the record layer
4668
0
         * version number of ClientHello is { 3, 2 } (TLS 1.1) or higher, these
4669
0
         * servers reset the TCP connections. Lastly, some F5 BIG-IP servers
4670
0
         * hang if a record containing a ClientHello has a version greater than
4671
0
         * { 3, 1 } and a length greater than 255. Set this flag to work around
4672
0
         * such servers.
4673
0
         *
4674
0
         * The final version is set when a version is negotiated.
4675
0
         */
4676
0
        spec->recordVersion = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0,
4677
0
                                     ss->vrange.max);
4678
0
    }
4679
0
    ssl_ReleaseSpecWriteLock(ss);
4680
0
}
4681
4682
/* Called from ssl3_HandleHelloRequest(),
4683
 *             ssl3_RedoHandshake()
4684
 *             ssl_BeginClientHandshake (when resuming ssl3 session)
4685
 *             dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
4686
 *
4687
 * The |type| argument indicates what is going on here:
4688
 * - client_hello_initial is set for the very first ClientHello
4689
 * - client_hello_retry indicates that this is a second attempt after receiving
4690
 *   a HelloRetryRequest (in TLS 1.3)
4691
 * - client_hello_retransmit is used in DTLS when resending
4692
 * - client_hello_renegotiation is used to renegotiate (in TLS <1.3)
4693
 */
4694
SECStatus
4695
ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type)
4696
0
{
4697
0
    sslSessionID *sid;
4698
0
    SECStatus rv;
4699
0
    unsigned int i;
4700
0
    unsigned int length;
4701
0
    unsigned int num_suites;
4702
0
    unsigned int actual_count = 0;
4703
0
    PRBool isTLS = PR_FALSE;
4704
0
    PRBool requestingResume = PR_FALSE, fallbackSCSV = PR_FALSE;
4705
0
    PRBool unlockNeeded = PR_FALSE;
4706
0
    sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
4707
0
    PRUint16 version = ss->vrange.max;
4708
0
    PRInt32 flags;
4709
0
    unsigned int cookieLen = ss->ssl3.hs.cookie.len;
4710
0
4711
0
    SSL_TRC(3, ("%d: SSL3[%d]: send %s ClientHello handshake", SSL_GETPID(),
4712
0
                ss->fd, ssl_ClientHelloTypeName(type)));
4713
0
4714
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4715
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
4716
0
4717
0
    /* shouldn't get here if SSL3 is disabled, but ... */
4718
0
    if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
4719
0
        PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
4720
0
        PORT_SetError(SSL_ERROR_SSL_DISABLED);
4721
0
        return SECFailure;
4722
0
    }
4723
0
4724
0
    /* If we are responding to a HelloRetryRequest, don't reinitialize. We need
4725
0
     * to maintain the handshake hashes. */
4726
0
    if (ss->ssl3.hs.helloRetry) {
4727
0
        PORT_Assert(type == client_hello_retry);
4728
0
        /* This cookieLen applies to the cookie that appears in the DTLS
4729
0
           ClientHello, which isn't used in DTLS 1.3. */
4730
0
        cookieLen = 0;
4731
0
    } else {
4732
0
        ssl3_RestartHandshakeHashes(ss);
4733
0
    }
4734
0
4735
0
    if (type == client_hello_initial) {
4736
0
        ssl_SetClientHelloSpecVersion(ss, ss->ssl3.cwSpec);
4737
0
    }
4738
0
    /* These must be reset every handshake. */
4739
0
    ssl3_ResetExtensionData(&ss->xtnData, ss);
4740
0
    ss->ssl3.hs.sendingSCSV = PR_FALSE;
4741
0
    ss->ssl3.hs.preliminaryInfo = 0;
4742
0
    PORT_Assert(IS_DTLS(ss) || type != client_hello_retransmit);
4743
0
    SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
4744
0
    ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
4745
0
4746
0
    /* How many suites does our PKCS11 support (regardless of policy)? */
4747
0
    if (ssl3_config_match_init(ss) == 0) {
4748
0
        return SECFailure; /* ssl3_config_match_init has set error code. */
4749
0
    }
4750
0
4751
0
    /*
4752
0
     * During a renegotiation, ss->clientHelloVersion will be used again to
4753
0
     * work around a Windows SChannel bug. Ensure that it is still enabled.
4754
0
     */
4755
0
    if (ss->firstHsDone) {
4756
0
        PORT_Assert(type != client_hello_initial);
4757
0
        if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
4758
0
            PORT_SetError(SSL_ERROR_SSL_DISABLED);
4759
0
            return SECFailure;
4760
0
        }
4761
0
4762
0
        if (ss->clientHelloVersion < ss->vrange.min ||
4763
0
            ss->clientHelloVersion > ss->vrange.max) {
4764
0
            PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
4765
0
            return SECFailure;
4766
0
        }
4767
0
    }
4768
0
4769
0
    /* Check if we have a ss->sec.ci.sid.
4770
0
     * Check that it's not expired.
4771
0
     * If we have an sid and it comes from an external cache, we use it. */
4772
0
    if (ss->sec.ci.sid && ss->sec.ci.sid->cached == in_external_cache) {
4773
0
        PORT_Assert(!ss->sec.isServer);
4774
0
        sid = ss->sec.ci.sid;
4775
0
        SSL_TRC(3, ("%d: SSL3[%d]: using external resumption token in ClientHello",
4776
0
                    SSL_GETPID(), ss->fd));
4777
0
    } else if (!ss->opt.noCache) {
4778
0
        /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
4779
0
         * handles expired entries and other details.
4780
0
         * XXX If we've been called from ssl_BeginClientHandshake, then
4781
0
         * this lookup is duplicative and wasteful.
4782
0
         */
4783
0
        sid = ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url);
4784
0
    } else {
4785
0
        sid = NULL;
4786
0
    }
4787
0
4788
0
    /* We can't resume based on a different token. If the sid exists,
4789
0
     * make sure the token that holds the master secret still exists ...
4790
0
     * If we previously did client-auth, make sure that the token that holds
4791
0
     * the private key still exists, is logged in, hasn't been removed, etc.
4792
0
     */
4793
0
    if (sid) {
4794
0
        PRBool sidOK = PR_TRUE;
4795
0
        const ssl3CipherSuiteCfg *suite;
4796
0
4797
0
        /* Check that the cipher suite we need is enabled. */
4798
0
        suite = ssl_LookupCipherSuiteCfg(sid->u.ssl3.cipherSuite,
4799
0
                                         ss->cipherSuites);
4800
0
        PORT_Assert(suite);
4801
0
        if (!suite || !config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) {
4802
0
            sidOK = PR_FALSE;
4803
0
        }
4804
0
4805
0
        /* Check that we can recover the master secret. */
4806
0
        if (sidOK) {
4807
0
            PK11SlotInfo *slot = NULL;
4808
0
            if (sid->u.ssl3.masterValid) {
4809
0
                slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
4810
0
                                         sid->u.ssl3.masterSlotID);
4811
0
            }
4812
0
            if (slot == NULL) {
4813
0
                sidOK = PR_FALSE;
4814
0
            } else {
4815
0
                PK11SymKey *wrapKey = NULL;
4816
0
                if (!PK11_IsPresent(slot) ||
4817
0
                    ((wrapKey = PK11_GetWrapKey(slot,
4818
0
                                                sid->u.ssl3.masterWrapIndex,
4819
0
                                                sid->u.ssl3.masterWrapMech,
4820
0
                                                sid->u.ssl3.masterWrapSeries,
4821
0
                                                ss->pkcs11PinArg)) == NULL)) {
4822
0
                    sidOK = PR_FALSE;
4823
0
                }
4824
0
                if (wrapKey)
4825
0
                    PK11_FreeSymKey(wrapKey);
4826
0
                PK11_FreeSlot(slot);
4827
0
                slot = NULL;
4828
0
            }
4829
0
        }
4830
0
        /* If we previously did client-auth, make sure that the token that
4831
0
        ** holds the private key still exists, is logged in, hasn't been
4832
0
        ** removed, etc.
4833
0
        */
4834
0
        if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
4835
0
            sidOK = PR_FALSE;
4836
0
        }
4837
0
4838
0
        if (sidOK) {
4839
0
            /* Set version based on the sid. */
4840
0
            if (ss->firstHsDone) {
4841
0
                /*
4842
0
                 * Windows SChannel compares the client_version inside the RSA
4843
0
                 * EncryptedPreMasterSecret of a renegotiation with the
4844
0
                 * client_version of the initial ClientHello rather than the
4845
0
                 * ClientHello in the renegotiation. To work around this bug, we
4846
0
                 * continue to use the client_version used in the initial
4847
0
                 * ClientHello when renegotiating.
4848
0
                 *
4849
0
                 * The client_version of the initial ClientHello is still
4850
0
                 * available in ss->clientHelloVersion. Ensure that
4851
0
                 * sid->version is bounded within
4852
0
                 * [ss->vrange.min, ss->clientHelloVersion], otherwise we
4853
0
                 * can't use sid.
4854
0
                 */
4855
0
                if (sid->version >= ss->vrange.min &&
4856
0
                    sid->version <= ss->clientHelloVersion) {
4857
0
                    version = ss->clientHelloVersion;
4858
0
                } else {
4859
0
                    sidOK = PR_FALSE;
4860
0
                }
4861
0
            } else {
4862
0
                /*
4863
0
                 * Check sid->version is OK first.
4864
0
                 * Previously, we would cap the version based on sid->version,
4865
0
                 * but that prevents negotiation of a higher version if the
4866
0
                 * previous session was reduced (e.g., with version fallback)
4867
0
                 */
4868
0
                if (sid->version < ss->vrange.min ||
4869
0
                    sid->version > ss->vrange.max) {
4870
0
                    sidOK = PR_FALSE;
4871
0
                }
4872
0
            }
4873
0
        }
4874
0
4875
0
        if (!sidOK) {
4876
0
            SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_not_ok);
4877
0
            ssl_UncacheSessionID(ss);
4878
0
            ssl_FreeSID(sid);
4879
0
            sid = NULL;
4880
0
        }
4881
0
    }
4882
0
4883
0
    if (sid) {
4884
0
        requestingResume = PR_TRUE;
4885
0
        SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_hits);
4886
0
4887
0
        PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
4888
0
                      sid->u.ssl3.sessionIDLength));
4889
0
4890
0
        ss->ssl3.policy = sid->u.ssl3.policy;
4891
0
    } else {
4892
0
        SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_misses);
4893
0
4894
0
        /*
4895
0
         * Windows SChannel compares the client_version inside the RSA
4896
0
         * EncryptedPreMasterSecret of a renegotiation with the
4897
0
         * client_version of the initial ClientHello rather than the
4898
0
         * ClientHello in the renegotiation. To work around this bug, we
4899
0
         * continue to use the client_version used in the initial
4900
0
         * ClientHello when renegotiating.
4901
0
         */
4902
0
        if (ss->firstHsDone) {
4903
0
            version = ss->clientHelloVersion;
4904
0
        }
4905
0
4906
0
        sid = ssl3_NewSessionID(ss, PR_FALSE);
4907
0
        if (!sid) {
4908
0
            return SECFailure; /* memory error is set */
4909
0
        }
4910
0
        /* ss->version isn't set yet, but the sid needs a sane value. */
4911
0
        sid->version = version;
4912
0
    }
4913
0
4914
0
    isTLS = (version > SSL_LIBRARY_VERSION_3_0);
4915
0
    ssl_GetSpecWriteLock(ss);
4916
0
    if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
4917
0
        /* SSL records are not being MACed. */
4918
0
        ss->ssl3.cwSpec->version = version;
4919
0
    }
4920
0
    ssl_ReleaseSpecWriteLock(ss);
4921
0
4922
0
    if (ss->sec.ci.sid != NULL) {
4923
0
        ssl_FreeSID(ss->sec.ci.sid); /* decrement ref count, free if zero */
4924
0
    }
4925
0
    ss->sec.ci.sid = sid;
4926
0
4927
0
    /* HACK for SCSV in SSL 3.0.  On initial handshake, prepend SCSV,
4928
0
     * only if TLS is disabled.
4929
0
     */
4930
0
    if (!ss->firstHsDone && !isTLS) {
4931
0
        /* Must set this before calling Hello Extension Senders,
4932
0
         * to suppress sending of empty RI extension.
4933
0
         */
4934
0
        ss->ssl3.hs.sendingSCSV = PR_TRUE;
4935
0
    }
4936
0
4937
0
    /* When we attempt session resumption (only), we must lock the sid to
4938
0
     * prevent races with other resumption connections that receive a
4939
0
     * NewSessionTicket that will cause the ticket in the sid to be replaced.
4940
0
     * Once we've copied the session ticket into our ClientHello message, it
4941
0
     * is OK for the ticket to change, so we just need to make sure we hold
4942
0
     * the lock across the calls to ssl_ConstructExtensions.
4943
0
     */
4944
0
    if (sid->u.ssl3.lock) {
4945
0
        unlockNeeded = PR_TRUE;
4946
0
        PR_RWLock_Rlock(sid->u.ssl3.lock);
4947
0
    }
4948
0
4949
0
    if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3 &&
4950
0
        type == client_hello_initial) {
4951
0
        rv = tls13_SetupClientHello(ss);
4952
0
        if (rv != SECSuccess) {
4953
0
            goto loser;
4954
0
        }
4955
0
    }
4956
0
    if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
4957
0
        rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_client_hello);
4958
0
        if (rv != SECSuccess) {
4959
0
            goto loser;
4960
0
        }
4961
0
    }
4962
0
4963
0
    if (IS_DTLS(ss)) {
4964
0
        ssl3_DisableNonDTLSSuites(ss);
4965
0
    }
4966
0
4967
0
    /* how many suites are permitted by policy and user preference? */
4968
0
    num_suites = count_cipher_suites(ss, ss->ssl3.policy);
4969
0
    if (!num_suites) {
4970
0
        goto loser; /* count_cipher_suites has set error code. */
4971
0
    }
4972
0
4973
0
    fallbackSCSV = ss->opt.enableFallbackSCSV && (!requestingResume ||
4974
0
                                                  version < sid->version);
4975
0
    /* make room for SCSV */
4976
0
    if (ss->ssl3.hs.sendingSCSV) {
4977
0
        ++num_suites;
4978
0
    }
4979
0
    if (fallbackSCSV) {
4980
0
        ++num_suites;
4981
0
    }
4982
0
4983
0
    length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH +
4984
0
             1 + /* session id */
4985
0
             2 + num_suites * sizeof(ssl3CipherSuite) +
4986
0
             1 + 1 /* compression methods */;
4987
0
    if (sid->version < SSL_LIBRARY_VERSION_TLS_1_3) {
4988
0
        length += sid->u.ssl3.sessionIDLength;
4989
0
    } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) {
4990
0
        length += SSL3_SESSIONID_BYTES;
4991
0
    }
4992
0
    if (IS_DTLS(ss)) {
4993
0
        length += 1 + cookieLen;
4994
0
    }
4995
0
4996
0
    if (extensionBuf.len) {
4997
0
        rv = ssl_InsertPaddingExtension(ss, length, &extensionBuf);
4998
0
        if (rv != SECSuccess) {
4999
0
            goto loser; /* err set by ssl_InsertPaddingExtension */
5000
0
        }
5001
0
        length += 2 + extensionBuf.len;
5002
0
    }
5003
0
5004
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_hello, length);
5005
0
    if (rv != SECSuccess) {
5006
0
        goto loser; /* err set by ssl3_AppendHandshake* */
5007
0
    }
5008
0
5009
0
    if (ss->firstHsDone) {
5010
0
        /* The client hello version must stay unchanged to work around
5011
0
         * the Windows SChannel bug described above. */
5012
0
        PORT_Assert(version == ss->clientHelloVersion);
5013
0
    }
5014
0
    ss->clientHelloVersion = PR_MIN(version, SSL_LIBRARY_VERSION_TLS_1_2);
5015
0
    if (IS_DTLS(ss)) {
5016
0
        PRUint16 dtlsVersion;
5017
0
5018
0
        dtlsVersion = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
5019
0
        rv = ssl3_AppendHandshakeNumber(ss, dtlsVersion, 2);
5020
0
    } else {
5021
0
        rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2);
5022
0
    }
5023
0
    if (rv != SECSuccess) {
5024
0
        goto loser; /* err set by ssl3_AppendHandshake* */
5025
0
    }
5026
0
5027
0
    /* Generate a new random if this is the first attempt. */
5028
0
    if (type == client_hello_initial) {
5029
0
        rv = ssl3_GetNewRandom(ss->ssl3.hs.client_random);
5030
0
        if (rv != SECSuccess) {
5031
0
            goto loser; /* err set by GetNewRandom. */
5032
0
        }
5033
0
    }
5034
0
    rv = ssl3_AppendHandshake(ss, ss->ssl3.hs.client_random,
5035
0
                              SSL3_RANDOM_LENGTH);
5036
0
    if (rv != SECSuccess) {
5037
0
        goto loser; /* err set by ssl3_AppendHandshake* */
5038
0
    }
5039
0
5040
0
    if (sid->version < SSL_LIBRARY_VERSION_TLS_1_3) {
5041
0
        rv = ssl3_AppendHandshakeVariable(
5042
0
            ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
5043
0
    } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) {
5044
0
        /* We're faking session resumption, so rather than create new
5045
0
         * randomness, just mix up the client random a little. */
5046
0
        PRUint8 buf[SSL3_SESSIONID_BYTES];
5047
0
        ssl_MakeFakeSid(ss, buf);
5048
0
        rv = ssl3_AppendHandshakeVariable(ss, buf, SSL3_SESSIONID_BYTES, 1);
5049
0
    } else {
5050
0
        rv = ssl3_AppendHandshakeNumber(ss, 0, 1);
5051
0
    }
5052
0
    if (rv != SECSuccess) {
5053
0
        goto loser; /* err set by ssl3_AppendHandshake* */
5054
0
    }
5055
0
5056
0
    if (IS_DTLS(ss)) {
5057
0
        rv = ssl3_AppendHandshakeVariable(
5058
0
            ss, ss->ssl3.hs.cookie.data, cookieLen, 1);
5059
0
        if (rv != SECSuccess) {
5060
0
            goto loser; /* err set by ssl3_AppendHandshake* */
5061
0
        }
5062
0
    }
5063
0
5064
0
    rv = ssl3_AppendHandshakeNumber(ss, num_suites * sizeof(ssl3CipherSuite), 2);
5065
0
    if (rv != SECSuccess) {
5066
0
        goto loser; /* err set by ssl3_AppendHandshake* */
5067
0
    }
5068
0
5069
0
    if (ss->ssl3.hs.sendingSCSV) {
5070
0
        /* Add the actual SCSV */
5071
0
        rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
5072
0
                                        sizeof(ssl3CipherSuite));
5073
0
        if (rv != SECSuccess) {
5074
0
            goto loser; /* err set by ssl3_AppendHandshake* */
5075
0
        }
5076
0
        actual_count++;
5077
0
    }
5078
0
    if (fallbackSCSV) {
5079
0
        rv = ssl3_AppendHandshakeNumber(ss, TLS_FALLBACK_SCSV,
5080
0
                                        sizeof(ssl3CipherSuite));
5081
0
        if (rv != SECSuccess) {
5082
0
            goto loser; /* err set by ssl3_AppendHandshake* */
5083
0
        }
5084
0
        actual_count++;
5085
0
    }
5086
0
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
5087
0
        ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
5088
0
        if (config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) {
5089
0
            actual_count++;
5090
0
            if (actual_count > num_suites) {
5091
0
                /* set error card removal/insertion error */
5092
0
                PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
5093
0
                goto loser;
5094
0
            }
5095
0
            rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite,
5096
0
                                            sizeof(ssl3CipherSuite));
5097
0
            if (rv != SECSuccess) {
5098
0
                goto loser; /* err set by ssl3_AppendHandshake* */
5099
0
            }
5100
0
        }
5101
0
    }
5102
0
5103
0
    /* if cards were removed or inserted between count_cipher_suites and
5104
0
     * generating our list, detect the error here rather than send it off to
5105
0
     * the server.. */
5106
0
    if (actual_count != num_suites) {
5107
0
        /* Card removal/insertion error */
5108
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
5109
0
        goto loser;
5110
0
    }
5111
0
5112
0
    /* Compression methods: count is always 1, null compression. */
5113
0
    rv = ssl3_AppendHandshakeNumber(ss, 1, 1);
5114
0
    if (rv != SECSuccess) {
5115
0
        goto loser; /* err set by ssl3_AppendHandshake* */
5116
0
    }
5117
0
    rv = ssl3_AppendHandshakeNumber(ss, ssl_compression_null, 1);
5118
0
    if (rv != SECSuccess) {
5119
0
        goto loser; /* err set by ssl3_AppendHandshake* */
5120
0
    }
5121
0
5122
0
    if (extensionBuf.len) {
5123
0
        /* If we are sending a PSK binder, replace the dummy value.  Note that
5124
0
         * we only set statelessResume on the client in TLS 1.3. */
5125
0
        if (ss->statelessResume &&
5126
0
            ss->xtnData.sentSessionTicketInClientHello) {
5127
0
            rv = tls13_WriteExtensionsWithBinder(ss, &extensionBuf);
5128
0
        } else {
5129
0
            rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensionBuf, 2);
5130
0
        }
5131
0
        if (rv != SECSuccess) {
5132
0
            goto loser; /* err set by AppendHandshake. */
5133
0
        }
5134
0
    }
5135
0
5136
0
    sslBuffer_Clear(&extensionBuf);
5137
0
    if (unlockNeeded) {
5138
0
        /* Note: goto loser can't be used past this point. */
5139
0
        PR_RWLock_Unlock(sid->u.ssl3.lock);
5140
0
    }
5141
0
5142
0
    if (ss->xtnData.sentSessionTicketInClientHello) {
5143
0
        SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes);
5144
0
    }
5145
0
5146
0
    if (ss->ssl3.hs.sendingSCSV) {
5147
0
        /* Since we sent the SCSV, pretend we sent empty RI extension. */
5148
0
        TLSExtensionData *xtnData = &ss->xtnData;
5149
0
        xtnData->advertised[xtnData->numAdvertised++] =
5150
0
            ssl_renegotiation_info_xtn;
5151
0
    }
5152
0
5153
0
    flags = 0;
5154
0
    rv = ssl3_FlushHandshake(ss, flags);
5155
0
    if (rv != SECSuccess) {
5156
0
        return rv; /* error code set by ssl3_FlushHandshake */
5157
0
    }
5158
0
5159
0
    if (version >= SSL_LIBRARY_VERSION_TLS_1_3) {
5160
0
        rv = tls13_MaybeDo0RTTHandshake(ss);
5161
0
        if (rv != SECSuccess) {
5162
0
            return SECFailure; /* error code set already. */
5163
0
        }
5164
0
    }
5165
0
5166
0
    ss->ssl3.hs.ws = wait_server_hello;
5167
0
    return SECSuccess;
5168
0
5169
0
loser:
5170
0
    if (unlockNeeded) {
5171
0
        PR_RWLock_Unlock(sid->u.ssl3.lock);
5172
0
    }
5173
0
    sslBuffer_Clear(&extensionBuf);
5174
0
    return SECFailure;
5175
0
}
5176
5177
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
5178
 * complete ssl3 Hello Request.
5179
 * Caller must hold Handshake and RecvBuf locks.
5180
 */
5181
static SECStatus
5182
ssl3_HandleHelloRequest(sslSocket *ss)
5183
0
{
5184
0
    sslSessionID *sid = ss->sec.ci.sid;
5185
0
    SECStatus rv;
5186
0
5187
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
5188
0
                SSL_GETPID(), ss->fd));
5189
0
5190
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
5191
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5192
0
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
5193
0
5194
0
    if (ss->ssl3.hs.ws == wait_server_hello)
5195
0
        return SECSuccess;
5196
0
    if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
5197
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
5198
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
5199
0
        return SECFailure;
5200
0
    }
5201
0
    if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
5202
0
        (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation);
5203
0
        PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
5204
0
        return SECFailure;
5205
0
    }
5206
0
5207
0
    if (sid) {
5208
0
        ssl_UncacheSessionID(ss);
5209
0
        ssl_FreeSID(sid);
5210
0
        ss->sec.ci.sid = NULL;
5211
0
    }
5212
0
5213
0
    if (IS_DTLS(ss)) {
5214
0
        dtls_RehandshakeCleanup(ss);
5215
0
    }
5216
0
5217
0
    ssl_GetXmitBufLock(ss);
5218
0
    rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
5219
0
    ssl_ReleaseXmitBufLock(ss);
5220
0
5221
0
    return rv;
5222
0
}
5223
5224
static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
5225
    CKM_DES3_ECB,
5226
    CKM_CAST5_ECB,
5227
    CKM_DES_ECB,
5228
    CKM_KEY_WRAP_LYNKS,
5229
    CKM_IDEA_ECB,
5230
    CKM_CAST3_ECB,
5231
    CKM_CAST_ECB,
5232
    CKM_RC5_ECB,
5233
    CKM_RC2_ECB,
5234
    CKM_CDMF_ECB,
5235
    CKM_SKIPJACK_WRAP,
5236
    CKM_SKIPJACK_CBC64,
5237
    CKM_AES_ECB,
5238
    CKM_CAMELLIA_ECB,
5239
    CKM_SEED_ECB
5240
};
5241
5242
static SECStatus
5243
ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech, unsigned int *wrapMechIndex)
5244
0
{
5245
0
    unsigned int i;
5246
0
    for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
5247
0
        if (wrapMechanismList[i] == mech) {
5248
0
            *wrapMechIndex = i;
5249
0
            return SECSuccess;
5250
0
        }
5251
0
    }
5252
0
    PORT_Assert(0);
5253
0
    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5254
0
    return SECFailure;
5255
0
}
5256
5257
/* Each process sharing the server session ID cache has its own array of SymKey
5258
 * pointers for the symmetric wrapping keys that are used to wrap the master
5259
 * secrets.  There is one key for each authentication type.  These Symkeys
5260
 * correspond to the wrapped SymKeys kept in the server session cache.
5261
 */
5262
const SSLAuthType ssl_wrap_key_auth_type[SSL_NUM_WRAP_KEYS] = {
5263
    ssl_auth_rsa_decrypt,
5264
    ssl_auth_rsa_sign,
5265
    ssl_auth_rsa_pss,
5266
    ssl_auth_ecdsa,
5267
    ssl_auth_ecdh_rsa,
5268
    ssl_auth_ecdh_ecdsa
5269
};
5270
5271
static SECStatus
5272
ssl_FindIndexByWrapKey(const sslServerCert *serverCert, unsigned int *wrapKeyIndex)
5273
0
{
5274
0
    unsigned int i;
5275
0
    for (i = 0; i < SSL_NUM_WRAP_KEYS; ++i) {
5276
0
        if (SSL_CERT_IS(serverCert, ssl_wrap_key_auth_type[i])) {
5277
0
            *wrapKeyIndex = i;
5278
0
            return SECSuccess;
5279
0
        }
5280
0
    }
5281
0
    /* Can't assert here because we still get people using DSA certificates. */
5282
0
    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5283
0
    return SECFailure;
5284
0
}
5285
5286
static PK11SymKey *
5287
ssl_UnwrapSymWrappingKey(
5288
    SSLWrappedSymWrappingKey *pWswk,
5289
    SECKEYPrivateKey *svrPrivKey,
5290
    unsigned int wrapKeyIndex,
5291
    CK_MECHANISM_TYPE masterWrapMech,
5292
    void *pwArg)
5293
0
{
5294
0
    PK11SymKey *unwrappedWrappingKey = NULL;
5295
0
    SECItem wrappedKey;
5296
0
    PK11SymKey *Ks;
5297
0
    SECKEYPublicKey pubWrapKey;
5298
0
    ECCWrappedKeyInfo *ecWrapped;
5299
0
5300
0
    /* found the wrapping key on disk. */
5301
0
    PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
5302
0
    PORT_Assert(pWswk->wrapKeyIndex == wrapKeyIndex);
5303
0
    if (pWswk->symWrapMechanism != masterWrapMech ||
5304
0
        pWswk->wrapKeyIndex != wrapKeyIndex) {
5305
0
        goto loser;
5306
0
    }
5307
0
    wrappedKey.type = siBuffer;
5308
0
    wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
5309
0
    wrappedKey.len = pWswk->wrappedSymKeyLen;
5310
0
    PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
5311
0
5312
0
    switch (ssl_wrap_key_auth_type[wrapKeyIndex]) {
5313
0
5314
0
        case ssl_auth_rsa_decrypt:
5315
0
        case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
5316
0
            unwrappedWrappingKey =
5317
0
                PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
5318
0
                                     masterWrapMech, CKA_UNWRAP, 0);
5319
0
            break;
5320
0
5321
0
        case ssl_auth_ecdsa:
5322
0
        case ssl_auth_ecdh_rsa:
5323
0
        case ssl_auth_ecdh_ecdsa:
5324
0
            /*
5325
0
             * For ssl_auth_ecd*, we first create an EC public key based on
5326
0
             * data stored with the wrappedSymmetricWrappingkey. Next,
5327
0
             * we do an ECDH computation involving this public key and
5328
0
             * the SSL server's (long-term) EC private key. The resulting
5329
0
             * shared secret is treated the same way as Fortezza's Ks, i.e.,
5330
0
             * it is used to recover the symmetric wrapping key.
5331
0
             *
5332
0
             * The data in wrappedSymmetricWrappingkey is laid out as defined
5333
0
             * in the ECCWrappedKeyInfo structure.
5334
0
             */
5335
0
            ecWrapped = (ECCWrappedKeyInfo *)pWswk->wrappedSymmetricWrappingkey;
5336
0
5337
0
            PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5338
0
                            ecWrapped->wrappedKeyLen <=
5339
0
                        MAX_EC_WRAPPED_KEY_BUFLEN);
5340
0
5341
0
            if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5342
0
                    ecWrapped->wrappedKeyLen >
5343
0
                MAX_EC_WRAPPED_KEY_BUFLEN) {
5344
0
                PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5345
0
                goto loser;
5346
0
            }
5347
0
5348
0
            pubWrapKey.keyType = ecKey;
5349
0
            pubWrapKey.u.ec.size = ecWrapped->size;
5350
0
            pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
5351
0
            pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
5352
0
            pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
5353
0
            pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
5354
0
                                               ecWrapped->encodedParamLen;
5355
0
5356
0
            wrappedKey.len = ecWrapped->wrappedKeyLen;
5357
0
            wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
5358
0
                              ecWrapped->pubValueLen;
5359
0
5360
0
            /* Derive Ks using ECDH */
5361
0
            Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
5362
0
                                       NULL, CKM_ECDH1_DERIVE, masterWrapMech,
5363
0
                                       CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5364
0
            if (Ks == NULL) {
5365
0
                goto loser;
5366
0
            }
5367
0
5368
0
            /*  Use Ks to unwrap the wrapping key */
5369
0
            unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL,
5370
0
                                                     &wrappedKey, masterWrapMech,
5371
0
                                                     CKA_UNWRAP, 0);
5372
0
            PK11_FreeSymKey(Ks);
5373
0
5374
0
            break;
5375
0
5376
0
        default:
5377
0
            PORT_Assert(0);
5378
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5379
0
            goto loser;
5380
0
    }
5381
0
loser:
5382
0
    return unwrappedWrappingKey;
5383
0
}
5384
5385
typedef struct {
5386
    PK11SymKey *symWrapKey[SSL_NUM_WRAP_KEYS];
5387
} ssl3SymWrapKey;
5388
5389
static PZLock *symWrapKeysLock = NULL;
5390
static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS];
5391
5392
SECStatus
5393
ssl_FreeSymWrapKeysLock(void)
5394
0
{
5395
0
    if (symWrapKeysLock) {
5396
0
        PZ_DestroyLock(symWrapKeysLock);
5397
0
        symWrapKeysLock = NULL;
5398
0
        return SECSuccess;
5399
0
    }
5400
0
    PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
5401
0
    return SECFailure;
5402
0
}
5403
5404
SECStatus
5405
SSL3_ShutdownServerCache(void)
5406
0
{
5407
0
    int i, j;
5408
0
5409
0
    if (!symWrapKeysLock)
5410
0
        return SECSuccess; /* lock was never initialized */
5411
0
    PZ_Lock(symWrapKeysLock);
5412
0
    /* get rid of all symWrapKeys */
5413
0
    for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
5414
0
        for (j = 0; j < SSL_NUM_WRAP_KEYS; ++j) {
5415
0
            PK11SymKey **pSymWrapKey;
5416
0
            pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
5417
0
            if (*pSymWrapKey) {
5418
0
                PK11_FreeSymKey(*pSymWrapKey);
5419
0
                *pSymWrapKey = NULL;
5420
0
            }
5421
0
        }
5422
0
    }
5423
0
5424
0
    PZ_Unlock(symWrapKeysLock);
5425
0
    ssl_FreeSessionCacheLocks();
5426
0
    return SECSuccess;
5427
0
}
5428
5429
SECStatus
5430
ssl_InitSymWrapKeysLock(void)
5431
0
{
5432
0
    symWrapKeysLock = PZ_NewLock(nssILockOther);
5433
0
    return symWrapKeysLock ? SECSuccess : SECFailure;
5434
0
}
5435
5436
/* Try to get wrapping key for mechanism from in-memory array.
5437
 * If that fails, look for one on disk.
5438
 * If that fails, generate a new one, put the new one on disk,
5439
 * Put the new key in the in-memory array.
5440
 *
5441
 * Note that this function performs some fairly inadvisable functions with
5442
 * certificate private keys.  ECDSA keys are used with ECDH; similarly, RSA
5443
 * signing keys are used to encrypt.  Bug 1248320.
5444
 */
5445
PK11SymKey *
5446
ssl3_GetWrappingKey(sslSocket *ss,
5447
                    PK11SlotInfo *masterSecretSlot,
5448
                    CK_MECHANISM_TYPE masterWrapMech,
5449
                    void *pwArg)
5450
0
{
5451
0
    SSLAuthType authType;
5452
0
    SECKEYPrivateKey *svrPrivKey;
5453
0
    SECKEYPublicKey *svrPubKey = NULL;
5454
0
    PK11SymKey *unwrappedWrappingKey = NULL;
5455
0
    PK11SymKey **pSymWrapKey;
5456
0
    CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM;
5457
0
    int length;
5458
0
    unsigned int wrapMechIndex;
5459
0
    unsigned int wrapKeyIndex;
5460
0
    SECStatus rv;
5461
0
    SECItem wrappedKey;
5462
0
    SSLWrappedSymWrappingKey wswk;
5463
0
    PK11SymKey *Ks = NULL;
5464
0
    SECKEYPublicKey *pubWrapKey = NULL;
5465
0
    SECKEYPrivateKey *privWrapKey = NULL;
5466
0
    ECCWrappedKeyInfo *ecWrapped;
5467
0
    const sslServerCert *serverCert = ss->sec.serverCert;
5468
0
5469
0
    PORT_Assert(serverCert);
5470
0
    PORT_Assert(serverCert->serverKeyPair);
5471
0
    PORT_Assert(serverCert->serverKeyPair->privKey);
5472
0
    PORT_Assert(serverCert->serverKeyPair->pubKey);
5473
0
    if (!serverCert || !serverCert->serverKeyPair ||
5474
0
        !serverCert->serverKeyPair->privKey ||
5475
0
        !serverCert->serverKeyPair->pubKey) {
5476
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5477
0
        return NULL; /* hmm */
5478
0
    }
5479
0
5480
0
    rv = ssl_FindIndexByWrapKey(serverCert, &wrapKeyIndex);
5481
0
    if (rv != SECSuccess)
5482
0
        return NULL; /* unusable wrapping key. */
5483
0
5484
0
    rv = ssl_FindIndexByWrapMechanism(masterWrapMech, &wrapMechIndex);
5485
0
    if (rv != SECSuccess)
5486
0
        return NULL; /* invalid masterWrapMech. */
5487
0
5488
0
    authType = ssl_wrap_key_auth_type[wrapKeyIndex];
5489
0
    svrPrivKey = serverCert->serverKeyPair->privKey;
5490
0
    pSymWrapKey = &symWrapKeys[wrapMechIndex].symWrapKey[wrapKeyIndex];
5491
0
5492
0
    ssl_InitSessionCacheLocks(PR_TRUE);
5493
0
5494
0
    PZ_Lock(symWrapKeysLock);
5495
0
5496
0
    unwrappedWrappingKey = *pSymWrapKey;
5497
0
    if (unwrappedWrappingKey != NULL) {
5498
0
        if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
5499
0
            unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
5500
0
            goto done;
5501
0
        }
5502
0
        /* slot series has changed, so this key is no good any more. */
5503
0
        PK11_FreeSymKey(unwrappedWrappingKey);
5504
0
        *pSymWrapKey = unwrappedWrappingKey = NULL;
5505
0
    }
5506
0
5507
0
    /* Try to get wrapped SymWrapping key out of the (disk) cache. */
5508
0
    /* Following call fills in wswk on success. */
5509
0
    rv = ssl_GetWrappingKey(wrapMechIndex, wrapKeyIndex, &wswk);
5510
0
    if (rv == SECSuccess) {
5511
0
        /* found the wrapped sym wrapping key on disk. */
5512
0
        unwrappedWrappingKey =
5513
0
            ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
5514
0
                                     masterWrapMech, pwArg);
5515
0
        if (unwrappedWrappingKey) {
5516
0
            goto install;
5517
0
        }
5518
0
    }
5519
0
5520
0
    if (!masterSecretSlot) /* caller doesn't want to create a new one. */
5521
0
        goto loser;
5522
0
5523
0
    length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
5524
0
    /* Zero length means fixed key length algorithm, or error.
5525
0
     * It's ambiguous.
5526
0
     */
5527
0
    unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
5528
0
                                       length, pwArg);
5529
0
    if (!unwrappedWrappingKey) {
5530
0
        goto loser;
5531
0
    }
5532
0
5533
0
    /* Prepare the buffer to receive the wrappedWrappingKey,
5534
0
     * the symmetric wrapping key wrapped using the server's pub key.
5535
0
     */
5536
0
    PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */
5537
0
5538
0
    svrPubKey = serverCert->serverKeyPair->pubKey;
5539
0
    wrappedKey.type = siBuffer;
5540
0
    wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey);
5541
0
    wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
5542
0
5543
0
    PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
5544
0
    if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
5545
0
        goto loser;
5546
0
5547
0
    /* wrap symmetric wrapping key in server's public key. */
5548
0
    switch (authType) {
5549
0
        case ssl_auth_rsa_decrypt:
5550
0
        case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
5551
0
        case ssl_auth_rsa_pss:
5552
0
            asymWrapMechanism = CKM_RSA_PKCS;
5553
0
            rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
5554
0
                                    unwrappedWrappingKey, &wrappedKey);
5555
0
            break;
5556
0
5557
0
        case ssl_auth_ecdsa:
5558
0
        case ssl_auth_ecdh_rsa:
5559
0
        case ssl_auth_ecdh_ecdsa:
5560
0
            /*
5561
0
             * We generate an ephemeral EC key pair. Perform an ECDH
5562
0
             * computation involving this ephemeral EC public key and
5563
0
             * the SSL server's (long-term) EC private key. The resulting
5564
0
             * shared secret is treated in the same way as Fortezza's Ks,
5565
0
             * i.e., it is used to wrap the wrapping key. To facilitate
5566
0
             * unwrapping in ssl_UnwrapWrappingKey, we also store all
5567
0
             * relevant info about the ephemeral EC public key in
5568
0
             * wswk.wrappedSymmetricWrappingkey and lay it out as
5569
0
             * described in the ECCWrappedKeyInfo structure.
5570
0
             */
5571
0
            PORT_Assert(SECKEY_GetPublicKeyType(svrPubKey) == ecKey);
5572
0
            if (SECKEY_GetPublicKeyType(svrPubKey) != ecKey) {
5573
0
                /* something is wrong in sslsecur.c if this isn't an ecKey */
5574
0
                PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5575
0
                rv = SECFailure;
5576
0
                goto ec_cleanup;
5577
0
            }
5578
0
5579
0
            privWrapKey = SECKEY_CreateECPrivateKey(
5580
0
                &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
5581
0
            if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
5582
0
                rv = SECFailure;
5583
0
                goto ec_cleanup;
5584
0
            }
5585
0
5586
0
            /* Set the key size in bits */
5587
0
            if (pubWrapKey->u.ec.size == 0) {
5588
0
                pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
5589
0
            }
5590
0
5591
0
            PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +
5592
0
                            pubWrapKey->u.ec.publicValue.len <
5593
0
                        MAX_EC_WRAPPED_KEY_BUFLEN);
5594
0
            if (pubWrapKey->u.ec.DEREncodedParams.len +
5595
0
                    pubWrapKey->u.ec.publicValue.len >=
5596
0
                MAX_EC_WRAPPED_KEY_BUFLEN) {
5597
0
                PORT_SetError(SEC_ERROR_INVALID_KEY);
5598
0
                rv = SECFailure;
5599
0
                goto ec_cleanup;
5600
0
            }
5601
0
5602
0
            /* Derive Ks using ECDH */
5603
0
            Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
5604
0
                                       NULL, CKM_ECDH1_DERIVE, masterWrapMech,
5605
0
                                       CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5606
0
            if (Ks == NULL) {
5607
0
                rv = SECFailure;
5608
0
                goto ec_cleanup;
5609
0
            }
5610
0
5611
0
            ecWrapped = (ECCWrappedKeyInfo *)(wswk.wrappedSymmetricWrappingkey);
5612
0
            ecWrapped->size = pubWrapKey->u.ec.size;
5613
0
            ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
5614
0
            PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
5615
0
                        pubWrapKey->u.ec.DEREncodedParams.len);
5616
0
5617
0
            ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
5618
0
            PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen,
5619
0
                        pubWrapKey->u.ec.publicValue.data,
5620
0
                        pubWrapKey->u.ec.publicValue.len);
5621
0
5622
0
            wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN -
5623
0
                             (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
5624
0
            wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
5625
0
                              ecWrapped->pubValueLen;
5626
0
5627
0
            /* wrap symmetricWrapping key with the local Ks */
5628
0
            rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
5629
0
                                 unwrappedWrappingKey, &wrappedKey);
5630
0
5631
0
            if (rv != SECSuccess) {
5632
0
                goto ec_cleanup;
5633
0
            }
5634
0
5635
0
            /* Write down the length of wrapped key in the buffer
5636
0
             * wswk.wrappedSymmetricWrappingkey at the appropriate offset
5637
0
             */
5638
0
            ecWrapped->wrappedKeyLen = wrappedKey.len;
5639
0
5640
0
        ec_cleanup:
5641
0
            if (privWrapKey)
5642
0
                SECKEY_DestroyPrivateKey(privWrapKey);
5643
0
            if (pubWrapKey)
5644
0
                SECKEY_DestroyPublicKey(pubWrapKey);
5645
0
            if (Ks)
5646
0
                PK11_FreeSymKey(Ks);
5647
0
            asymWrapMechanism = masterWrapMech;
5648
0
            break;
5649
0
5650
0
        default:
5651
0
            rv = SECFailure;
5652
0
            break;
5653
0
    }
5654
0
5655
0
    if (rv != SECSuccess) {
5656
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5657
0
        goto loser;
5658
0
    }
5659
0
5660
0
    PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
5661
0
5662
0
    wswk.symWrapMechanism = masterWrapMech;
5663
0
    wswk.asymWrapMechanism = asymWrapMechanism;
5664
0
    wswk.wrapMechIndex = wrapMechIndex;
5665
0
    wswk.wrapKeyIndex = wrapKeyIndex;
5666
0
    wswk.wrappedSymKeyLen = wrappedKey.len;
5667
0
5668
0
    /* put it on disk. */
5669
0
    /* If the wrapping key for this KEA type has already been set,
5670
0
     * then abandon the value we just computed and
5671
0
     * use the one we got from the disk.
5672
0
     */
5673
0
    rv = ssl_SetWrappingKey(&wswk);
5674
0
    if (rv == SECSuccess) {
5675
0
        /* somebody beat us to it.  The original contents of our wswk
5676
0
         * has been replaced with the content on disk.  Now, discard
5677
0
         * the key we just created and unwrap this new one.
5678
0
         */
5679
0
        PK11_FreeSymKey(unwrappedWrappingKey);
5680
0
5681
0
        unwrappedWrappingKey =
5682
0
            ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
5683
0
                                     masterWrapMech, pwArg);
5684
0
    }
5685
0
5686
0
install:
5687
0
    if (unwrappedWrappingKey) {
5688
0
        *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
5689
0
    }
5690
0
5691
0
loser:
5692
0
done:
5693
0
    PZ_Unlock(symWrapKeysLock);
5694
0
    return unwrappedWrappingKey;
5695
0
}
5696
5697
#ifdef NSS_ALLOW_SSLKEYLOGFILE
5698
/* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
5699
 * bytes to |out|. */
5700
static void
5701
hexEncode(char *out, const unsigned char *in, unsigned int length)
5702
0
{
5703
0
    static const char hextable[] = "0123456789abcdef";
5704
0
    unsigned int i;
5705
0
5706
0
    for (i = 0; i < length; i++) {
5707
0
        *(out++) = hextable[in[i] >> 4];
5708
0
        *(out++) = hextable[in[i] & 15];
5709
0
    }
5710
0
}
5711
#endif
5712
5713
/* Called from ssl3_SendClientKeyExchange(). */
5714
static SECStatus
5715
ssl3_SendRSAClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
5716
0
{
5717
0
    PK11SymKey *pms = NULL;
5718
0
    SECStatus rv = SECFailure;
5719
0
    SECItem enc_pms = { siBuffer, NULL, 0 };
5720
0
    PRBool isTLS;
5721
0
5722
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5723
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5724
0
5725
0
    /* Generate the pre-master secret ...  */
5726
0
    ssl_GetSpecWriteLock(ss);
5727
0
    isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
5728
0
5729
0
    pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
5730
0
    ssl_ReleaseSpecWriteLock(ss);
5731
0
    if (pms == NULL) {
5732
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5733
0
        goto loser;
5734
0
    }
5735
0
5736
0
    /* Get the wrapped (encrypted) pre-master secret, enc_pms */
5737
0
    unsigned int svrPubKeyBits = SECKEY_PublicKeyStrengthInBits(svrPubKey);
5738
0
    enc_pms.len = (svrPubKeyBits + 7) / 8;
5739
0
    /* Check that the RSA key isn't larger than 8k bit. */
5740
0
    if (svrPubKeyBits > SSL_MAX_RSA_KEY_BITS) {
5741
0
        (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
5742
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5743
0
        goto loser;
5744
0
    }
5745
0
    enc_pms.data = (unsigned char *)PORT_Alloc(enc_pms.len);
5746
0
    if (enc_pms.data == NULL) {
5747
0
        goto loser; /* err set by PORT_Alloc */
5748
0
    }
5749
0
5750
0
    /* Wrap pre-master secret in server's public key. */
5751
0
    rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
5752
0
    if (rv != SECSuccess) {
5753
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5754
0
        goto loser;
5755
0
    }
5756
0
5757
#ifdef TRACE
5758
    if (ssl_trace >= 100) {
5759
        SECStatus extractRV = PK11_ExtractKeyValue(pms);
5760
        if (extractRV == SECSuccess) {
5761
            SECItem *keyData = PK11_GetKeyData(pms);
5762
            if (keyData && keyData->data && keyData->len) {
5763
                ssl_PrintBuf(ss, "Pre-Master Secret",
5764
                             keyData->data, keyData->len);
5765
            }
5766
        }
5767
    }
5768
#endif
5769
5770
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
5771
0
                                    isTLS ? enc_pms.len + 2
5772
0
                                          : enc_pms.len);
5773
0
    if (rv != SECSuccess) {
5774
0
        goto loser; /* err set by ssl3_AppendHandshake* */
5775
0
    }
5776
0
    if (isTLS) {
5777
0
        rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
5778
0
    } else {
5779
0
        rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
5780
0
    }
5781
0
    if (rv != SECSuccess) {
5782
0
        goto loser; /* err set by ssl3_AppendHandshake* */
5783
0
    }
5784
0
5785
0
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
5786
0
    PK11_FreeSymKey(pms);
5787
0
    pms = NULL;
5788
0
5789
0
    if (rv != SECSuccess) {
5790
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5791
0
        goto loser;
5792
0
    }
5793
0
5794
0
    rv = SECSuccess;
5795
0
5796
0
loser:
5797
0
    if (enc_pms.data != NULL) {
5798
0
        PORT_Free(enc_pms.data);
5799
0
    }
5800
0
    if (pms != NULL) {
5801
0
        PK11_FreeSymKey(pms);
5802
0
    }
5803
0
    return rv;
5804
0
}
5805
5806
/* DH shares need to be padded to the size of their prime.  Some implementations
5807
 * require this.  TLS 1.3 also requires this. */
5808
SECStatus
5809
ssl_AppendPaddedDHKeyShare(sslBuffer *buf, const SECKEYPublicKey *pubKey,
5810
                           PRBool appendLength)
5811
0
{
5812
0
    SECStatus rv;
5813
0
    unsigned int pad = pubKey->u.dh.prime.len - pubKey->u.dh.publicValue.len;
5814
0
5815
0
    if (appendLength) {
5816
0
        rv = sslBuffer_AppendNumber(buf, pubKey->u.dh.prime.len, 2);
5817
0
        if (rv != SECSuccess) {
5818
0
            return rv;
5819
0
        }
5820
0
    }
5821
0
    while (pad) {
5822
0
        rv = sslBuffer_AppendNumber(buf, 0, 1);
5823
0
        if (rv != SECSuccess) {
5824
0
            return rv;
5825
0
        }
5826
0
        --pad;
5827
0
    }
5828
0
    rv = sslBuffer_Append(buf, pubKey->u.dh.publicValue.data,
5829
0
                          pubKey->u.dh.publicValue.len);
5830
0
    if (rv != SECSuccess) {
5831
0
        return rv;
5832
0
    }
5833
0
    return SECSuccess;
5834
0
}
5835
5836
/* Called from ssl3_SendClientKeyExchange(). */
5837
static SECStatus
5838
ssl3_SendDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
5839
0
{
5840
0
    PK11SymKey *pms = NULL;
5841
0
    SECStatus rv;
5842
0
    PRBool isTLS;
5843
0
    CK_MECHANISM_TYPE target;
5844
0
5845
0
    const ssl3DHParams *params;
5846
0
    ssl3DHParams customParams;
5847
0
    const sslNamedGroupDef *groupDef;
5848
0
    static const sslNamedGroupDef customGroupDef = {
5849
0
        ssl_grp_ffdhe_custom, 0, ssl_kea_dh, SEC_OID_TLS_DHE_CUSTOM, PR_FALSE
5850
0
    };
5851
0
    sslEphemeralKeyPair *keyPair = NULL;
5852
0
    SECKEYPublicKey *pubKey;
5853
0
    PRUint8 dhData[SSL_MAX_DH_KEY_BITS / 8 + 2];
5854
0
    sslBuffer dhBuf = SSL_BUFFER(dhData);
5855
0
5856
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5857
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5858
0
5859
0
    isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
5860
0
5861
0
    /* Copy DH parameters from server key */
5862
0
5863
0
    if (SECKEY_GetPublicKeyType(svrPubKey) != dhKey) {
5864
0
        PORT_SetError(SEC_ERROR_BAD_KEY);
5865
0
        return SECFailure;
5866
0
    }
5867
0
5868
0
    /* Work out the parameters. */
5869
0
    rv = ssl_ValidateDHENamedGroup(ss, &svrPubKey->u.dh.prime,
5870
0
                                   &svrPubKey->u.dh.base,
5871
0
                                   &groupDef, &params);
5872
0
    if (rv != SECSuccess) {
5873
0
        /* If we require named groups, we will have already validated the group
5874
0
         * in ssl_HandleDHServerKeyExchange() */
5875
0
        PORT_Assert(!ss->opt.requireDHENamedGroups &&
5876
0
                    !ss->xtnData.peerSupportsFfdheGroups);
5877
0
5878
0
        customParams.name = ssl_grp_ffdhe_custom;
5879
0
        customParams.prime.data = svrPubKey->u.dh.prime.data;
5880
0
        customParams.prime.len = svrPubKey->u.dh.prime.len;
5881
0
        customParams.base.data = svrPubKey->u.dh.base.data;
5882
0
        customParams.base.len = svrPubKey->u.dh.base.len;
5883
0
        params = &customParams;
5884
0
        groupDef = &customGroupDef;
5885
0
    }
5886
0
    ss->sec.keaGroup = groupDef;
5887
0
5888
0
    rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
5889
0
    if (rv != SECSuccess) {
5890
0
        ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
5891
0
        goto loser;
5892
0
    }
5893
0
    pubKey = keyPair->keys->pubKey;
5894
0
    PRINT_BUF(50, (ss, "DH public value:",
5895
0
                   pubKey->u.dh.publicValue.data,
5896
0
                   pubKey->u.dh.publicValue.len));
5897
0
5898
0
    if (isTLS)
5899
0
        target = CKM_TLS_MASTER_KEY_DERIVE_DH;
5900
0
    else
5901
0
        target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
5902
0
5903
0
    /* Determine the PMS */
5904
0
    pms = PK11_PubDerive(keyPair->keys->privKey, svrPubKey,
5905
0
                         PR_FALSE, NULL, NULL, CKM_DH_PKCS_DERIVE,
5906
0
                         target, CKA_DERIVE, 0, NULL);
5907
0
5908
0
    if (pms == NULL) {
5909
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5910
0
        goto loser;
5911
0
    }
5912
0
5913
0
    /* Note: send the DH share padded to avoid triggering bugs. */
5914
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
5915
0
                                    params->prime.len + 2);
5916
0
    if (rv != SECSuccess) {
5917
0
        goto loser; /* err set by ssl3_AppendHandshake* */
5918
0
    }
5919
0
    rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE);
5920
0
    if (rv != SECSuccess) {
5921
0
        goto loser; /* err set by ssl_AppendPaddedDHKeyShare */
5922
0
    }
5923
0
    rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
5924
0
    if (rv != SECSuccess) {
5925
0
        goto loser; /* err set by ssl3_AppendBufferToHandshake */
5926
0
    }
5927
0
5928
0
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
5929
0
    if (rv != SECSuccess) {
5930
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
5931
0
        goto loser;
5932
0
    }
5933
0
5934
0
    sslBuffer_Clear(&dhBuf);
5935
0
    PK11_FreeSymKey(pms);
5936
0
    ssl_FreeEphemeralKeyPair(keyPair);
5937
0
    return SECSuccess;
5938
0
5939
0
loser:
5940
0
    if (pms)
5941
0
        PK11_FreeSymKey(pms);
5942
0
    if (keyPair)
5943
0
        ssl_FreeEphemeralKeyPair(keyPair);
5944
0
    sslBuffer_Clear(&dhBuf);
5945
0
    return SECFailure;
5946
0
}
5947
5948
/* Called from ssl3_HandleServerHelloDone(). */
5949
static SECStatus
5950
ssl3_SendClientKeyExchange(sslSocket *ss)
5951
0
{
5952
0
    SECKEYPublicKey *serverKey = NULL;
5953
0
    SECStatus rv = SECFailure;
5954
0
5955
0
    SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
5956
0
                SSL_GETPID(), ss->fd));
5957
0
5958
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5959
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5960
0
5961
0
    if (ss->sec.peerKey == NULL) {
5962
0
        serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
5963
0
        if (serverKey == NULL) {
5964
0
            ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
5965
0
            return SECFailure;
5966
0
        }
5967
0
    } else {
5968
0
        serverKey = ss->sec.peerKey;
5969
0
        ss->sec.peerKey = NULL; /* we're done with it now */
5970
0
    }
5971
0
5972
0
    ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
5973
0
    ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
5974
0
5975
0
    switch (ss->ssl3.hs.kea_def->exchKeyType) {
5976
0
        case ssl_kea_rsa:
5977
0
            rv = ssl3_SendRSAClientKeyExchange(ss, serverKey);
5978
0
            break;
5979
0
5980
0
        case ssl_kea_dh:
5981
0
            rv = ssl3_SendDHClientKeyExchange(ss, serverKey);
5982
0
            break;
5983
0
5984
0
        case ssl_kea_ecdh:
5985
0
            rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
5986
0
            break;
5987
0
5988
0
        default:
5989
0
            PORT_Assert(0);
5990
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5991
0
            break;
5992
0
    }
5993
0
5994
0
    SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
5995
0
                SSL_GETPID(), ss->fd));
5996
0
5997
0
    SECKEY_DestroyPublicKey(serverKey);
5998
0
    return rv; /* err code already set. */
5999
0
}
6000
6001
/* Used by ssl_PickSignatureScheme(). */
6002
static PRBool
6003
ssl_CanUseSignatureScheme(SSLSignatureScheme scheme,
6004
                          const SSLSignatureScheme *peerSchemes,
6005
                          unsigned int peerSchemeCount,
6006
                          PRBool requireSha1,
6007
                          PRBool slotDoesPss)
6008
0
{
6009
0
    SSLHashType hashType;
6010
0
    SECOidTag hashOID;
6011
0
    PRUint32 policy;
6012
0
    unsigned int i;
6013
0
6014
0
    /* Skip RSA-PSS schemes when the certificate's private key slot does
6015
0
     * not support this signature mechanism. */
6016
0
    if (ssl_IsRsaPssSignatureScheme(scheme) && !slotDoesPss) {
6017
0
        return PR_FALSE;
6018
0
    }
6019
0
6020
0
    hashType = ssl_SignatureSchemeToHashType(scheme);
6021
0
    if (requireSha1 && (hashType != ssl_hash_sha1)) {
6022
0
        return PR_FALSE;
6023
0
    }
6024
0
    hashOID = ssl3_HashTypeToOID(hashType);
6025
0
    if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) &&
6026
0
        !(policy & NSS_USE_ALG_IN_SSL_KX)) {
6027
0
        return PR_FALSE;
6028
0
    }
6029
0
6030
0
    for (i = 0; i < peerSchemeCount; i++) {
6031
0
        if (peerSchemes[i] == scheme) {
6032
0
            return PR_TRUE;
6033
0
        }
6034
0
    }
6035
0
    return PR_FALSE;
6036
0
}
6037
6038
SECStatus
6039
ssl_PickSignatureScheme(sslSocket *ss,
6040
                        CERTCertificate *cert,
6041
                        SECKEYPublicKey *pubKey,
6042
                        SECKEYPrivateKey *privKey,
6043
                        const SSLSignatureScheme *peerSchemes,
6044
                        unsigned int peerSchemeCount,
6045
                        PRBool requireSha1)
6046
0
{
6047
0
    unsigned int i;
6048
0
    PK11SlotInfo *slot;
6049
0
    PRBool slotDoesPss;
6050
0
    PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
6051
0
    SECStatus rv;
6052
0
    SSLSignatureScheme scheme;
6053
0
    SECOidTag spkiOid;
6054
0
6055
0
    /* We can't require SHA-1 in TLS 1.3. */
6056
0
    PORT_Assert(!(requireSha1 && isTLS13));
6057
0
    if (!pubKey || !privKey) {
6058
0
        PORT_Assert(0);
6059
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6060
0
        return SECFailure;
6061
0
    }
6062
0
6063
0
    slot = PK11_GetSlotFromPrivateKey(privKey);
6064
0
    if (!slot) {
6065
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6066
0
        return SECFailure;
6067
0
    }
6068
0
    slotDoesPss = PK11_DoesMechanism(slot, auth_alg_defs[ssl_auth_rsa_pss]);
6069
0
    PK11_FreeSlot(slot);
6070
0
6071
0
    /* If the certificate SPKI indicates a single scheme, don't search. */
6072
0
    rv = ssl_SignatureSchemeFromSpki(&cert->subjectPublicKeyInfo,
6073
0
                                     isTLS13, &scheme);
6074
0
    if (rv != SECSuccess) {
6075
0
        return SECFailure;
6076
0
    }
6077
0
    if (scheme != ssl_sig_none) {
6078
0
        if (!ssl_SignatureSchemeEnabled(ss, scheme) ||
6079
0
            !ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
6080
0
                                       requireSha1, slotDoesPss)) {
6081
0
            PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
6082
0
            return SECFailure;
6083
0
        }
6084
0
        ss->ssl3.hs.signatureScheme = scheme;
6085
0
        return SECSuccess;
6086
0
    }
6087
0
6088
0
    spkiOid = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm);
6089
0
6090
0
    /* Now we have to search based on the key type. Go through our preferred
6091
0
     * schemes in order and find the first that can be used. */
6092
0
    for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
6093
0
        scheme = ss->ssl3.signatureSchemes[i];
6094
0
6095
0
        if (ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13) &&
6096
0
            ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
6097
0
                                      requireSha1, slotDoesPss)) {
6098
0
            ss->ssl3.hs.signatureScheme = scheme;
6099
0
            return SECSuccess;
6100
0
        }
6101
0
    }
6102
0
6103
0
    PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
6104
0
    return SECFailure;
6105
0
}
6106
6107
static SECStatus
6108
ssl_PickFallbackSignatureScheme(sslSocket *ss, SECKEYPublicKey *pubKey)
6109
0
{
6110
0
    PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
6111
0
6112
0
    switch (SECKEY_GetPublicKeyType(pubKey)) {
6113
0
        case rsaKey:
6114
0
            if (isTLS12) {
6115
0
                ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1;
6116
0
            } else {
6117
0
                ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1md5;
6118
0
            }
6119
0
            break;
6120
0
        case ecKey:
6121
0
            ss->ssl3.hs.signatureScheme = ssl_sig_ecdsa_sha1;
6122
0
            break;
6123
0
        case dsaKey:
6124
0
            ss->ssl3.hs.signatureScheme = ssl_sig_dsa_sha1;
6125
0
            break;
6126
0
        default:
6127
0
            PORT_Assert(0);
6128
0
            PORT_SetError(SEC_ERROR_INVALID_KEY);
6129
0
            return SECFailure;
6130
0
    }
6131
0
    return SECSuccess;
6132
0
}
6133
6134
/* ssl3_PickServerSignatureScheme selects a signature scheme for signing the
6135
 * handshake.  Most of this is determined by the key pair we are using.
6136
 * Prior to TLS 1.2, the MD5/SHA1 combination is always used. With TLS 1.2, a
6137
 * client may advertise its support for signature and hash combinations. */
6138
static SECStatus
6139
ssl3_PickServerSignatureScheme(sslSocket *ss)
6140
0
{
6141
0
    const sslServerCert *cert = ss->sec.serverCert;
6142
0
    PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
6143
0
6144
0
    if (!isTLS12 || !ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) {
6145
0
        /* If the client didn't provide any signature_algorithms extension then
6146
0
         * we can assume that they support SHA-1: RFC5246, Section 7.4.1.4.1. */
6147
0
        return ssl_PickFallbackSignatureScheme(ss, cert->serverKeyPair->pubKey);
6148
0
    }
6149
0
6150
0
    /* Sets error code, if needed. */
6151
0
    return ssl_PickSignatureScheme(ss, cert->serverCert,
6152
0
                                   cert->serverKeyPair->pubKey,
6153
0
                                   cert->serverKeyPair->privKey,
6154
0
                                   ss->xtnData.sigSchemes,
6155
0
                                   ss->xtnData.numSigSchemes,
6156
0
                                   PR_FALSE /* requireSha1 */);
6157
0
}
6158
6159
static SECStatus
6160
ssl_PickClientSignatureScheme(sslSocket *ss, const SSLSignatureScheme *schemes,
6161
                              unsigned int numSchemes)
6162
0
{
6163
0
    SECKEYPrivateKey *privKey = ss->ssl3.clientPrivateKey;
6164
0
    SECStatus rv;
6165
0
    PRBool isTLS13 = (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
6166
0
    SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(ss->ssl3.clientCertificate);
6167
0
6168
0
    PORT_Assert(pubKey);
6169
0
6170
0
    if (!isTLS13 && numSchemes == 0) {
6171
0
        /* If the server didn't provide any signature algorithms
6172
0
         * then let's assume they support SHA-1. */
6173
0
        rv = ssl_PickFallbackSignatureScheme(ss, pubKey);
6174
0
        SECKEY_DestroyPublicKey(pubKey);
6175
0
        return rv;
6176
0
    }
6177
0
6178
0
    PORT_Assert(schemes && numSchemes > 0);
6179
0
6180
0
    if (!isTLS13 &&
6181
0
        (SECKEY_GetPublicKeyType(pubKey) == rsaKey ||
6182
0
         SECKEY_GetPublicKeyType(pubKey) == dsaKey) &&
6183
0
        SECKEY_PublicKeyStrengthInBits(pubKey) <= 1024) {
6184
0
        /* If the key is a 1024-bit RSA or DSA key, assume conservatively that
6185
0
         * it may be unable to sign SHA-256 hashes. This is the case for older
6186
0
         * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and
6187
0
         * older, DSA key size is at most 1024 bits and the hash function must
6188
0
         * be SHA-1.
6189
0
         */
6190
0
        rv = ssl_PickSignatureScheme(ss, ss->ssl3.clientCertificate,
6191
0
                                     pubKey, privKey, schemes, numSchemes,
6192
0
                                     PR_TRUE /* requireSha1 */);
6193
0
        if (rv == SECSuccess) {
6194
0
            SECKEY_DestroyPublicKey(pubKey);
6195
0
            return SECSuccess;
6196
0
        }
6197
0
        /* If this fails, that's because the peer doesn't advertise SHA-1,
6198
0
         * so fall back to the full negotiation. */
6199
0
    }
6200
0
    rv = ssl_PickSignatureScheme(ss, ss->ssl3.clientCertificate,
6201
0
                                 pubKey, privKey, schemes, numSchemes,
6202
0
                                 PR_FALSE /* requireSha1 */);
6203
0
    SECKEY_DestroyPublicKey(pubKey);
6204
0
    return rv;
6205
0
}
6206
6207
/* Called from ssl3_HandleServerHelloDone(). */
6208
static SECStatus
6209
ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
6210
0
{
6211
0
    SECStatus rv = SECFailure;
6212
0
    PRBool isTLS12;
6213
0
    SECItem buf = { siBuffer, NULL, 0 };
6214
0
    SSL3Hashes hashes;
6215
0
    unsigned int len;
6216
0
    SSLHashType hashAlg;
6217
0
6218
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6219
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6220
0
6221
0
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
6222
0
                SSL_GETPID(), ss->fd));
6223
0
6224
0
    ssl_GetSpecReadLock(ss);
6225
0
6226
0
    if (ss->ssl3.hs.hashType == handshake_hash_record) {
6227
0
        hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
6228
0
    } else {
6229
0
        /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
6230
0
        hashAlg = ssl_hash_none;
6231
0
    }
6232
0
    if (ss->ssl3.hs.hashType == handshake_hash_record &&
6233
0
        hashAlg != ssl3_GetSuitePrfHash(ss)) {
6234
0
        rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
6235
0
                                       ss->ssl3.hs.messages.len,
6236
0
                                       hashAlg, &hashes);
6237
0
        if (rv != SECSuccess) {
6238
0
            ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
6239
0
        }
6240
0
    } else {
6241
0
        rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
6242
0
    }
6243
0
    ssl_ReleaseSpecReadLock(ss);
6244
0
    if (rv != SECSuccess) {
6245
0
        goto done; /* err code was set by ssl3_ComputeHandshakeHash(es) */
6246
0
    }
6247
0
6248
0
    isTLS12 = (PRBool)(ss->version == SSL_LIBRARY_VERSION_TLS_1_2);
6249
0
    PORT_Assert(ss->version <= SSL_LIBRARY_VERSION_TLS_1_2);
6250
0
6251
0
    rv = ssl3_SignHashes(ss, &hashes, privKey, &buf);
6252
0
    if (rv == SECSuccess && !ss->sec.isServer) {
6253
0
        /* Remember the info about the slot that did the signing.
6254
0
        ** Later, when doing an SSL restart handshake, verify this.
6255
0
        ** These calls are mere accessors, and can't fail.
6256
0
        */
6257
0
        PK11SlotInfo *slot;
6258
0
        sslSessionID *sid = ss->sec.ci.sid;
6259
0
6260
0
        slot = PK11_GetSlotFromPrivateKey(privKey);
6261
0
        sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
6262
0
        sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
6263
0
        sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
6264
0
        sid->u.ssl3.clAuthValid = PR_TRUE;
6265
0
        PK11_FreeSlot(slot);
6266
0
    }
6267
0
    if (rv != SECSuccess) {
6268
0
        goto done; /* err code was set by ssl3_SignHashes */
6269
0
    }
6270
0
6271
0
    len = buf.len + 2 + (isTLS12 ? 2 : 0);
6272
0
6273
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len);
6274
0
    if (rv != SECSuccess) {
6275
0
        goto done; /* error code set by AppendHandshake */
6276
0
    }
6277
0
    if (isTLS12) {
6278
0
        rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
6279
0
        if (rv != SECSuccess) {
6280
0
            goto done; /* err set by AppendHandshake. */
6281
0
        }
6282
0
    }
6283
0
    rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
6284
0
    if (rv != SECSuccess) {
6285
0
        goto done; /* error code set by AppendHandshake */
6286
0
    }
6287
0
6288
0
done:
6289
0
    if (buf.data)
6290
0
        PORT_Free(buf.data);
6291
0
    return rv;
6292
0
}
6293
6294
/* Once a cipher suite has been selected, make sure that the necessary secondary
6295
 * information is properly set. */
6296
SECStatus
6297
ssl3_SetupCipherSuite(sslSocket *ss, PRBool initHashes)
6298
0
{
6299
0
    ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
6300
0
    if (!ss->ssl3.hs.suite_def) {
6301
0
        PORT_Assert(0);
6302
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6303
0
        return SECFailure;
6304
0
    }
6305
0
6306
0
    ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg];
6307
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite;
6308
0
6309
0
    if (!initHashes) {
6310
0
        return SECSuccess;
6311
0
    }
6312
0
    /* Now we have a cipher suite, initialize the handshake hashes. */
6313
0
    return ssl3_InitHandshakeHashes(ss);
6314
0
}
6315
6316
SECStatus
6317
ssl_ClientSetCipherSuite(sslSocket *ss, SSL3ProtocolVersion version,
6318
                         ssl3CipherSuite suite, PRBool initHashes)
6319
0
{
6320
0
    unsigned int i;
6321
0
    if (ssl3_config_match_init(ss) == 0) {
6322
0
        PORT_Assert(PR_FALSE);
6323
0
        return SECFailure;
6324
0
    }
6325
0
    for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
6326
0
        ssl3CipherSuiteCfg *suiteCfg = &ss->cipherSuites[i];
6327
0
        if (suite == suiteCfg->cipher_suite) {
6328
0
            SSLVersionRange vrange = { version, version };
6329
0
            if (!config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) {
6330
0
                /* config_match already checks whether the cipher suite is
6331
0
                 * acceptable for the version, but the check is repeated here
6332
0
                 * in order to give a more precise error code. */
6333
0
                if (!ssl3_CipherSuiteAllowedForVersionRange(suite, &vrange)) {
6334
0
                    PORT_SetError(SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION);
6335
0
                } else {
6336
0
                    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
6337
0
                }
6338
0
                return SECFailure;
6339
0
            }
6340
0
            break;
6341
0
        }
6342
0
    }
6343
0
    if (i >= ssl_V3_SUITES_IMPLEMENTED) {
6344
0
        PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
6345
0
        return SECFailure;
6346
0
    }
6347
0
6348
0
    /* Don't let the server change its mind. */
6349
0
    if (ss->ssl3.hs.helloRetry && suite != ss->ssl3.hs.cipher_suite) {
6350
0
        (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
6351
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
6352
0
        return SECFailure;
6353
0
    }
6354
0
6355
0
    ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)suite;
6356
0
    return ssl3_SetupCipherSuite(ss, initHashes);
6357
0
}
6358
6359
/* Check that session ID we received from the server, if any, matches our
6360
 * expectations, depending on whether we're in compat mode and whether we
6361
 * negotiated TLS 1.3+ or TLS 1.2-.
6362
 */
6363
static PRBool
6364
ssl_CheckServerSessionIdCorrectness(sslSocket *ss, SECItem *sidBytes)
6365
0
{
6366
0
    sslSessionID *sid = ss->sec.ci.sid;
6367
0
    PRBool sidMatch = PR_FALSE;
6368
0
    PRBool sentFakeSid = PR_FALSE;
6369
0
    PRBool sentRealSid = sid && sid->version < SSL_LIBRARY_VERSION_TLS_1_3;
6370
0
6371
0
    /* If attempting to resume a TLS 1.2 connection, the session ID won't be a
6372
0
     * fake. Check for the real value. */
6373
0
    if (sentRealSid) {
6374
0
        sidMatch = (sidBytes->len == sid->u.ssl3.sessionIDLength) &&
6375
0
                   PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len) == 0;
6376
0
    } else {
6377
0
        /* Otherwise, the session ID was a fake if TLS 1.3 compat mode is
6378
0
         * enabled.  If so, check for the fake value. */
6379
0
        sentFakeSid = ss->opt.enableTls13CompatMode && !IS_DTLS(ss);
6380
0
        if (sentFakeSid && sidBytes->len == SSL3_SESSIONID_BYTES) {
6381
0
            PRUint8 buf[SSL3_SESSIONID_BYTES];
6382
0
            ssl_MakeFakeSid(ss, buf);
6383
0
            sidMatch = PORT_Memcmp(buf, sidBytes->data, sidBytes->len) == 0;
6384
0
        }
6385
0
    }
6386
0
6387
0
    /* TLS 1.2: Session ID shouldn't match if we sent a fake. */
6388
0
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
6389
0
        if (sentFakeSid) {
6390
0
            return !sidMatch;
6391
0
        }
6392
0
        return PR_TRUE;
6393
0
    }
6394
0
6395
0
    /* TLS 1.3: We sent a session ID.  The server's should match. */
6396
0
    if (!IS_DTLS(ss) && (sentRealSid || sentFakeSid)) {
6397
0
        return sidMatch;
6398
0
    }
6399
0
6400
0
    /* TLS 1.3 (no SID)/DTLS 1.3: The server shouldn't send a session ID. */
6401
0
    return sidBytes->len == 0;
6402
0
}
6403
6404
static SECStatus
6405
ssl_CheckServerRandom(sslSocket *ss)
6406
0
{
6407
0
    /* Check the ServerHello.random per [RFC 8446 Section 4.1.3].
6408
0
     *
6409
0
     * TLS 1.3 clients receiving a ServerHello indicating TLS 1.2 or below
6410
0
     * MUST check that the last 8 bytes are not equal to either of these
6411
0
     * values.  TLS 1.2 clients SHOULD also check that the last 8 bytes are
6412
0
     * not equal to the second value if the ServerHello indicates TLS 1.1 or
6413
0
     * below.  If a match is found, the client MUST abort the handshake with
6414
0
     * an "illegal_parameter" alert.
6415
0
     */
6416
0
    SSL3ProtocolVersion checkVersion =
6417
0
        ss->ssl3.downgradeCheckVersion ? ss->ssl3.downgradeCheckVersion
6418
0
                                       : ss->vrange.max;
6419
0
6420
0
    if (checkVersion >= SSL_LIBRARY_VERSION_TLS_1_2 &&
6421
0
        checkVersion > ss->version) {
6422
0
        /* Both sections use the same sentinel region. */
6423
0
        PRUint8 *downgrade_sentinel =
6424
0
            ss->ssl3.hs.server_random +
6425
0
            SSL3_RANDOM_LENGTH - sizeof(tls13_downgrade_random);
6426
0
        if (!PORT_Memcmp(downgrade_sentinel,
6427
0
                         tls13_downgrade_random,
6428
0
                         sizeof(tls13_downgrade_random)) ||
6429
0
            !PORT_Memcmp(downgrade_sentinel,
6430
0
                         tls12_downgrade_random,
6431
0
                         sizeof(tls12_downgrade_random))) {
6432
0
            return SECFailure;
6433
0
        }
6434
0
    }
6435
0
6436
0
    return SECSuccess;
6437
0
}
6438
6439
/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6440
 * ssl3 ServerHello message.
6441
 * Caller must hold Handshake and RecvBuf locks.
6442
 */
6443
static SECStatus
6444
ssl3_HandleServerHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
6445
0
{
6446
0
    PRUint32 cipher;
6447
0
    int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6448
0
    PRUint32 compression;
6449
0
    SECStatus rv;
6450
0
    SECItem sidBytes = { siBuffer, NULL, 0 };
6451
0
    PRBool isHelloRetry;
6452
0
    SSL3AlertDescription desc = illegal_parameter;
6453
0
    const PRUint8 *savedMsg = b;
6454
0
    const PRUint32 savedLength = length;
6455
0
6456
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
6457
0
                SSL_GETPID(), ss->fd));
6458
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
6459
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6460
0
6461
0
    if (ss->ssl3.hs.ws != wait_server_hello) {
6462
0
        errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
6463
0
        desc = unexpected_message;
6464
0
        goto alert_loser;
6465
0
    }
6466
0
6467
0
    /* clean up anything left from previous handshake. */
6468
0
    if (ss->ssl3.clientCertChain != NULL) {
6469
0
        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
6470
0
        ss->ssl3.clientCertChain = NULL;
6471
0
    }
6472
0
    if (ss->ssl3.clientCertificate != NULL) {
6473
0
        CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6474
0
        ss->ssl3.clientCertificate = NULL;
6475
0
    }
6476
0
    if (ss->ssl3.clientPrivateKey != NULL) {
6477
0
        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6478
0
        ss->ssl3.clientPrivateKey = NULL;
6479
0
    }
6480
0
6481
0
    /* Note that if the server selects TLS 1.3, this will set the version to TLS
6482
0
     * 1.2.  We will amend that once all other fields have been read. */
6483
0
    rv = ssl_ClientReadVersion(ss, &b, &length, &ss->version);
6484
0
    if (rv != SECSuccess) {
6485
0
        goto loser; /* alert has been sent */
6486
0
    }
6487
0
6488
0
    rv = ssl3_ConsumeHandshake(
6489
0
        ss, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
6490
0
    if (rv != SECSuccess) {
6491
0
        goto loser; /* alert has been sent */
6492
0
    }
6493
0
    isHelloRetry = !PORT_Memcmp(ss->ssl3.hs.server_random,
6494
0
                                ssl_hello_retry_random, SSL3_RANDOM_LENGTH);
6495
0
6496
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
6497
0
    if (rv != SECSuccess) {
6498
0
        goto loser; /* alert has been sent */
6499
0
    }
6500
0
    if (sidBytes.len > SSL3_SESSIONID_BYTES) {
6501
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_0)
6502
0
            desc = decode_error;
6503
0
        goto alert_loser; /* malformed. */
6504
0
    }
6505
0
6506
0
    /* Read the cipher suite. */
6507
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &cipher, 2, &b, &length);
6508
0
    if (rv != SECSuccess) {
6509
0
        goto loser; /* alert has been sent */
6510
0
    }
6511
0
6512
0
    /* Compression method. */
6513
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &compression, 1, &b, &length);
6514
0
    if (rv != SECSuccess) {
6515
0
        goto loser; /* alert has been sent */
6516
0
    }
6517
0
    if (compression != ssl_compression_null) {
6518
0
        desc = illegal_parameter;
6519
0
        errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6520
0
        goto alert_loser;
6521
0
    }
6522
0
6523
0
    /* Parse extensions. */
6524
0
    if (length != 0) {
6525
0
        PRUint32 extensionLength;
6526
0
        rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
6527
0
        if (rv != SECSuccess) {
6528
0
            goto loser; /* alert already sent */
6529
0
        }
6530
0
        if (extensionLength != length) {
6531
0
            desc = decode_error;
6532
0
            goto alert_loser;
6533
0
        }
6534
0
        rv = ssl3_ParseExtensions(ss, &b, &length);
6535
0
        if (rv != SECSuccess) {
6536
0
            goto alert_loser; /* malformed */
6537
0
        }
6538
0
    }
6539
0
6540
0
    /* Read supported_versions if present. */
6541
0
    rv = tls13_ClientReadSupportedVersion(ss);
6542
0
    if (rv != SECSuccess) {
6543
0
        goto loser;
6544
0
    }
6545
0
6546
0
    PORT_Assert(!SSL_ALL_VERSIONS_DISABLED(&ss->vrange));
6547
0
    /* Check that the version is within the configured range. */
6548
0
    if (ss->vrange.min > ss->version || ss->vrange.max < ss->version) {
6549
0
        desc = (ss->version > SSL_LIBRARY_VERSION_3_0)
6550
0
                   ? protocol_version
6551
0
                   : handshake_failure;
6552
0
        errCode = SSL_ERROR_UNSUPPORTED_VERSION;
6553
0
        goto alert_loser;
6554
0
    }
6555
0
6556
0
    if (isHelloRetry && ss->ssl3.hs.helloRetry) {
6557
0
        SSL_TRC(3, ("%d: SSL3[%d]: received a second hello_retry_request",
6558
0
                    SSL_GETPID(), ss->fd));
6559
0
        desc = unexpected_message;
6560
0
        errCode = SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST;
6561
0
        goto alert_loser;
6562
0
    }
6563
0
6564
0
    /* The server didn't pick 1.3 although we either received a
6565
0
     * HelloRetryRequest, or we prepared to send early app data. */
6566
0
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
6567
0
        if (isHelloRetry || ss->ssl3.hs.helloRetry) {
6568
0
            /* SSL3_SendAlert() will uncache the SID. */
6569
0
            desc = illegal_parameter;
6570
0
            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6571
0
            goto alert_loser;
6572
0
        }
6573
0
        if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
6574
0
            /* SSL3_SendAlert() will uncache the SID. */
6575
0
            desc = illegal_parameter;
6576
0
            errCode = SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA;
6577
0
            goto alert_loser;
6578
0
        }
6579
0
    }
6580
0
6581
0
    /* Check that the server negotiated the same version as it did
6582
0
     * in the first handshake. This isn't really the best place for
6583
0
     * us to be getting this version number, but it's what we have.
6584
0
     * (1294697). */
6585
0
    if (ss->firstHsDone && (ss->version != ss->ssl3.crSpec->version)) {
6586
0
        desc = protocol_version;
6587
0
        errCode = SSL_ERROR_UNSUPPORTED_VERSION;
6588
0
        goto alert_loser;
6589
0
    }
6590
0
6591
0
    if (ss->opt.enableHelloDowngradeCheck
6592
0
#ifdef DTLS_1_3_DRAFT_VERSION
6593
0
        /* Disable this check while we are on draft DTLS 1.3 versions. */
6594
0
        && !IS_DTLS(ss)
6595
0
#endif
6596
0
            ) {
6597
0
        rv = ssl_CheckServerRandom(ss);
6598
0
        if (rv != SECSuccess) {
6599
0
            desc = illegal_parameter;
6600
0
            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6601
0
            goto alert_loser;
6602
0
        }
6603
0
    }
6604
0
6605
0
    /* Finally, now all the version-related checks have passed. */
6606
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
6607
0
    /* Update the write cipher spec to match the version. But not after
6608
0
     * HelloRetryRequest, because cwSpec might be a 0-RTT cipher spec,
6609
0
     * in which case this is a no-op. */
6610
0
    if (!ss->firstHsDone && !isHelloRetry) {
6611
0
        ssl_GetSpecWriteLock(ss);
6612
0
        ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
6613
0
        ssl_ReleaseSpecWriteLock(ss);
6614
0
    }
6615
0
6616
0
    /* Check that the session ID is as expected. */
6617
0
    if (!ssl_CheckServerSessionIdCorrectness(ss, &sidBytes)) {
6618
0
        desc = illegal_parameter;
6619
0
        errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6620
0
        goto alert_loser;
6621
0
    }
6622
0
6623
0
    /* Only initialize hashes if this isn't a Hello Retry. */
6624
0
    rv = ssl_ClientSetCipherSuite(ss, ss->version, cipher,
6625
0
                                  !isHelloRetry);
6626
0
    if (rv != SECSuccess) {
6627
0
        desc = illegal_parameter;
6628
0
        errCode = PORT_GetError();
6629
0
        goto alert_loser;
6630
0
    }
6631
0
6632
0
    dtls_ReceivedFirstMessageInFlight(ss);
6633
0
6634
0
    if (isHelloRetry) {
6635
0
        rv = tls13_HandleHelloRetryRequest(ss, savedMsg, savedLength);
6636
0
        if (rv != SECSuccess) {
6637
0
            goto loser;
6638
0
        }
6639
0
        return SECSuccess;
6640
0
    }
6641
0
6642
0
    rv = ssl3_HandleParsedExtensions(ss, ssl_hs_server_hello);
6643
0
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
6644
0
    if (rv != SECSuccess) {
6645
0
        goto alert_loser;
6646
0
    }
6647
0
6648
0
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_server_hello,
6649
0
                                  savedMsg, savedLength);
6650
0
    if (rv != SECSuccess) {
6651
0
        goto loser;
6652
0
    }
6653
0
6654
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
6655
0
        rv = tls13_HandleServerHelloPart2(ss);
6656
0
        if (rv != SECSuccess) {
6657
0
            errCode = PORT_GetError();
6658
0
            goto loser;
6659
0
        }
6660
0
    } else {
6661
0
        rv = ssl3_HandleServerHelloPart2(ss, &sidBytes, &errCode);
6662
0
        if (rv != SECSuccess)
6663
0
            goto loser;
6664
0
    }
6665
0
6666
0
    return SECSuccess;
6667
0
6668
0
alert_loser:
6669
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
6670
0
6671
0
loser:
6672
0
    /* Clean up the temporary pointer to the handshake buffer. */
6673
0
    ss->xtnData.signedCertTimestamps.len = 0;
6674
0
    ssl_MapLowLevelError(errCode);
6675
0
    return SECFailure;
6676
0
}
6677
6678
static SECStatus
6679
ssl3_UnwrapMasterSecretClient(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
6680
0
{
6681
0
    PK11SlotInfo *slot;
6682
0
    PK11SymKey *wrapKey;
6683
0
    CK_FLAGS keyFlags = 0;
6684
0
    SECItem wrappedMS = {
6685
0
        siBuffer,
6686
0
        sid->u.ssl3.keys.wrapped_master_secret,
6687
0
        sid->u.ssl3.keys.wrapped_master_secret_len
6688
0
    };
6689
0
6690
0
    /* unwrap master secret */
6691
0
    slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
6692
0
                             sid->u.ssl3.masterSlotID);
6693
0
    if (slot == NULL) {
6694
0
        return SECFailure;
6695
0
    }
6696
0
    if (!PK11_IsPresent(slot)) {
6697
0
        PK11_FreeSlot(slot);
6698
0
        return SECFailure;
6699
0
    }
6700
0
    wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
6701
0
                              sid->u.ssl3.masterWrapMech,
6702
0
                              sid->u.ssl3.masterWrapSeries,
6703
0
                              ss->pkcs11PinArg);
6704
0
    PK11_FreeSlot(slot);
6705
0
    if (wrapKey == NULL) {
6706
0
        return SECFailure;
6707
0
    }
6708
0
6709
0
    if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
6710
0
        keyFlags = CKF_SIGN | CKF_VERIFY;
6711
0
    }
6712
0
6713
0
    *ms = PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
6714
0
                                     NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
6715
0
                                     CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH, keyFlags);
6716
0
    PK11_FreeSymKey(wrapKey);
6717
0
    if (!*ms) {
6718
0
        return SECFailure;
6719
0
    }
6720
0
    return SECSuccess;
6721
0
}
6722
6723
static SECStatus
6724
ssl3_HandleServerHelloPart2(sslSocket *ss, const SECItem *sidBytes,
6725
                            int *retErrCode)
6726
0
{
6727
0
    SSL3AlertDescription desc = handshake_failure;
6728
0
    int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6729
0
    SECStatus rv;
6730
0
    PRBool sid_match;
6731
0
    sslSessionID *sid = ss->sec.ci.sid;
6732
0
6733
0
    if ((ss->opt.requireSafeNegotiation ||
6734
0
         (ss->firstHsDone && (ss->peerRequestedProtection ||
6735
0
                              ss->opt.enableRenegotiation ==
6736
0
                                  SSL_RENEGOTIATE_REQUIRES_XTN))) &&
6737
0
        !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
6738
0
        desc = handshake_failure;
6739
0
        errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
6740
0
                                  : SSL_ERROR_UNSAFE_NEGOTIATION;
6741
0
        goto alert_loser;
6742
0
    }
6743
0
6744
0
    /* Any errors after this point are not "malformed" errors. */
6745
0
    desc = handshake_failure;
6746
0
6747
0
    /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
6748
0
     * key exchange algorithm. */
6749
0
    rv = ssl3_SetupBothPendingCipherSpecs(ss);
6750
0
    if (rv != SECSuccess) {
6751
0
        goto alert_loser; /* error code is set. */
6752
0
    }
6753
0
6754
0
    /* We may or may not have sent a session id, we may get one back or
6755
0
     * not and if so it may match the one we sent.
6756
0
     * Attempt to restore the master secret to see if this is so...
6757
0
     * Don't consider failure to find a matching SID an error.
6758
0
     */
6759
0
    sid_match = (PRBool)(sidBytes->len > 0 &&
6760
0
                         sidBytes->len ==
6761
0
                             sid->u.ssl3.sessionIDLength &&
6762
0
                         !PORT_Memcmp(sid->u.ssl3.sessionID,
6763
0
                                      sidBytes->data, sidBytes->len));
6764
0
6765
0
    if (sid_match) {
6766
0
        if (sid->version != ss->version ||
6767
0
            sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
6768
0
            errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6769
0
            goto alert_loser;
6770
0
        }
6771
0
        do {
6772
0
            PK11SymKey *masterSecret;
6773
0
6774
0
            /* [draft-ietf-tls-session-hash-06; Section 5.3]
6775
0
             *
6776
0
             * o  If the original session did not use the "extended_master_secret"
6777
0
             *    extension but the new ServerHello contains the extension, the
6778
0
             *    client MUST abort the handshake.
6779
0
             */
6780
0
            if (!sid->u.ssl3.keys.extendedMasterSecretUsed &&
6781
0
                ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
6782
0
                errCode = SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET;
6783
0
                goto alert_loser;
6784
0
            }
6785
0
6786
0
            /*
6787
0
             *   o  If the original session used an extended master secret but the new
6788
0
             *      ServerHello does not contain the "extended_master_secret"
6789
0
             *      extension, the client SHOULD abort the handshake.
6790
0
             *
6791
0
             * TODO(ekr@rtfm.com): Add option to refuse to resume when EMS is not
6792
0
             * used at all (bug 1176526).
6793
0
             */
6794
0
            if (sid->u.ssl3.keys.extendedMasterSecretUsed &&
6795
0
                !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
6796
0
                errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
6797
0
                goto alert_loser;
6798
0
            }
6799
0
6800
0
            ss->sec.authType = sid->authType;
6801
0
            ss->sec.authKeyBits = sid->authKeyBits;
6802
0
            ss->sec.keaType = sid->keaType;
6803
0
            ss->sec.keaKeyBits = sid->keaKeyBits;
6804
0
            ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
6805
0
            ss->sec.signatureScheme = sid->sigScheme;
6806
0
6807
0
            rv = ssl3_UnwrapMasterSecretClient(ss, sid, &masterSecret);
6808
0
            if (rv != SECSuccess) {
6809
0
                break; /* not considered an error */
6810
0
            }
6811
0
6812
0
            /* Got a Match */
6813
0
            SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_hits);
6814
0
6815
0
            /* If we sent a session ticket, then this is a stateless resume. */
6816
0
            if (ss->xtnData.sentSessionTicketInClientHello)
6817
0
                SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_stateless_resumes);
6818
0
6819
0
            if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
6820
0
                ss->ssl3.hs.ws = wait_new_session_ticket;
6821
0
            else
6822
0
                ss->ssl3.hs.ws = wait_change_cipher;
6823
0
6824
0
            ss->ssl3.hs.isResuming = PR_TRUE;
6825
0
6826
0
            /* copy the peer cert from the SID */
6827
0
            if (sid->peerCert != NULL) {
6828
0
                ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
6829
0
            }
6830
0
6831
0
            /* We are re-using the old MS, so no need to derive again. */
6832
0
            rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE);
6833
0
            if (rv != SECSuccess) {
6834
0
                goto alert_loser; /* err code was set */
6835
0
            }
6836
0
            return SECSuccess;
6837
0
        } while (0);
6838
0
    }
6839
0
6840
0
    if (sid_match)
6841
0
        SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_not_ok);
6842
0
    else
6843
0
        SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_misses);
6844
0
6845
0
    /* We tried to resume a 1.3 session but the server negotiated 1.2. */
6846
0
    if (ss->statelessResume) {
6847
0
        PORT_Assert(sid->version == SSL_LIBRARY_VERSION_TLS_1_3);
6848
0
        PORT_Assert(ss->ssl3.hs.currentSecret);
6849
0
6850
0
        /* Reset resumption state, only used by 1.3 code. */
6851
0
        ss->statelessResume = PR_FALSE;
6852
0
6853
0
        /* Clear TLS 1.3 early data traffic key. */
6854
0
        PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
6855
0
        ss->ssl3.hs.currentSecret = NULL;
6856
0
    }
6857
0
6858
0
    /* throw the old one away */
6859
0
    sid->u.ssl3.keys.resumable = PR_FALSE;
6860
0
    ssl_UncacheSessionID(ss);
6861
0
    ssl_FreeSID(sid);
6862
0
6863
0
    /* get a new sid */
6864
0
    ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
6865
0
    if (sid == NULL) {
6866
0
        goto alert_loser; /* memory error is set. */
6867
0
    }
6868
0
6869
0
    sid->version = ss->version;
6870
0
    sid->u.ssl3.sessionIDLength = sidBytes->len;
6871
0
    if (sidBytes->len > 0) {
6872
0
        PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len);
6873
0
    }
6874
0
6875
0
    sid->u.ssl3.keys.extendedMasterSecretUsed =
6876
0
        ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
6877
0
6878
0
    /* Copy Signed Certificate Timestamps, if any. */
6879
0
    if (ss->xtnData.signedCertTimestamps.len) {
6880
0
        rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps,
6881
0
                              &ss->xtnData.signedCertTimestamps);
6882
0
        ss->xtnData.signedCertTimestamps.len = 0;
6883
0
        if (rv != SECSuccess)
6884
0
            goto loser;
6885
0
    }
6886
0
6887
0
    ss->ssl3.hs.isResuming = PR_FALSE;
6888
0
    if (ss->ssl3.hs.kea_def->authKeyType != ssl_auth_null) {
6889
0
        /* All current cipher suites other than those with ssl_auth_null (i.e.,
6890
0
         * (EC)DH_anon_* suites) require a certificate, so use that signal. */
6891
0
        ss->ssl3.hs.ws = wait_server_cert;
6892
0
    } else {
6893
0
        /* All the remaining cipher suites must be (EC)DH_anon_* and so
6894
0
         * must be ephemeral. Note, if we ever add PSK this might
6895
0
         * change. */
6896
0
        PORT_Assert(ss->ssl3.hs.kea_def->ephemeral);
6897
0
        ss->ssl3.hs.ws = wait_server_key;
6898
0
    }
6899
0
    return SECSuccess;
6900
0
6901
0
alert_loser:
6902
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
6903
0
6904
0
loser:
6905
0
    *retErrCode = errCode;
6906
0
    return SECFailure;
6907
0
}
6908
6909
static SECStatus
6910
ssl_HandleDHServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
6911
0
{
6912
0
    SECStatus rv;
6913
0
    int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
6914
0
    SSL3AlertDescription desc = illegal_parameter;
6915
0
    SSLHashType hashAlg;
6916
0
    PRBool isTLS = ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0;
6917
0
    SSLSignatureScheme sigScheme;
6918
0
6919
0
    SECItem dh_p = { siBuffer, NULL, 0 };
6920
0
    SECItem dh_g = { siBuffer, NULL, 0 };
6921
0
    SECItem dh_Ys = { siBuffer, NULL, 0 };
6922
0
    unsigned dh_p_bits;
6923
0
    unsigned dh_g_bits;
6924
0
    PRInt32 minDH;
6925
0
6926
0
    SSL3Hashes hashes;
6927
0
    SECItem signature = { siBuffer, NULL, 0 };
6928
0
    PLArenaPool *arena = NULL;
6929
0
    SECKEYPublicKey *peerKey = NULL;
6930
0
6931
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
6932
0
    if (rv != SECSuccess) {
6933
0
        goto loser; /* malformed. */
6934
0
    }
6935
0
6936
0
    rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH);
6937
0
    if (rv != SECSuccess || minDH <= 0) {
6938
0
        minDH = SSL_DH_MIN_P_BITS;
6939
0
    }
6940
0
    dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p);
6941
0
    if (dh_p_bits < (unsigned)minDH) {
6942
0
        errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
6943
0
        goto alert_loser;
6944
0
    }
6945
0
    if (dh_p_bits > SSL_MAX_DH_KEY_BITS) {
6946
0
        errCode = SSL_ERROR_DH_KEY_TOO_LONG;
6947
0
        goto alert_loser;
6948
0
    }
6949
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
6950
0
    if (rv != SECSuccess) {
6951
0
        goto loser; /* malformed. */
6952
0
    }
6953
0
    /* Abort if dh_g is 0, 1, or obviously too big. */
6954
0
    dh_g_bits = SECKEY_BigIntegerBitLength(&dh_g);
6955
0
    if (dh_g_bits > dh_p_bits || dh_g_bits <= 1) {
6956
0
        goto alert_loser;
6957
0
    }
6958
0
    if (ss->opt.requireDHENamedGroups) {
6959
0
        /* If we're doing named groups, make sure it's good. */
6960
0
        rv = ssl_ValidateDHENamedGroup(ss, &dh_p, &dh_g, NULL, NULL);
6961
0
        if (rv != SECSuccess) {
6962
0
            errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
6963
0
            goto alert_loser;
6964
0
        }
6965
0
    }
6966
0
6967
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
6968
0
    if (rv != SECSuccess) {
6969
0
        goto loser; /* malformed. */
6970
0
    }
6971
0
    if (!ssl_IsValidDHEShare(&dh_p, &dh_Ys)) {
6972
0
        errCode = SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE;
6973
0
        goto alert_loser;
6974
0
    }
6975
0
6976
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
6977
0
        rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
6978
0
        if (rv != SECSuccess) {
6979
0
            goto alert_loser; /* malformed or unsupported. */
6980
0
        }
6981
0
        rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme,
6982
0
                                                 ss->sec.peerCert);
6983
0
        if (rv != SECSuccess) {
6984
0
            goto alert_loser;
6985
0
        }
6986
0
        hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
6987
0
    } else {
6988
0
        /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
6989
0
        hashAlg = ssl_hash_none;
6990
0
        sigScheme = ssl_sig_none;
6991
0
    }
6992
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
6993
0
    if (rv != SECSuccess) {
6994
0
        goto loser; /* malformed. */
6995
0
    }
6996
0
    if (length != 0) {
6997
0
        if (isTLS) {
6998
0
            desc = decode_error;
6999
0
        }
7000
0
        goto alert_loser; /* malformed. */
7001
0
    }
7002
0
7003
0
    PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
7004
0
    PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
7005
0
    PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
7006
0
7007
0
    /* failures after this point are not malformed handshakes. */
7008
0
    /* TLS: send decrypt_error if signature failed. */
7009
0
    desc = isTLS ? decrypt_error : handshake_failure;
7010
0
7011
0
    /*
7012
0
     * Check to make sure the hash is signed by right guy.
7013
0
     */
7014
0
    rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
7015
0
                               dh_p, dh_g, dh_Ys, PR_FALSE /* padY */);
7016
0
    if (rv != SECSuccess) {
7017
0
        errCode =
7018
0
            ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7019
0
        goto alert_loser;
7020
0
    }
7021
0
    rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signature);
7022
0
    if (rv != SECSuccess) {
7023
0
        errCode =
7024
0
            ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7025
0
        goto alert_loser;
7026
0
    }
7027
0
7028
0
    /*
7029
0
     * we really need to build a new key here because we can no longer
7030
0
     * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
7031
0
     * pkcs11 slots and ID's.
7032
0
     */
7033
0
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7034
0
    if (arena == NULL) {
7035
0
        errCode = SEC_ERROR_NO_MEMORY;
7036
0
        goto loser;
7037
0
    }
7038
0
7039
0
    peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
7040
0
    if (peerKey == NULL) {
7041
0
        errCode = SEC_ERROR_NO_MEMORY;
7042
0
        goto loser;
7043
0
    }
7044
0
7045
0
    peerKey->arena = arena;
7046
0
    peerKey->keyType = dhKey;
7047
0
    peerKey->pkcs11Slot = NULL;
7048
0
    peerKey->pkcs11ID = CK_INVALID_HANDLE;
7049
0
7050
0
    if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) ||
7051
0
        SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) ||
7052
0
        SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) {
7053
0
        errCode = SEC_ERROR_NO_MEMORY;
7054
0
        goto loser;
7055
0
    }
7056
0
    ss->sec.peerKey = peerKey;
7057
0
    return SECSuccess;
7058
0
7059
0
alert_loser:
7060
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
7061
0
loser:
7062
0
    if (arena) {
7063
0
        PORT_FreeArena(arena, PR_FALSE);
7064
0
    }
7065
0
    PORT_SetError(ssl_MapLowLevelError(errCode));
7066
0
    return SECFailure;
7067
0
}
7068
7069
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
7070
 * complete ssl3 ServerKeyExchange message.
7071
 * Caller must hold Handshake and RecvBuf locks.
7072
 */
7073
static SECStatus
7074
ssl3_HandleServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
7075
0
{
7076
0
    SECStatus rv;
7077
0
7078
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
7079
0
                SSL_GETPID(), ss->fd));
7080
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7081
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7082
0
7083
0
    if (ss->ssl3.hs.ws != wait_server_key) {
7084
0
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
7085
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
7086
0
        return SECFailure;
7087
0
    }
7088
0
7089
0
    switch (ss->ssl3.hs.kea_def->exchKeyType) {
7090
0
        case ssl_kea_dh:
7091
0
            rv = ssl_HandleDHServerKeyExchange(ss, b, length);
7092
0
            break;
7093
0
7094
0
        case ssl_kea_ecdh:
7095
0
            rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
7096
0
            break;
7097
0
7098
0
        default:
7099
0
            SSL3_SendAlert(ss, alert_fatal, handshake_failure);
7100
0
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
7101
0
            rv = SECFailure;
7102
0
            break;
7103
0
    }
7104
0
7105
0
    if (rv == SECSuccess) {
7106
0
        ss->ssl3.hs.ws = wait_cert_request;
7107
0
    }
7108
0
    /* All Handle*ServerKeyExchange functions set the error code. */
7109
0
    return rv;
7110
0
}
7111
7112
typedef struct dnameNode {
7113
    struct dnameNode *next;
7114
    SECItem name;
7115
} dnameNode;
7116
7117
/*
7118
 * Parse the ca_list structure in a CertificateRequest.
7119
 *
7120
 * Called from:
7121
 * ssl3_HandleCertificateRequest
7122
 * tls13_HandleCertificateRequest
7123
 */
7124
SECStatus
7125
ssl3_ParseCertificateRequestCAs(sslSocket *ss, PRUint8 **b, PRUint32 *length,
7126
                                CERTDistNames *ca_list)
7127
0
{
7128
0
    PRUint32 remaining;
7129
0
    int nnames = 0;
7130
0
    dnameNode *node;
7131
0
    SECStatus rv;
7132
0
    int i;
7133
0
7134
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 2, b, length);
7135
0
    if (rv != SECSuccess)
7136
0
        return SECFailure; /* malformed, alert has been sent */
7137
0
7138
0
    if (remaining > *length)
7139
0
        goto alert_loser;
7140
0
7141
0
    ca_list->head = node = PORT_ArenaZNew(ca_list->arena, dnameNode);
7142
0
    if (node == NULL)
7143
0
        goto no_mem;
7144
0
7145
0
    while (remaining > 0) {
7146
0
        PRUint32 len;
7147
0
7148
0
        if (remaining < 2)
7149
0
            goto alert_loser; /* malformed */
7150
0
7151
0
        rv = ssl3_ConsumeHandshakeNumber(ss, &len, 2, b, length);
7152
0
        if (rv != SECSuccess)
7153
0
            return SECFailure; /* malformed, alert has been sent */
7154
0
        if (len == 0 || remaining < len + 2)
7155
0
            goto alert_loser; /* malformed */
7156
0
7157
0
        remaining -= 2;
7158
0
        if (SECITEM_MakeItem(ca_list->arena, &node->name, *b, len) != SECSuccess) {
7159
0
            goto no_mem;
7160
0
        }
7161
0
        node->name.len = len;
7162
0
        *b += len;
7163
0
        *length -= len;
7164
0
        remaining -= len;
7165
0
        nnames++;
7166
0
        if (remaining <= 0)
7167
0
            break; /* success */
7168
0
7169
0
        node->next = PORT_ArenaZNew(ca_list->arena, dnameNode);
7170
0
        node = node->next;
7171
0
        if (node == NULL)
7172
0
            goto no_mem;
7173
0
    }
7174
0
7175
0
    ca_list->nnames = nnames;
7176
0
    ca_list->names = PORT_ArenaNewArray(ca_list->arena, SECItem, nnames);
7177
0
    if (nnames > 0 && ca_list->names == NULL)
7178
0
        goto no_mem;
7179
0
7180
0
    for (i = 0, node = (dnameNode *)ca_list->head;
7181
0
         i < nnames;
7182
0
         i++, node = node->next) {
7183
0
        ca_list->names[i] = node->name;
7184
0
    }
7185
0
7186
0
    return SECSuccess;
7187
0
7188
0
no_mem:
7189
0
    return SECFailure;
7190
0
7191
0
alert_loser:
7192
0
    (void)SSL3_SendAlert(ss, alert_fatal,
7193
0
                         ss->version < SSL_LIBRARY_VERSION_TLS_1_0 ? illegal_parameter
7194
0
                                                                   : decode_error);
7195
0
    PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
7196
0
    return SECFailure;
7197
0
}
7198
7199
SECStatus
7200
ssl_ParseSignatureSchemes(const sslSocket *ss, PLArenaPool *arena,
7201
                          SSLSignatureScheme **schemesOut,
7202
                          unsigned int *numSchemesOut,
7203
                          unsigned char **b, unsigned int *len)
7204
0
{
7205
0
    SECStatus rv;
7206
0
    SECItem buf;
7207
0
    SSLSignatureScheme *schemes = NULL;
7208
0
    unsigned int numSupported = 0;
7209
0
    unsigned int numRemaining = 0;
7210
0
    unsigned int max;
7211
0
7212
0
    rv = ssl3_ExtConsumeHandshakeVariable(ss, &buf, 2, b, len);
7213
0
    if (rv != SECSuccess) {
7214
0
        return SECFailure;
7215
0
    }
7216
0
    /* An odd-length value is invalid. */
7217
0
    if ((buf.len & 1) != 0) {
7218
0
        ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
7219
0
        return SECFailure;
7220
0
    }
7221
0
7222
0
    /* Let the caller decide whether to alert here. */
7223
0
    if (buf.len == 0) {
7224
0
        goto done;
7225
0
    }
7226
0
7227
0
    /* Limit the number of schemes we read. */
7228
0
    numRemaining = buf.len / 2;
7229
0
    max = PR_MIN(numRemaining, MAX_SIGNATURE_SCHEMES);
7230
0
7231
0
    if (arena) {
7232
0
        schemes = PORT_ArenaZNewArray(arena, SSLSignatureScheme, max);
7233
0
    } else {
7234
0
        schemes = PORT_ZNewArray(SSLSignatureScheme, max);
7235
0
    }
7236
0
    if (!schemes) {
7237
0
        ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
7238
0
        return SECFailure;
7239
0
    }
7240
0
7241
0
    for (; numRemaining && numSupported < MAX_SIGNATURE_SCHEMES; --numRemaining) {
7242
0
        PRUint32 tmp;
7243
0
        rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2, &buf.data, &buf.len);
7244
0
        if (rv != SECSuccess) {
7245
0
            PORT_Assert(0);
7246
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
7247
0
            return SECFailure;
7248
0
        }
7249
0
        if (ssl_IsSupportedSignatureScheme((SSLSignatureScheme)tmp)) {
7250
0
            schemes[numSupported++] = (SSLSignatureScheme)tmp;
7251
0
        }
7252
0
    }
7253
0
7254
0
    if (!numSupported) {
7255
0
        if (!arena) {
7256
0
            PORT_Free(schemes);
7257
0
        }
7258
0
        schemes = NULL;
7259
0
    }
7260
0
7261
0
done:
7262
0
    *schemesOut = schemes;
7263
0
    *numSchemesOut = numSupported;
7264
0
    return SECSuccess;
7265
0
}
7266
7267
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
7268
 * a complete ssl3 Certificate Request message.
7269
 * Caller must hold Handshake and RecvBuf locks.
7270
 */
7271
static SECStatus
7272
ssl3_HandleCertificateRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
7273
0
{
7274
0
    PLArenaPool *arena = NULL;
7275
0
    PRBool isTLS = PR_FALSE;
7276
0
    PRBool isTLS12 = PR_FALSE;
7277
0
    int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
7278
0
    SECStatus rv;
7279
0
    SSL3AlertDescription desc = illegal_parameter;
7280
0
    SECItem cert_types = { siBuffer, NULL, 0 };
7281
0
    SSLSignatureScheme *signatureSchemes = NULL;
7282
0
    unsigned int signatureSchemeCount = 0;
7283
0
    CERTDistNames ca_list;
7284
0
7285
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
7286
0
                SSL_GETPID(), ss->fd));
7287
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7288
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7289
0
7290
0
    if (ss->ssl3.hs.ws != wait_cert_request) {
7291
0
        desc = unexpected_message;
7292
0
        errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
7293
0
        goto alert_loser;
7294
0
    }
7295
0
7296
0
    PORT_Assert(ss->ssl3.clientCertChain == NULL);
7297
0
    PORT_Assert(ss->ssl3.clientCertificate == NULL);
7298
0
    PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
7299
0
7300
0
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
7301
0
    isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
7302
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
7303
0
    if (rv != SECSuccess)
7304
0
        goto loser; /* malformed, alert has been sent */
7305
0
7306
0
    arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7307
0
    if (arena == NULL)
7308
0
        goto no_mem;
7309
0
7310
0
    if (isTLS12) {
7311
0
        rv = ssl_ParseSignatureSchemes(ss, arena,
7312
0
                                       &signatureSchemes,
7313
0
                                       &signatureSchemeCount,
7314
0
                                       &b, &length);
7315
0
        if (rv != SECSuccess) {
7316
0
            PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
7317
0
            goto loser; /* malformed, alert has been sent */
7318
0
        }
7319
0
    }
7320
0
7321
0
    rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, &ca_list);
7322
0
    if (rv != SECSuccess)
7323
0
        goto done; /* alert sent in ssl3_ParseCertificateRequestCAs */
7324
0
7325
0
    if (length != 0)
7326
0
        goto alert_loser; /* malformed */
7327
0
7328
0
    ss->ssl3.hs.ws = wait_hello_done;
7329
0
7330
0
    rv = ssl3_CompleteHandleCertificateRequest(ss, signatureSchemes,
7331
0
                                               signatureSchemeCount, &ca_list);
7332
0
    if (rv == SECFailure) {
7333
0
        PORT_Assert(0);
7334
0
        errCode = SEC_ERROR_LIBRARY_FAILURE;
7335
0
        desc = internal_error;
7336
0
        goto alert_loser;
7337
0
    }
7338
0
    goto done;
7339
0
7340
0
no_mem:
7341
0
    rv = SECFailure;
7342
0
    PORT_SetError(SEC_ERROR_NO_MEMORY);
7343
0
    goto done;
7344
0
7345
0
alert_loser:
7346
0
    if (isTLS && desc == illegal_parameter)
7347
0
        desc = decode_error;
7348
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
7349
0
loser:
7350
0
    PORT_SetError(errCode);
7351
0
    rv = SECFailure;
7352
0
done:
7353
0
    if (arena != NULL)
7354
0
        PORT_FreeArena(arena, PR_FALSE);
7355
0
    return rv;
7356
0
}
7357
7358
SECStatus
7359
ssl3_CompleteHandleCertificateRequest(sslSocket *ss,
7360
                                      const SSLSignatureScheme *signatureSchemes,
7361
                                      unsigned int signatureSchemeCount,
7362
                                      CERTDistNames *ca_list)
7363
0
{
7364
0
    SECStatus rv;
7365
0
7366
0
    if (ss->getClientAuthData != NULL) {
7367
0
        PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
7368
0
                    ssl_preinfo_all);
7369
0
        /* XXX Should pass cert_types and algorithms in this call!! */
7370
0
        rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
7371
0
                                                 ss->fd, ca_list,
7372
0
                                                 &ss->ssl3.clientCertificate,
7373
0
                                                 &ss->ssl3.clientPrivateKey);
7374
0
    } else {
7375
0
        rv = SECFailure; /* force it to send a no_certificate alert */
7376
0
    }
7377
0
    switch (rv) {
7378
0
        case SECWouldBlock: /* getClientAuthData has put up a dialog box. */
7379
0
            ssl3_SetAlwaysBlock(ss);
7380
0
            break; /* not an error */
7381
0
7382
0
        case SECSuccess:
7383
0
            /* check what the callback function returned */
7384
0
            if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
7385
0
                /* we are missing either the key or cert */
7386
0
                if (ss->ssl3.clientCertificate) {
7387
0
                    /* got a cert, but no key - free it */
7388
0
                    CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7389
0
                    ss->ssl3.clientCertificate = NULL;
7390
0
                }
7391
0
                if (ss->ssl3.clientPrivateKey) {
7392
0
                    /* got a key, but no cert - free it */
7393
0
                    SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7394
0
                    ss->ssl3.clientPrivateKey = NULL;
7395
0
                }
7396
0
                goto send_no_certificate;
7397
0
            }
7398
0
            /* Setting ssl3.clientCertChain non-NULL will cause
7399
0
             * ssl3_HandleServerHelloDone to call SendCertificate.
7400
0
             */
7401
0
            ss->ssl3.clientCertChain = CERT_CertChainFromCert(
7402
0
                ss->ssl3.clientCertificate,
7403
0
                certUsageSSLClient, PR_FALSE);
7404
0
            if (ss->ssl3.clientCertChain == NULL) {
7405
0
                CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7406
0
                ss->ssl3.clientCertificate = NULL;
7407
0
                SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7408
0
                ss->ssl3.clientPrivateKey = NULL;
7409
0
                goto send_no_certificate;
7410
0
            }
7411
0
            if (ss->ssl3.hs.hashType == handshake_hash_record ||
7412
0
                ss->ssl3.hs.hashType == handshake_hash_single) {
7413
0
                rv = ssl_PickClientSignatureScheme(ss, signatureSchemes,
7414
0
                                                   signatureSchemeCount);
7415
0
            }
7416
0
            break; /* not an error */
7417
0
7418
0
        case SECFailure:
7419
0
        default:
7420
0
        send_no_certificate:
7421
0
            if (ss->version > SSL_LIBRARY_VERSION_3_0) {
7422
0
                ss->ssl3.sendEmptyCert = PR_TRUE;
7423
0
            } else {
7424
0
                (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
7425
0
            }
7426
0
            rv = SECSuccess;
7427
0
            break;
7428
0
    }
7429
0
7430
0
    return rv;
7431
0
}
7432
7433
static SECStatus
7434
ssl3_CheckFalseStart(sslSocket *ss)
7435
0
{
7436
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7437
0
    PORT_Assert(!ss->ssl3.hs.authCertificatePending);
7438
0
    PORT_Assert(!ss->ssl3.hs.canFalseStart);
7439
0
7440
0
    if (!ss->canFalseStartCallback) {
7441
0
        SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start",
7442
0
                    SSL_GETPID(), ss->fd));
7443
0
    } else {
7444
0
        PRBool maybeFalseStart = PR_TRUE;
7445
0
        SECStatus rv;
7446
0
7447
0
        rv = ssl_CheckServerRandom(ss);
7448
0
        if (rv != SECSuccess) {
7449
0
            SSL_TRC(3, ("%d: SSL[%d]: no false start due to possible downgrade",
7450
0
                        SSL_GETPID(), ss->fd));
7451
0
            maybeFalseStart = PR_FALSE;
7452
0
        }
7453
0
7454
0
        /* An attacker can control the selected ciphersuite so we only wish to
7455
0
         * do False Start in the case that the selected ciphersuite is
7456
0
         * sufficiently strong that the attack can gain no advantage.
7457
0
         * Therefore we always require an 80-bit cipher. */
7458
0
        if (maybeFalseStart) {
7459
0
            ssl_GetSpecReadLock(ss);
7460
0
            maybeFalseStart = ss->ssl3.cwSpec->cipherDef->secret_key_size >= 10;
7461
0
            ssl_ReleaseSpecReadLock(ss);
7462
0
        }
7463
0
7464
0
        if (!maybeFalseStart) {
7465
0
            SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher",
7466
0
                        SSL_GETPID(), ss->fd));
7467
0
        } else {
7468
0
            PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
7469
0
                        ssl_preinfo_all);
7470
0
            rv = (ss->canFalseStartCallback)(ss->fd,
7471
0
                                             ss->canFalseStartCallbackData,
7472
0
                                             &ss->ssl3.hs.canFalseStart);
7473
0
            if (rv == SECSuccess) {
7474
0
                SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s",
7475
0
                            SSL_GETPID(), ss->fd,
7476
0
                            ss->ssl3.hs.canFalseStart ? "TRUE"
7477
0
                                                      : "FALSE"));
7478
0
            } else {
7479
0
                SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)",
7480
0
                            SSL_GETPID(), ss->fd,
7481
0
                            PR_ErrorToName(PR_GetError())));
7482
0
            }
7483
0
            return rv;
7484
0
        }
7485
0
    }
7486
0
7487
0
    ss->ssl3.hs.canFalseStart = PR_FALSE;
7488
0
    return SECSuccess;
7489
0
}
7490
7491
PRBool
7492
ssl3_WaitingForServerSecondRound(sslSocket *ss)
7493
0
{
7494
0
    PRBool result;
7495
0
7496
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7497
0
7498
0
    switch (ss->ssl3.hs.ws) {
7499
0
        case wait_new_session_ticket:
7500
0
        case wait_change_cipher:
7501
0
        case wait_finished:
7502
0
            result = PR_TRUE;
7503
0
            break;
7504
0
        default:
7505
0
            result = PR_FALSE;
7506
0
            break;
7507
0
    }
7508
0
7509
0
    return result;
7510
0
}
7511
7512
static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
7513
7514
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
7515
 * a complete ssl3 Server Hello Done message.
7516
 * Caller must hold Handshake and RecvBuf locks.
7517
 */
7518
static SECStatus
7519
ssl3_HandleServerHelloDone(sslSocket *ss)
7520
0
{
7521
0
    SECStatus rv;
7522
0
    SSL3WaitState ws = ss->ssl3.hs.ws;
7523
0
7524
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
7525
0
                SSL_GETPID(), ss->fd));
7526
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7527
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7528
0
7529
0
    /* Skipping CertificateRequest is always permitted. */
7530
0
    if (ws != wait_hello_done &&
7531
0
        ws != wait_cert_request) {
7532
0
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
7533
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
7534
0
        return SECFailure;
7535
0
    }
7536
0
7537
0
    rv = ssl3_SendClientSecondRound(ss);
7538
0
7539
0
    return rv;
7540
0
}
7541
7542
/* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
7543
 *
7544
 * Caller must hold Handshake and RecvBuf locks.
7545
 */
7546
static SECStatus
7547
ssl3_SendClientSecondRound(sslSocket *ss)
7548
0
{
7549
0
    SECStatus rv;
7550
0
    PRBool sendClientCert;
7551
0
7552
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7553
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7554
0
7555
0
    sendClientCert = !ss->ssl3.sendEmptyCert &&
7556
0
                     ss->ssl3.clientCertChain != NULL &&
7557
0
                     ss->ssl3.clientPrivateKey != NULL;
7558
0
7559
0
    /* We must wait for the server's certificate to be authenticated before
7560
0
     * sending the client certificate in order to disclosing the client
7561
0
     * certificate to an attacker that does not have a valid cert for the
7562
0
     * domain we are connecting to.
7563
0
     *
7564
0
     * During the initial handshake on a connection, we never send/receive
7565
0
     * application data until we have authenticated the server's certificate;
7566
0
     * i.e. we have fully authenticated the handshake before using the cipher
7567
0
     * specs agreed upon for that handshake. During a renegotiation, we may
7568
0
     * continue sending and receiving application data during the handshake
7569
0
     * interleaved with the handshake records. If we were to send the client's
7570
0
     * second round for a renegotiation before the server's certificate was
7571
0
     * authenticated, then the application data sent/received after this point
7572
0
     * would be using cipher spec that hadn't been authenticated. By waiting
7573
0
     * until the server's certificate has been authenticated during
7574
0
     * renegotiations, we ensure that renegotiations have the same property
7575
0
     * as initial handshakes; i.e. we have fully authenticated the handshake
7576
0
     * before using the cipher specs agreed upon for that handshake for
7577
0
     * application data.
7578
0
     */
7579
0
    if (ss->ssl3.hs.restartTarget) {
7580
0
        PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
7581
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
7582
0
        return SECFailure;
7583
0
    }
7584
0
    if (ss->ssl3.hs.authCertificatePending &&
7585
0
        (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) {
7586
0
        SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"
7587
0
                    " certificate authentication is still pending.",
7588
0
                    SSL_GETPID(), ss->fd));
7589
0
        ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
7590
0
        return SECWouldBlock;
7591
0
    }
7592
0
7593
0
    ssl_GetXmitBufLock(ss); /*******************************/
7594
0
7595
0
    if (ss->ssl3.sendEmptyCert) {
7596
0
        ss->ssl3.sendEmptyCert = PR_FALSE;
7597
0
        rv = ssl3_SendEmptyCertificate(ss);
7598
0
        /* Don't send verify */
7599
0
        if (rv != SECSuccess) {
7600
0
            goto loser; /* error code is set. */
7601
0
        }
7602
0
    } else if (sendClientCert) {
7603
0
        rv = ssl3_SendCertificate(ss);
7604
0
        if (rv != SECSuccess) {
7605
0
            goto loser; /* error code is set. */
7606
0
        }
7607
0
    }
7608
0
7609
0
    rv = ssl3_SendClientKeyExchange(ss);
7610
0
    if (rv != SECSuccess) {
7611
0
        goto loser; /* err is set. */
7612
0
    }
7613
0
7614
0
    if (sendClientCert) {
7615
0
        rv = ssl3_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
7616
0
        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7617
0
        ss->ssl3.clientPrivateKey = NULL;
7618
0
        if (rv != SECSuccess) {
7619
0
            goto loser; /* err is set. */
7620
0
        }
7621
0
    }
7622
0
7623
0
    rv = ssl3_SendChangeCipherSpecs(ss);
7624
0
    if (rv != SECSuccess) {
7625
0
        goto loser; /* err code was set. */
7626
0
    }
7627
0
7628
0
    /* This must be done after we've set ss->ssl3.cwSpec in
7629
0
     * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information
7630
0
     * from cwSpec. This must be done before we call ssl3_CheckFalseStart
7631
0
     * because the false start callback (if any) may need the information from
7632
0
     * the functions that depend on this being set.
7633
0
     */
7634
0
    ss->enoughFirstHsDone = PR_TRUE;
7635
0
7636
0
    if (!ss->firstHsDone) {
7637
0
        if (ss->opt.enableFalseStart) {
7638
0
            if (!ss->ssl3.hs.authCertificatePending) {
7639
0
                /* When we fix bug 589047, we will need to know whether we are
7640
0
                 * false starting before we try to flush the client second
7641
0
                 * round to the network. With that in mind, we purposefully
7642
0
                 * call ssl3_CheckFalseStart before calling ssl3_SendFinished,
7643
0
                 * which includes a call to ssl3_FlushHandshake, so that
7644
0
                 * no application develops a reliance on such flushing being
7645
0
                 * done before its false start callback is called.
7646
0
                 */
7647
0
                ssl_ReleaseXmitBufLock(ss);
7648
0
                rv = ssl3_CheckFalseStart(ss);
7649
0
                ssl_GetXmitBufLock(ss);
7650
0
                if (rv != SECSuccess) {
7651
0
                    goto loser;
7652
0
                }
7653
0
            } else {
7654
0
                /* The certificate authentication and the server's Finished
7655
0
                 * message are racing each other. If the certificate
7656
0
                 * authentication wins, then we will try to false start in
7657
0
                 * ssl3_AuthCertificateComplete.
7658
0
                 */
7659
0
                SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because"
7660
0
                            " certificate authentication is still pending.",
7661
0
                            SSL_GETPID(), ss->fd));
7662
0
            }
7663
0
        }
7664
0
    }
7665
0
7666
0
    rv = ssl3_SendFinished(ss, 0);
7667
0
    if (rv != SECSuccess) {
7668
0
        goto loser; /* err code was set. */
7669
0
    }
7670
0
7671
0
    ssl_ReleaseXmitBufLock(ss); /*******************************/
7672
0
7673
0
    if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
7674
0
        ss->ssl3.hs.ws = wait_new_session_ticket;
7675
0
    else
7676
0
        ss->ssl3.hs.ws = wait_change_cipher;
7677
0
7678
0
    PORT_Assert(ssl3_WaitingForServerSecondRound(ss));
7679
0
7680
0
    return SECSuccess;
7681
0
7682
0
loser:
7683
0
    ssl_ReleaseXmitBufLock(ss);
7684
0
    return rv;
7685
0
}
7686
7687
/*
7688
 * Routines used by servers
7689
 */
7690
static SECStatus
7691
ssl3_SendHelloRequest(sslSocket *ss)
7692
0
{
7693
0
    SECStatus rv;
7694
0
7695
0
    SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
7696
0
                ss->fd));
7697
0
7698
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7699
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
7700
0
7701
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_hello_request, 0);
7702
0
    if (rv != SECSuccess) {
7703
0
        return rv; /* err set by AppendHandshake */
7704
0
    }
7705
0
    rv = ssl3_FlushHandshake(ss, 0);
7706
0
    if (rv != SECSuccess) {
7707
0
        return rv; /* error code set by ssl3_FlushHandshake */
7708
0
    }
7709
0
    ss->ssl3.hs.ws = wait_client_hello;
7710
0
    return SECSuccess;
7711
0
}
7712
7713
/*
7714
 * Called from:
7715
 *  ssl3_HandleClientHello()
7716
 */
7717
static SECComparison
7718
ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
7719
0
{
7720
0
    if (!name1 != !name2) {
7721
0
        return SECLessThan;
7722
0
    }
7723
0
    if (!name1) {
7724
0
        return SECEqual;
7725
0
    }
7726
0
    if (name1->type != name2->type) {
7727
0
        return SECLessThan;
7728
0
    }
7729
0
    return SECITEM_CompareItem(name1, name2);
7730
0
}
7731
7732
/* Sets memory error when returning NULL.
7733
 * Called from:
7734
 *  ssl3_SendClientHello()
7735
 *  ssl3_HandleServerHello()
7736
 *  ssl3_HandleClientHello()
7737
 *  ssl3_HandleV2ClientHello()
7738
 */
7739
sslSessionID *
7740
ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
7741
0
{
7742
0
    sslSessionID *sid;
7743
0
7744
0
    sid = PORT_ZNew(sslSessionID);
7745
0
    if (sid == NULL)
7746
0
        return sid;
7747
0
7748
0
    if (is_server) {
7749
0
        const SECItem *srvName;
7750
0
        SECStatus rv = SECSuccess;
7751
0
7752
0
        ssl_GetSpecReadLock(ss); /********************************/
7753
0
        srvName = &ss->ssl3.hs.srvVirtName;
7754
0
        if (srvName->len && srvName->data) {
7755
0
            rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
7756
0
        }
7757
0
        ssl_ReleaseSpecReadLock(ss); /************************************/
7758
0
        if (rv != SECSuccess) {
7759
0
            PORT_Free(sid);
7760
0
            return NULL;
7761
0
        }
7762
0
    }
7763
0
    sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
7764
0
    sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url);
7765
0
    sid->addr = ss->sec.ci.peer;
7766
0
    sid->port = ss->sec.ci.port;
7767
0
    sid->references = 1;
7768
0
    sid->cached = never_cached;
7769
0
    sid->version = ss->version;
7770
0
    sid->sigScheme = ssl_sig_none;
7771
0
7772
0
    sid->u.ssl3.keys.resumable = PR_TRUE;
7773
0
    sid->u.ssl3.policy = SSL_ALLOWED;
7774
0
    sid->u.ssl3.keys.extendedMasterSecretUsed = PR_FALSE;
7775
0
7776
0
    if (is_server) {
7777
0
        SECStatus rv;
7778
0
        int pid = SSL_GETPID();
7779
0
7780
0
        sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
7781
0
        sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff;
7782
0
        sid->u.ssl3.sessionID[1] = pid & 0xff;
7783
0
        rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
7784
0
                                 SSL3_SESSIONID_BYTES - 2);
7785
0
        if (rv != SECSuccess) {
7786
0
            ssl_FreeSID(sid);
7787
0
            ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
7788
0
            return NULL;
7789
0
        }
7790
0
    }
7791
0
    return sid;
7792
0
}
7793
7794
/* Called from:  ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
7795
static SECStatus
7796
ssl3_SendServerHelloSequence(sslSocket *ss)
7797
0
{
7798
0
    const ssl3KEADef *kea_def;
7799
0
    SECStatus rv;
7800
0
7801
0
    SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
7802
0
                SSL_GETPID(), ss->fd));
7803
0
7804
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7805
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
7806
0
7807
0
    rv = ssl3_SendServerHello(ss);
7808
0
    if (rv != SECSuccess) {
7809
0
        return rv; /* err code is set. */
7810
0
    }
7811
0
    rv = ssl3_SendCertificate(ss);
7812
0
    if (rv != SECSuccess) {
7813
0
        return rv; /* error code is set. */
7814
0
    }
7815
0
    rv = ssl3_SendCertificateStatus(ss);
7816
0
    if (rv != SECSuccess) {
7817
0
        return rv; /* error code is set. */
7818
0
    }
7819
0
    /* We have to do this after the call to ssl3_SendServerHello,
7820
0
     * because kea_def is set up by ssl3_SendServerHello().
7821
0
     */
7822
0
    kea_def = ss->ssl3.hs.kea_def;
7823
0
7824
0
    if (kea_def->ephemeral) {
7825
0
        rv = ssl3_SendServerKeyExchange(ss);
7826
0
        if (rv != SECSuccess) {
7827
0
            return rv; /* err code was set. */
7828
0
        }
7829
0
    }
7830
0
7831
0
    if (ss->opt.requestCertificate) {
7832
0
        rv = ssl3_SendCertificateRequest(ss);
7833
0
        if (rv != SECSuccess) {
7834
0
            return rv; /* err code is set. */
7835
0
        }
7836
0
    }
7837
0
    rv = ssl3_SendServerHelloDone(ss);
7838
0
    if (rv != SECSuccess) {
7839
0
        return rv; /* err code is set. */
7840
0
    }
7841
0
7842
0
    ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
7843
0
                                                  : wait_client_key;
7844
0
    return SECSuccess;
7845
0
}
7846
7847
/* An empty TLS Renegotiation Info (RI) extension */
7848
static const PRUint8 emptyRIext[5] = { 0xff, 0x01, 0x00, 0x01, 0x00 };
7849
7850
static PRBool
7851
ssl3_KEASupportsTickets(const ssl3KEADef *kea_def)
7852
0
{
7853
0
    if (kea_def->signKeyType == dsaKey) {
7854
0
        /* TODO: Fix session tickets for DSS. The server code rejects the
7855
0
         * session ticket received from the client. Bug 1174677 */
7856
0
        return PR_FALSE;
7857
0
    }
7858
0
    return PR_TRUE;
7859
0
}
7860
7861
/* Select a cipher suite.
7862
**
7863
** NOTE: This suite selection algorithm should be the same as the one in
7864
** ssl3_HandleV2ClientHello().
7865
**
7866
** If TLS 1.0 is enabled, we could handle the case where the client
7867
** offered TLS 1.1 but offered only export cipher suites by choosing TLS
7868
** 1.0 and selecting one of those export cipher suites. However, a secure
7869
** TLS 1.1 client should not have export cipher suites enabled at all,
7870
** and a TLS 1.1 client should definitely not be offering *only* export
7871
** cipher suites. Therefore, we refuse to negotiate export cipher suites
7872
** with any client that indicates support for TLS 1.1 or higher when we
7873
** (the server) have TLS 1.1 support enabled.
7874
*/
7875
SECStatus
7876
ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites,
7877
                          PRBool initHashes)
7878
0
{
7879
0
    unsigned int j;
7880
0
    unsigned int i;
7881
0
7882
0
    for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
7883
0
        ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
7884
0
        SSLVersionRange vrange = { ss->version, ss->version };
7885
0
        if (!config_match(suite, ss->ssl3.policy, &vrange, ss)) {
7886
0
            continue;
7887
0
        }
7888
0
        for (i = 0; i + 1 < suites->len; i += 2) {
7889
0
            PRUint16 suite_i = (suites->data[i] << 8) | suites->data[i + 1];
7890
0
            if (suite_i == suite->cipher_suite) {
7891
0
                ss->ssl3.hs.cipher_suite = suite_i;
7892
0
                return ssl3_SetupCipherSuite(ss, initHashes);
7893
0
            }
7894
0
        }
7895
0
    }
7896
0
    return SECFailure;
7897
0
}
7898
7899
/*
7900
 * Call the SNI config hook.
7901
 *
7902
 * Called from:
7903
 *   ssl3_HandleClientHello
7904
 *   tls13_HandleClientHelloPart2
7905
 */
7906
SECStatus
7907
ssl3_ServerCallSNICallback(sslSocket *ss)
7908
0
{
7909
0
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
7910
0
    SSL3AlertDescription desc = illegal_parameter;
7911
0
    int ret = 0;
7912
0
7913
#ifdef SSL_SNI_ALLOW_NAME_CHANGE_2HS
7914
#error("No longer allowed to set SSL_SNI_ALLOW_NAME_CHANGE_2HS")
7915
#endif
7916
0
    if (!ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
7917
0
        if (ss->firstHsDone) {
7918
0
            /* Check that we don't have the name is current spec
7919
0
             * if this extension was not negotiated on the 2d hs. */
7920
0
            PRBool passed = PR_TRUE;
7921
0
            ssl_GetSpecReadLock(ss); /*******************************/
7922
0
            if (ss->ssl3.hs.srvVirtName.data) {
7923
0
                passed = PR_FALSE;
7924
0
            }
7925
0
            ssl_ReleaseSpecReadLock(ss); /***************************/
7926
0
            if (!passed) {
7927
0
                errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7928
0
                desc = handshake_failure;
7929
0
                goto alert_loser;
7930
0
            }
7931
0
        }
7932
0
        return SECSuccess;
7933
0
    }
7934
0
7935
0
    if (ss->sniSocketConfig)
7936
0
        do { /* not a loop */
7937
0
            PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
7938
0
                        ssl_preinfo_all);
7939
0
7940
0
            ret = SSL_SNI_SEND_ALERT;
7941
0
            /* If extension is negotiated, the len of names should > 0. */
7942
0
            if (ss->xtnData.sniNameArrSize) {
7943
0
                /* Calling client callback to reconfigure the socket. */
7944
0
                ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
7945
0
                                                        ss->xtnData.sniNameArr,
7946
0
                                                        ss->xtnData.sniNameArrSize,
7947
0
                                                        ss->sniSocketConfigArg);
7948
0
            }
7949
0
            if (ret <= SSL_SNI_SEND_ALERT) {
7950
0
                /* Application does not know the name or was not able to
7951
0
                 * properly reconfigure the socket. */
7952
0
                errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7953
0
                desc = unrecognized_name;
7954
0
                break;
7955
0
            } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
7956
0
                SECStatus rv = SECSuccess;
7957
0
                SECItem pwsNameBuf = { 0, NULL, 0 };
7958
0
                SECItem *pwsName = &pwsNameBuf;
7959
0
                SECItem *cwsName;
7960
0
7961
0
                ssl_GetSpecWriteLock(ss); /*******************************/
7962
0
                cwsName = &ss->ssl3.hs.srvVirtName;
7963
0
                /* not allow name change on the 2d HS */
7964
0
                if (ss->firstHsDone) {
7965
0
                    if (ssl3_ServerNameCompare(pwsName, cwsName)) {
7966
0
                        ssl_ReleaseSpecWriteLock(ss); /******************/
7967
0
                        errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
7968
0
                        desc = handshake_failure;
7969
0
                        ret = SSL_SNI_SEND_ALERT;
7970
0
                        break;
7971
0
                    }
7972
0
                }
7973
0
                if (pwsName->data) {
7974
0
                    SECITEM_FreeItem(pwsName, PR_FALSE);
7975
0
                }
7976
0
                if (cwsName->data) {
7977
0
                    rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
7978
0
                }
7979
0
                ssl_ReleaseSpecWriteLock(ss); /**************************/
7980
0
                if (rv != SECSuccess) {
7981
0
                    errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
7982
0
                    desc = internal_error;
7983
0
                    ret = SSL_SNI_SEND_ALERT;
7984
0
                    break;
7985
0
                }
7986
0
            } else if ((unsigned int)ret < ss->xtnData.sniNameArrSize) {
7987
0
                /* Application has configured new socket info. Lets check it
7988
0
                 * and save the name. */
7989
0
                SECStatus rv;
7990
0
                SECItem *name = &ss->xtnData.sniNameArr[ret];
7991
0
                SECItem *pwsName;
7992
0
7993
0
                /* get rid of the old name and save the newly picked. */
7994
0
                /* This code is protected by ssl3HandshakeLock. */
7995
0
                ssl_GetSpecWriteLock(ss); /*******************************/
7996
0
                /* not allow name change on the 2d HS */
7997
0
                if (ss->firstHsDone) {
7998
0
                    SECItem *cwsName = &ss->ssl3.hs.srvVirtName;
7999
0
                    if (ssl3_ServerNameCompare(name, cwsName)) {
8000
0
                        ssl_ReleaseSpecWriteLock(ss); /******************/
8001
0
                        errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8002
0
                        desc = handshake_failure;
8003
0
                        ret = SSL_SNI_SEND_ALERT;
8004
0
                        break;
8005
0
                    }
8006
0
                }
8007
0
                pwsName = &ss->ssl3.hs.srvVirtName;
8008
0
                if (pwsName->data) {
8009
0
                    SECITEM_FreeItem(pwsName, PR_FALSE);
8010
0
                }
8011
0
                rv = SECITEM_CopyItem(NULL, pwsName, name);
8012
0
                ssl_ReleaseSpecWriteLock(ss); /***************************/
8013
0
                if (rv != SECSuccess) {
8014
0
                    errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8015
0
                    desc = internal_error;
8016
0
                    ret = SSL_SNI_SEND_ALERT;
8017
0
                    break;
8018
0
                }
8019
0
                if (ssl3_config_match_init(ss) == 0) {
8020
0
                    /* no ciphers are working/supported */
8021
0
                    errCode = PORT_GetError();
8022
0
                    desc = handshake_failure;
8023
0
                    ret = SSL_SNI_SEND_ALERT;
8024
0
                    break;
8025
0
                }
8026
0
                /* Need to tell the client that application has picked
8027
0
                 * the name from the offered list and reconfigured the socket.
8028
0
                 */
8029
0
                ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_server_name_xtn,
8030
0
                                             ssl_SendEmptyExtension);
8031
0
            } else {
8032
0
                /* Callback returned index outside of the boundary. */
8033
0
                PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize);
8034
0
                errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8035
0
                desc = internal_error;
8036
0
                ret = SSL_SNI_SEND_ALERT;
8037
0
                break;
8038
0
            }
8039
0
        } while (0);
8040
0
    ssl3_FreeSniNameArray(&ss->xtnData);
8041
0
    if (ret <= SSL_SNI_SEND_ALERT) {
8042
0
        /* desc and errCode should be set. */
8043
0
        goto alert_loser;
8044
0
    }
8045
0
8046
0
    return SECSuccess;
8047
0
8048
0
alert_loser:
8049
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
8050
0
    PORT_SetError(errCode);
8051
0
    return SECFailure;
8052
0
}
8053
8054
SECStatus
8055
ssl3_SelectServerCert(sslSocket *ss)
8056
0
{
8057
0
    const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
8058
0
    PRCList *cursor;
8059
0
    SECStatus rv;
8060
0
8061
0
    /* If the client didn't include the supported groups extension, assume just
8062
0
     * P-256 support and disable all the other ECDHE groups.  This also affects
8063
0
     * ECDHE group selection, but this function is called first. */
8064
0
    if (!ssl3_ExtensionNegotiated(ss, ssl_supported_groups_xtn)) {
8065
0
        unsigned int i;
8066
0
        for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
8067
0
            if (ss->namedGroupPreferences[i] &&
8068
0
                ss->namedGroupPreferences[i]->keaType == ssl_kea_ecdh &&
8069
0
                ss->namedGroupPreferences[i]->name != ssl_grp_ec_secp256r1) {
8070
0
                ss->namedGroupPreferences[i] = NULL;
8071
0
            }
8072
0
        }
8073
0
    }
8074
0
8075
0
    /* This picks the first certificate that has:
8076
0
     * a) the right authentication method, and
8077
0
     * b) the right named curve (EC only)
8078
0
     *
8079
0
     * We might want to do some sort of ranking here later.  For now, it's all
8080
0
     * based on what order they are configured in. */
8081
0
    for (cursor = PR_NEXT_LINK(&ss->serverCerts);
8082
0
         cursor != &ss->serverCerts;
8083
0
         cursor = PR_NEXT_LINK(cursor)) {
8084
0
        sslServerCert *cert = (sslServerCert *)cursor;
8085
0
        if (kea_def->authKeyType == ssl_auth_rsa_sign) {
8086
0
            /* We consider PSS certificates here as well for TLS 1.2. */
8087
0
            if (!SSL_CERT_IS(cert, ssl_auth_rsa_sign) &&
8088
0
                (!SSL_CERT_IS(cert, ssl_auth_rsa_pss) ||
8089
0
                 ss->version < SSL_LIBRARY_VERSION_TLS_1_2)) {
8090
0
                continue;
8091
0
            }
8092
0
        } else {
8093
0
            if (!SSL_CERT_IS(cert, kea_def->authKeyType)) {
8094
0
                continue;
8095
0
            }
8096
0
            if (SSL_CERT_IS_EC(cert) &&
8097
0
                !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
8098
0
                continue;
8099
0
            }
8100
0
        }
8101
0
8102
0
        /* Found one. */
8103
0
        ss->sec.serverCert = cert;
8104
0
        ss->sec.authKeyBits = cert->serverKeyBits;
8105
0
8106
0
        /* Don't pick a signature scheme if we aren't going to use it. */
8107
0
        if (kea_def->signKeyType == nullKey) {
8108
0
            ss->sec.authType = kea_def->authKeyType;
8109
0
            return SECSuccess;
8110
0
        }
8111
0
8112
0
        rv = ssl3_PickServerSignatureScheme(ss);
8113
0
        if (rv != SECSuccess) {
8114
0
            return SECFailure;
8115
0
        }
8116
0
        ss->sec.authType =
8117
0
            ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme);
8118
0
        return SECSuccess;
8119
0
    }
8120
0
8121
0
    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
8122
0
    return SECFailure;
8123
0
}
8124
8125
static SECStatus
8126
ssl_GenerateServerRandom(sslSocket *ss)
8127
0
{
8128
0
    SECStatus rv = ssl3_GetNewRandom(ss->ssl3.hs.server_random);
8129
0
    if (rv != SECSuccess) {
8130
0
        return SECFailure;
8131
0
    }
8132
0
8133
0
    if (ss->version == ss->vrange.max) {
8134
0
        return SECSuccess;
8135
0
    }
8136
0
#ifdef DTLS_1_3_DRAFT_VERSION
8137
0
    if (IS_DTLS(ss)) {
8138
0
        return SECSuccess;
8139
0
    }
8140
0
#endif
8141
0
8142
0
    /*
8143
0
     * [RFC 8446 Section 4.1.3].
8144
0
     *
8145
0
     * TLS 1.3 servers which negotiate TLS 1.2 or below in response to a
8146
0
     * ClientHello MUST set the last 8 bytes of their Random value specially in
8147
0
     * their ServerHello.
8148
0
     *
8149
0
     * If negotiating TLS 1.2, TLS 1.3 servers MUST set the last 8 bytes of
8150
0
     * their Random value to the bytes:
8151
0
     *
8152
0
     *   44 4F 57 4E 47 52 44 01
8153
0
     *
8154
0
     * If negotiating TLS 1.1 or below, TLS 1.3 servers MUST, and TLS 1.2
8155
0
     * servers SHOULD, set the last 8 bytes of their ServerHello.Random value to
8156
0
     * the bytes:
8157
0
     *
8158
0
     *   44 4F 57 4E 47 52 44 00
8159
0
     */
8160
0
    PRUint8 *downgradeSentinel =
8161
0
        ss->ssl3.hs.server_random +
8162
0
        SSL3_RANDOM_LENGTH - sizeof(tls13_downgrade_random);
8163
0
8164
0
    switch (ss->vrange.max) {
8165
0
        case SSL_LIBRARY_VERSION_TLS_1_3:
8166
0
            PORT_Memcpy(downgradeSentinel,
8167
0
                        tls13_downgrade_random, sizeof(tls13_downgrade_random));
8168
0
            break;
8169
0
        case SSL_LIBRARY_VERSION_TLS_1_2:
8170
0
            PORT_Memcpy(downgradeSentinel,
8171
0
                        tls12_downgrade_random, sizeof(tls12_downgrade_random));
8172
0
            break;
8173
0
        default:
8174
0
            /* Do not change random. */
8175
0
            break;
8176
0
    }
8177
0
8178
0
    return SECSuccess;
8179
0
}
8180
8181
/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
8182
 * ssl3 Client Hello message.
8183
 * Caller must hold Handshake and RecvBuf locks.
8184
 */
8185
static SECStatus
8186
ssl3_HandleClientHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
8187
0
{
8188
0
    sslSessionID *sid = NULL;
8189
0
    PRUint32 tmp;
8190
0
    unsigned int i;
8191
0
    SECStatus rv;
8192
0
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8193
0
    SSL3AlertDescription desc = illegal_parameter;
8194
0
    SSL3AlertLevel level = alert_fatal;
8195
0
    SSL3ProtocolVersion version;
8196
0
    TLSExtension *versionExtension;
8197
0
    SECItem sidBytes = { siBuffer, NULL, 0 };
8198
0
    SECItem cookieBytes = { siBuffer, NULL, 0 };
8199
0
    SECItem suites = { siBuffer, NULL, 0 };
8200
0
    SECItem comps = { siBuffer, NULL, 0 };
8201
0
    PRBool isTLS13;
8202
0
    const PRUint8 *savedMsg = b;
8203
0
    const PRUint32 savedLen = length;
8204
0
8205
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
8206
0
                SSL_GETPID(), ss->fd));
8207
0
8208
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
8209
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8210
0
    ss->ssl3.hs.preliminaryInfo = 0;
8211
0
8212
0
    if (!ss->sec.isServer ||
8213
0
        (ss->ssl3.hs.ws != wait_client_hello &&
8214
0
         ss->ssl3.hs.ws != idle_handshake)) {
8215
0
        desc = unexpected_message;
8216
0
        errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
8217
0
        goto alert_loser;
8218
0
    }
8219
0
    if (ss->ssl3.hs.ws == idle_handshake) {
8220
0
        /* Refuse re-handshake when we have already negotiated TLS 1.3. */
8221
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
8222
0
            desc = unexpected_message;
8223
0
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
8224
0
            goto alert_loser;
8225
0
        }
8226
0
        if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
8227
0
            desc = no_renegotiation;
8228
0
            level = alert_warning;
8229
0
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
8230
0
            goto alert_loser;
8231
0
        }
8232
0
    }
8233
0
8234
0
    /* We should always be in a fresh state. */
8235
0
    SSL_ASSERT_HASHES_EMPTY(ss);
8236
0
8237
0
    /* Get peer name of client */
8238
0
    rv = ssl_GetPeerInfo(ss);
8239
0
    if (rv != SECSuccess) {
8240
0
        return rv; /* error code is set. */
8241
0
    }
8242
0
8243
0
    /* We might be starting session renegotiation in which case we should
8244
0
     * clear previous state.
8245
0
     */
8246
0
    ssl3_ResetExtensionData(&ss->xtnData, ss);
8247
0
    ss->statelessResume = PR_FALSE;
8248
0
8249
0
    if (IS_DTLS(ss)) {
8250
0
        dtls_RehandshakeCleanup(ss);
8251
0
    }
8252
0
8253
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, &b, &length);
8254
0
    if (rv != SECSuccess)
8255
0
        goto loser; /* malformed, alert already sent */
8256
0
8257
0
    /* Translate the version. */
8258
0
    if (IS_DTLS(ss)) {
8259
0
        ss->clientHelloVersion = version =
8260
0
            dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
8261
0
    } else {
8262
0
        ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp;
8263
0
    }
8264
0
8265
0
    /* Grab the client random data. */
8266
0
    rv = ssl3_ConsumeHandshake(
8267
0
        ss, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length);
8268
0
    if (rv != SECSuccess) {
8269
0
        goto loser; /* malformed */
8270
0
    }
8271
0
8272
0
    /* Grab the client's SID, if present. */
8273
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
8274
0
    if (rv != SECSuccess) {
8275
0
        goto loser; /* malformed */
8276
0
    }
8277
0
8278
0
    /* Grab the client's cookie, if present. */
8279
0
    if (IS_DTLS(ss)) {
8280
0
        rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length);
8281
0
        if (rv != SECSuccess) {
8282
0
            goto loser; /* malformed */
8283
0
        }
8284
0
        if (cookieBytes.len != 0) {
8285
0
            goto loser; /* We never send cookies in DTLS 1.2. */
8286
0
        }
8287
0
    }
8288
0
8289
0
    /* Grab the list of cipher suites. */
8290
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length);
8291
0
    if (rv != SECSuccess) {
8292
0
        goto loser; /* malformed */
8293
0
    }
8294
0
8295
0
    /* Grab the list of compression methods. */
8296
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length);
8297
0
    if (rv != SECSuccess) {
8298
0
        goto loser; /* malformed */
8299
0
    }
8300
0
8301
0
    /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
8302
0
     * we are restarting a previous session until extensions have been
8303
0
     * parsed, since we might have received a SessionTicket extension.
8304
0
     * Note: we allow extensions even when negotiating SSL3 for the sake
8305
0
     * of interoperability (and backwards compatibility).
8306
0
     */
8307
0
8308
0
    if (length) {
8309
0
        /* Get length of hello extensions */
8310
0
        PRUint32 extensionLength;
8311
0
        rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
8312
0
        if (rv != SECSuccess) {
8313
0
            goto loser; /* alert already sent */
8314
0
        }
8315
0
        if (extensionLength != length) {
8316
0
            errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8317
0
            desc = decode_error;
8318
0
            goto alert_loser;
8319
0
        }
8320
0
8321
0
        rv = ssl3_ParseExtensions(ss, &b, &length);
8322
0
        if (rv != SECSuccess) {
8323
0
            goto loser; /* malformed */
8324
0
        }
8325
0
    }
8326
0
8327
0
    versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
8328
0
    if (versionExtension) {
8329
0
        rv = tls13_NegotiateVersion(ss, versionExtension);
8330
0
        if (rv != SECSuccess) {
8331
0
            errCode = PORT_GetError();
8332
0
            desc = (errCode == SSL_ERROR_UNSUPPORTED_VERSION) ? protocol_version : illegal_parameter;
8333
0
            goto alert_loser;
8334
0
        }
8335
0
    } else {
8336
0
        /* The PR_MIN here ensures that we never negotiate 1.3 if the
8337
0
         * peer didn't offer "supported_versions". */
8338
0
        rv = ssl3_NegotiateVersion(ss,
8339
0
                                   PR_MIN(version,
8340
0
                                          SSL_LIBRARY_VERSION_TLS_1_2),
8341
0
                                   PR_TRUE);
8342
0
        if (rv != SECSuccess) {
8343
0
            desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
8344
0
                                                       : handshake_failure;
8345
0
            errCode = SSL_ERROR_UNSUPPORTED_VERSION;
8346
0
            goto alert_loser;
8347
0
        }
8348
0
    }
8349
0
8350
0
    if (ss->firstHsDone && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
8351
0
        desc = unexpected_message;
8352
0
        errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
8353
0
        goto alert_loser;
8354
0
    }
8355
0
8356
0
    isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
8357
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
8358
0
    /* Update the write spec to match the selected version. */
8359
0
    if (!ss->firstHsDone) {
8360
0
        ssl_GetSpecWriteLock(ss);
8361
0
        ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
8362
0
        ssl_ReleaseSpecWriteLock(ss);
8363
0
    }
8364
0
8365
0
    if (isTLS13 && sidBytes.len > 0 && !IS_DTLS(ss)) {
8366
0
        SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
8367
0
        rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.fakeSid, &sidBytes);
8368
0
        if (rv != SECSuccess) {
8369
0
            desc = internal_error;
8370
0
            errCode = PORT_GetError();
8371
0
            goto alert_loser;
8372
0
        }
8373
0
    }
8374
0
8375
0
    /* If there is a cookie, then this is a second ClientHello (TLS 1.3). */
8376
0
    if (ssl3_FindExtension(ss, ssl_tls13_cookie_xtn)) {
8377
0
        ss->ssl3.hs.helloRetry = PR_TRUE;
8378
0
    }
8379
0
8380
0
    if (ss->ssl3.hs.receivedCcs) {
8381
0
        /* This is only valid if we sent HelloRetryRequest, so we should have
8382
0
         * negotiated TLS 1.3 and there should be a cookie extension. */
8383
0
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3 ||
8384
0
            !ss->ssl3.hs.helloRetry) {
8385
0
            desc = unexpected_message;
8386
0
            errCode = SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER;
8387
0
            goto alert_loser;
8388
0
        }
8389
0
    }
8390
0
8391
0
    /* Now parse the rest of the extensions. */
8392
0
    rv = ssl3_HandleParsedExtensions(ss, ssl_hs_client_hello);
8393
0
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
8394
0
    if (rv != SECSuccess) {
8395
0
        if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
8396
0
            errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
8397
0
        }
8398
0
        goto loser; /* malformed */
8399
0
    }
8400
0
8401
0
    /* If the ClientHello version is less than our maximum version, check for a
8402
0
     * TLS_FALLBACK_SCSV and reject the connection if found. */
8403
0
    if (ss->vrange.max > ss->version) {
8404
0
        for (i = 0; i + 1 < suites.len; i += 2) {
8405
0
            PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
8406
0
            if (suite_i != TLS_FALLBACK_SCSV)
8407
0
                continue;
8408
0
            desc = inappropriate_fallback;
8409
0
            errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
8410
0
            goto alert_loser;
8411
0
        }
8412
0
    }
8413
0
8414
0
    /* TLS 1.3 requires that compression only include null. */
8415
0
    if (isTLS13) {
8416
0
        if (comps.len != 1 || comps.data[0] != ssl_compression_null) {
8417
0
            goto alert_loser;
8418
0
        }
8419
0
    } else {
8420
0
        /* Other versions need to include null somewhere. */
8421
0
        if (comps.len < 1 ||
8422
0
            !memchr(comps.data, ssl_compression_null, comps.len)) {
8423
0
            goto alert_loser;
8424
0
        }
8425
0
    }
8426
0
8427
0
    if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
8428
0
        /* If we didn't receive an RI extension, look for the SCSV,
8429
0
         * and if found, treat it just like an empty RI extension
8430
0
         * by processing a local copy of an empty RI extension.
8431
0
         */
8432
0
        for (i = 0; i + 1 < suites.len; i += 2) {
8433
0
            PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
8434
0
            if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
8435
0
                PRUint8 *b2 = (PRUint8 *)emptyRIext;
8436
0
                PRUint32 L2 = sizeof emptyRIext;
8437
0
                (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
8438
0
                break;
8439
0
            }
8440
0
        }
8441
0
    }
8442
0
8443
0
    /* The check for renegotiation in TLS 1.3 is earlier. */
8444
0
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
8445
0
        if (ss->firstHsDone &&
8446
0
            (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
8447
0
             ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) &&
8448
0
            !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
8449
0
            desc = no_renegotiation;
8450
0
            level = alert_warning;
8451
0
            errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
8452
0
            goto alert_loser;
8453
0
        }
8454
0
        if ((ss->opt.requireSafeNegotiation ||
8455
0
             (ss->firstHsDone && ss->peerRequestedProtection)) &&
8456
0
            !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
8457
0
            desc = handshake_failure;
8458
0
            errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
8459
0
            goto alert_loser;
8460
0
        }
8461
0
    }
8462
0
8463
0
    /* We do stateful resumes only if we are in TLS < 1.3 and
8464
0
     * either of the following conditions are satisfied:
8465
0
     * (1) the client does not support the session ticket extension, or
8466
0
     * (2) the client support the session ticket extension, but sent an
8467
0
     * empty ticket.
8468
0
     */
8469
0
    if ((ss->version < SSL_LIBRARY_VERSION_TLS_1_3) &&
8470
0
        (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
8471
0
         ss->xtnData.emptySessionTicket)) {
8472
0
        if (sidBytes.len > 0 && !ss->opt.noCache) {
8473
0
            SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
8474
0
                        SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
8475
0
                        ss->sec.ci.peer.pr_s6_addr32[1],
8476
0
                        ss->sec.ci.peer.pr_s6_addr32[2],
8477
0
                        ss->sec.ci.peer.pr_s6_addr32[3]));
8478
0
            if (ssl_sid_lookup) {
8479
0
                sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data,
8480
0
                                        sidBytes.len, ss->dbHandle);
8481
0
            } else {
8482
0
                errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
8483
0
                goto loser;
8484
0
            }
8485
0
        }
8486
0
    } else if (ss->statelessResume) {
8487
0
        /* Fill in the client's session ID if doing a stateless resume.
8488
0
         * (When doing stateless resumes, server echos client's SessionID.)
8489
0
         * This branch also handles TLS 1.3 resumption-PSK.
8490
0
         */
8491
0
        sid = ss->sec.ci.sid;
8492
0
        PORT_Assert(sid != NULL); /* Should have already been filled in.*/
8493
0
8494
0
        if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
8495
0
            sid->u.ssl3.sessionIDLength = sidBytes.len;
8496
0
            PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
8497
0
                        sidBytes.len);
8498
0
            sid->u.ssl3.sessionIDLength = sidBytes.len;
8499
0
        } else {
8500
0
            sid->u.ssl3.sessionIDLength = 0;
8501
0
        }
8502
0
        ss->sec.ci.sid = NULL;
8503
0
    }
8504
0
8505
0
    /* Free a potentially leftover session ID from a previous handshake. */
8506
0
    if (ss->sec.ci.sid) {
8507
0
        ssl_FreeSID(ss->sec.ci.sid);
8508
0
        ss->sec.ci.sid = NULL;
8509
0
    }
8510
0
8511
0
    if (sid != NULL) {
8512
0
        /* We've found a session cache entry for this client.
8513
0
         * Now, if we're going to require a client-auth cert,
8514
0
         * and we don't already have this client's cert in the session cache,
8515
0
         * and this is the first handshake on this connection (not a redo),
8516
0
         * then drop this old cache entry and start a new session.
8517
0
         */
8518
0
        if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
8519
0
            ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
8520
0
             (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
8521
0
             ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) &&
8522
0
              !ss->firstHsDone))) {
8523
0
8524
0
            SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
8525
0
            ssl_UncacheSessionID(ss);
8526
0
            ssl_FreeSID(sid);
8527
0
            sid = NULL;
8528
0
        }
8529
0
    }
8530
0
8531
0
    if (IS_DTLS(ss)) {
8532
0
        ssl3_DisableNonDTLSSuites(ss);
8533
0
        dtls_ReceivedFirstMessageInFlight(ss);
8534
0
    }
8535
0
8536
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
8537
0
        rv = tls13_HandleClientHelloPart2(ss, &suites, sid, savedMsg, savedLen);
8538
0
    } else {
8539
0
        rv = ssl3_HandleClientHelloPart2(ss, &suites, sid,
8540
0
                                         savedMsg, savedLen);
8541
0
    }
8542
0
    if (rv != SECSuccess) {
8543
0
        errCode = PORT_GetError();
8544
0
        goto loser;
8545
0
    }
8546
0
    return SECSuccess;
8547
0
8548
0
alert_loser:
8549
0
    (void)SSL3_SendAlert(ss, level, desc);
8550
0
/* FALLTHRU */
8551
0
loser:
8552
0
    PORT_SetError(errCode);
8553
0
    return SECFailure;
8554
0
}
8555
8556
static SECStatus
8557
ssl3_UnwrapMasterSecretServer(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
8558
0
{
8559
0
    PK11SymKey *wrapKey;
8560
0
    CK_FLAGS keyFlags = 0;
8561
0
    SECItem wrappedMS = {
8562
0
        siBuffer,
8563
0
        sid->u.ssl3.keys.wrapped_master_secret,
8564
0
        sid->u.ssl3.keys.wrapped_master_secret_len
8565
0
    };
8566
0
8567
0
    wrapKey = ssl3_GetWrappingKey(ss, NULL, sid->u.ssl3.masterWrapMech,
8568
0
                                  ss->pkcs11PinArg);
8569
0
    if (!wrapKey) {
8570
0
        return SECFailure;
8571
0
    }
8572
0
8573
0
    if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
8574
0
        keyFlags = CKF_SIGN | CKF_VERIFY;
8575
0
    }
8576
0
8577
0
    /* unwrap the master secret. */
8578
0
    *ms = PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
8579
0
                                     NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
8580
0
                                     CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH, keyFlags);
8581
0
    PK11_FreeSymKey(wrapKey);
8582
0
    if (!*ms) {
8583
0
        return SECFailure;
8584
0
    }
8585
0
    return SECSuccess;
8586
0
}
8587
8588
static SECStatus
8589
ssl3_HandleClientHelloPart2(sslSocket *ss,
8590
                            SECItem *suites,
8591
                            sslSessionID *sid,
8592
                            const PRUint8 *msg,
8593
                            unsigned int len)
8594
0
{
8595
0
    PRBool haveXmitBufLock = PR_FALSE;
8596
0
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8597
0
    SSL3AlertDescription desc = illegal_parameter;
8598
0
    SECStatus rv;
8599
0
    unsigned int i;
8600
0
    unsigned int j;
8601
0
8602
0
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_client_hello, msg, len);
8603
0
    if (rv != SECSuccess) {
8604
0
        errCode = SEC_ERROR_LIBRARY_FAILURE;
8605
0
        desc = internal_error;
8606
0
        goto alert_loser;
8607
0
    }
8608
0
8609
0
    /* If we already have a session for this client, be sure to pick the same
8610
0
    ** cipher suite we picked before.  This is not a loop, despite appearances.
8611
0
    */
8612
0
    if (sid)
8613
0
        do {
8614
0
            ssl3CipherSuiteCfg *suite;
8615
#ifdef PARANOID
8616
            SSLVersionRange vrange = { ss->version, ss->version };
8617
#endif
8618
8619
0
            suite = ss->cipherSuites;
8620
0
            /* Find the entry for the cipher suite used in the cached session. */
8621
0
            for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
8622
0
                if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
8623
0
                    break;
8624
0
            }
8625
0
            PORT_Assert(j > 0);
8626
0
            if (j == 0)
8627
0
                break;
8628
#ifdef PARANOID
8629
            /* Double check that the cached cipher suite is still enabled,
8630
             * implemented, and allowed by policy.  Might have been disabled.
8631
             * The product policy won't change during the process lifetime.
8632
             * Implemented ("isPresent") shouldn't change for servers.
8633
             */
8634
            if (!config_match(suite, ss->ssl3.policy, &vrange, ss))
8635
                break;
8636
#else
8637
0
            if (!suite->enabled)
8638
0
                break;
8639
0
#endif
8640
0
            /* Double check that the cached cipher suite is in the client's
8641
0
             * list.  If it isn't, fall through and start a new session. */
8642
0
            for (i = 0; i + 1 < suites->len; i += 2) {
8643
0
                PRUint16 suite_i = (suites->data[i] << 8) | suites->data[i + 1];
8644
0
                if (suite_i == suite->cipher_suite) {
8645
0
                    ss->ssl3.hs.cipher_suite = suite_i;
8646
0
                    rv = ssl3_SetupCipherSuite(ss, PR_TRUE);
8647
0
                    if (rv != SECSuccess) {
8648
0
                        desc = internal_error;
8649
0
                        errCode = PORT_GetError();
8650
0
                        goto alert_loser;
8651
0
                    }
8652
0
8653
0
                    goto cipher_found;
8654
0
                }
8655
0
            }
8656
0
        } while (0);
8657
0
/* START A NEW SESSION */
8658
0
8659
0
#ifndef PARANOID
8660
0
    /* Look for a matching cipher suite. */
8661
0
    if (ssl3_config_match_init(ss) == 0) {
8662
0
        desc = internal_error;
8663
0
        errCode = PORT_GetError(); /* error code is already set. */
8664
0
        goto alert_loser;
8665
0
    }
8666
0
#endif
8667
0
8668
0
    rv = ssl3_NegotiateCipherSuite(ss, suites, PR_TRUE);
8669
0
    if (rv != SECSuccess) {
8670
0
        desc = handshake_failure;
8671
0
        errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
8672
0
        goto alert_loser;
8673
0
    }
8674
0
8675
0
cipher_found:
8676
0
    suites->data = NULL;
8677
0
8678
0
    /* If there are any failures while processing the old sid,
8679
0
     * we don't consider them to be errors.  Instead, We just behave
8680
0
     * as if the client had sent us no sid to begin with, and make a new one.
8681
0
     * The exception here is attempts to resume extended_master_secret
8682
0
     * sessions without the extension, which causes an alert.
8683
0
     */
8684
0
    if (sid != NULL)
8685
0
        do {
8686
0
            PK11SymKey *masterSecret;
8687
0
8688
0
            if (sid->version != ss->version ||
8689
0
                sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
8690
0
                break; /* not an error */
8691
0
            }
8692
0
8693
0
            /* server sids don't remember the server cert we previously sent,
8694
0
            ** but they do remember the slot we originally used, so we
8695
0
            ** can locate it again, provided that the current ssl socket
8696
0
            ** has had its server certs configured the same as the previous one.
8697
0
            */
8698
0
            ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType, sid->namedCurve);
8699
0
            if (!ss->sec.serverCert || !ss->sec.serverCert->serverCert) {
8700
0
                /* A compatible certificate must not have been configured.  It
8701
0
                 * might not be the same certificate, but we only find that out
8702
0
                 * when the ticket fails to decrypt. */
8703
0
                break;
8704
0
            }
8705
0
8706
0
            /* [draft-ietf-tls-session-hash-06; Section 5.3]
8707
0
             * o  If the original session did not use the "extended_master_secret"
8708
0
             *    extension but the new ClientHello contains the extension, then the
8709
0
             *    server MUST NOT perform the abbreviated handshake.  Instead, it
8710
0
             *    SHOULD continue with a full handshake (as described in
8711
0
             *    Section 5.2) to negotiate a new session.
8712
0
             *
8713
0
             * o  If the original session used the "extended_master_secret"
8714
0
             *    extension but the new ClientHello does not contain the extension,
8715
0
             *    the server MUST abort the abbreviated handshake.
8716
0
             */
8717
0
            if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
8718
0
                if (!sid->u.ssl3.keys.extendedMasterSecretUsed) {
8719
0
                    break; /* not an error */
8720
0
                }
8721
0
            } else {
8722
0
                if (sid->u.ssl3.keys.extendedMasterSecretUsed) {
8723
0
                    /* Note: we do not destroy the session */
8724
0
                    desc = handshake_failure;
8725
0
                    errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
8726
0
                    goto alert_loser;
8727
0
                }
8728
0
            }
8729
0
8730
0
            if (ss->sec.ci.sid) {
8731
0
                ssl_UncacheSessionID(ss);
8732
0
                PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */
8733
0
                if (ss->sec.ci.sid != sid) {
8734
0
                    ssl_FreeSID(ss->sec.ci.sid);
8735
0
                }
8736
0
                ss->sec.ci.sid = NULL;
8737
0
            }
8738
0
8739
0
            /* we need to resurrect the master secret.... */
8740
0
            rv = ssl3_UnwrapMasterSecretServer(ss, sid, &masterSecret);
8741
0
            if (rv != SECSuccess) {
8742
0
                break; /* not an error */
8743
0
            }
8744
0
8745
0
            ss->sec.ci.sid = sid;
8746
0
            if (sid->peerCert != NULL) {
8747
0
                ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
8748
0
            }
8749
0
8750
0
            /*
8751
0
             * Old SID passed all tests, so resume this old session.
8752
0
             */
8753
0
            SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_hits);
8754
0
            if (ss->statelessResume)
8755
0
                SSL_AtomicIncrementLong(&ssl3stats.hch_sid_stateless_resumes);
8756
0
            ss->ssl3.hs.isResuming = PR_TRUE;
8757
0
8758
0
            ss->sec.authType = sid->authType;
8759
0
            ss->sec.authKeyBits = sid->authKeyBits;
8760
0
            ss->sec.keaType = sid->keaType;
8761
0
            ss->sec.keaKeyBits = sid->keaKeyBits;
8762
0
            ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
8763
0
            ss->sec.signatureScheme = sid->sigScheme;
8764
0
8765
0
            ss->sec.localCert =
8766
0
                CERT_DupCertificate(ss->sec.serverCert->serverCert);
8767
0
8768
0
            /* Copy cached name in to pending spec */
8769
0
            if (sid != NULL &&
8770
0
                sid->version > SSL_LIBRARY_VERSION_3_0 &&
8771
0
                sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
8772
0
                /* Set server name from sid */
8773
0
                SECItem *sidName = &sid->u.ssl3.srvName;
8774
0
                SECItem *pwsName = &ss->ssl3.hs.srvVirtName;
8775
0
                if (pwsName->data) {
8776
0
                    SECITEM_FreeItem(pwsName, PR_FALSE);
8777
0
                }
8778
0
                rv = SECITEM_CopyItem(NULL, pwsName, sidName);
8779
0
                if (rv != SECSuccess) {
8780
0
                    errCode = PORT_GetError();
8781
0
                    desc = internal_error;
8782
0
                    goto alert_loser;
8783
0
                }
8784
0
            }
8785
0
8786
0
            /* Clean up sni name array */
8787
0
            ssl3_FreeSniNameArray(&ss->xtnData);
8788
0
8789
0
            ssl_GetXmitBufLock(ss);
8790
0
            haveXmitBufLock = PR_TRUE;
8791
0
8792
0
            rv = ssl3_SendServerHello(ss);
8793
0
            if (rv != SECSuccess) {
8794
0
                errCode = PORT_GetError();
8795
0
                goto loser;
8796
0
            }
8797
0
8798
0
            /* We are re-using the old MS, so no need to derive again. */
8799
0
            rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE);
8800
0
            if (rv != SECSuccess) {
8801
0
                errCode = PORT_GetError();
8802
0
                goto loser;
8803
0
            }
8804
0
8805
0
            rv = ssl3_SendChangeCipherSpecs(ss);
8806
0
            if (rv != SECSuccess) {
8807
0
                errCode = PORT_GetError();
8808
0
                goto loser;
8809
0
            }
8810
0
            rv = ssl3_SendFinished(ss, 0);
8811
0
            ss->ssl3.hs.ws = wait_change_cipher;
8812
0
            if (rv != SECSuccess) {
8813
0
                errCode = PORT_GetError();
8814
0
                goto loser;
8815
0
            }
8816
0
8817
0
            if (haveXmitBufLock) {
8818
0
                ssl_ReleaseXmitBufLock(ss);
8819
0
            }
8820
0
8821
0
            return SECSuccess;
8822
0
        } while (0);
8823
0
8824
0
    if (sid) { /* we had a sid, but it's no longer valid, free it */
8825
0
        ss->statelessResume = PR_FALSE;
8826
0
        SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
8827
0
        ssl_UncacheSessionID(ss);
8828
0
        ssl_FreeSID(sid);
8829
0
        sid = NULL;
8830
0
    }
8831
0
    SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
8832
0
8833
0
    /* We only send a session ticket extension if the client supports
8834
0
     * the extension and we are unable to resume.
8835
0
     *
8836
0
     * TODO: send a session ticket if performing a stateful
8837
0
     * resumption.  (As per RFC4507, a server may issue a session
8838
0
     * ticket while doing a (stateless or stateful) session resume,
8839
0
     * but OpenSSL-0.9.8g does not accept session tickets while
8840
0
     * resuming.)
8841
0
     */
8842
0
    if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
8843
0
        ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
8844
0
        ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_session_ticket_xtn,
8845
0
                                     ssl_SendEmptyExtension);
8846
0
    }
8847
0
8848
0
    rv = ssl3_ServerCallSNICallback(ss);
8849
0
    if (rv != SECSuccess) {
8850
0
        /* The alert has already been sent. */
8851
0
        errCode = PORT_GetError();
8852
0
        goto loser;
8853
0
    }
8854
0
8855
0
    rv = ssl3_SelectServerCert(ss);
8856
0
    if (rv != SECSuccess) {
8857
0
        errCode = PORT_GetError();
8858
0
        desc = handshake_failure;
8859
0
        goto alert_loser;
8860
0
    }
8861
0
8862
0
    sid = ssl3_NewSessionID(ss, PR_TRUE);
8863
0
    if (sid == NULL) {
8864
0
        errCode = PORT_GetError();
8865
0
        goto loser; /* memory error is set. */
8866
0
    }
8867
0
    ss->sec.ci.sid = sid;
8868
0
8869
0
    sid->u.ssl3.keys.extendedMasterSecretUsed =
8870
0
        ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
8871
0
    ss->ssl3.hs.isResuming = PR_FALSE;
8872
0
8873
0
    ssl_GetXmitBufLock(ss);
8874
0
    rv = ssl3_SendServerHelloSequence(ss);
8875
0
    ssl_ReleaseXmitBufLock(ss);
8876
0
    if (rv != SECSuccess) {
8877
0
        errCode = PORT_GetError();
8878
0
        desc = handshake_failure;
8879
0
        goto alert_loser;
8880
0
    }
8881
0
8882
0
    if (haveXmitBufLock) {
8883
0
        ssl_ReleaseXmitBufLock(ss);
8884
0
    }
8885
0
8886
0
    return SECSuccess;
8887
0
8888
0
alert_loser:
8889
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
8890
0
/* FALLTHRU */
8891
0
loser:
8892
0
    if (sid && sid != ss->sec.ci.sid) {
8893
0
        ssl_UncacheSessionID(ss);
8894
0
        ssl_FreeSID(sid);
8895
0
    }
8896
0
8897
0
    if (haveXmitBufLock) {
8898
0
        ssl_ReleaseXmitBufLock(ss);
8899
0
    }
8900
0
8901
0
    PORT_SetError(errCode);
8902
0
    return SECFailure;
8903
0
}
8904
8905
/*
8906
 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
8907
 * in asking to use the V3 handshake.
8908
 */
8909
SECStatus
8910
ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, unsigned int length,
8911
                         PRUint8 padding)
8912
0
{
8913
0
    sslSessionID *sid = NULL;
8914
0
    unsigned char *suites;
8915
0
    unsigned char *random;
8916
0
    SSL3ProtocolVersion version;
8917
0
    SECStatus rv;
8918
0
    unsigned int i;
8919
0
    unsigned int j;
8920
0
    unsigned int sid_length;
8921
0
    unsigned int suite_length;
8922
0
    unsigned int rand_length;
8923
0
    int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8924
0
    SSL3AlertDescription desc = handshake_failure;
8925
0
    unsigned int total = SSL_HL_CLIENT_HELLO_HBYTES;
8926
0
8927
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
8928
0
8929
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
8930
0
8931
0
    ssl_GetSSL3HandshakeLock(ss);
8932
0
8933
0
    version = (buffer[1] << 8) | buffer[2];
8934
0
    if (version < SSL_LIBRARY_VERSION_3_0) {
8935
0
        goto loser;
8936
0
    }
8937
0
8938
0
    ssl3_RestartHandshakeHashes(ss);
8939
0
8940
0
    if (ss->ssl3.hs.ws != wait_client_hello) {
8941
0
        desc = unexpected_message;
8942
0
        errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
8943
0
        goto alert_loser;
8944
0
    }
8945
0
8946
0
    total += suite_length = (buffer[3] << 8) | buffer[4];
8947
0
    total += sid_length = (buffer[5] << 8) | buffer[6];
8948
0
    total += rand_length = (buffer[7] << 8) | buffer[8];
8949
0
    total += padding;
8950
0
    ss->clientHelloVersion = version;
8951
0
8952
0
    if (version >= SSL_LIBRARY_VERSION_TLS_1_3) {
8953
0
        /* [draft-ietf-tls-tls-11; C.3] forbids sending a TLS 1.3
8954
0
         * ClientHello using the backwards-compatible format. */
8955
0
        desc = illegal_parameter;
8956
0
        errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8957
0
        goto alert_loser;
8958
0
    }
8959
0
8960
0
    rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
8961
0
    if (rv != SECSuccess) {
8962
0
        /* send back which ever alert client will understand. */
8963
0
        desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
8964
0
                                                   : handshake_failure;
8965
0
        errCode = SSL_ERROR_UNSUPPORTED_VERSION;
8966
0
        goto alert_loser;
8967
0
    }
8968
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
8969
0
    if (!ss->firstHsDone) {
8970
0
        ssl_GetSpecWriteLock(ss);
8971
0
        ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
8972
0
        ssl_ReleaseSpecWriteLock(ss);
8973
0
    }
8974
0
8975
0
    /* if we get a non-zero SID, just ignore it. */
8976
0
    if (length != total) {
8977
0
        SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
8978
0
                 SSL_GETPID(), ss->fd, length, total));
8979
0
        desc = illegal_parameter;
8980
0
        errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8981
0
        goto alert_loser;
8982
0
    }
8983
0
8984
0
    suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
8985
0
    random = suites + suite_length + sid_length;
8986
0
8987
0
    if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
8988
0
        rand_length > SSL_MAX_CHALLENGE_BYTES) {
8989
0
        desc = illegal_parameter;
8990
0
        errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8991
0
        goto alert_loser;
8992
0
    }
8993
0
8994
0
    PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
8995
0
8996
0
    PORT_Memset(ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
8997
0
    PORT_Memcpy(&ss->ssl3.hs.client_random[SSL3_RANDOM_LENGTH - rand_length],
8998
0
                random, rand_length);
8999
0
9000
0
    PRINT_BUF(60, (ss, "client random:", ss->ssl3.hs.client_random,
9001
0
                   SSL3_RANDOM_LENGTH));
9002
0
9003
0
    if (ssl3_config_match_init(ss) == 0) {
9004
0
        errCode = PORT_GetError(); /* error code is already set. */
9005
0
        goto alert_loser;
9006
0
    }
9007
0
9008
0
    /* Select a cipher suite.
9009
0
    **
9010
0
    ** NOTE: This suite selection algorithm should be the same as the one in
9011
0
    ** ssl3_HandleClientHello().
9012
0
    */
9013
0
    for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
9014
0
        ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
9015
0
        SSLVersionRange vrange = { ss->version, ss->version };
9016
0
        if (!config_match(suite, ss->ssl3.policy, &vrange, ss)) {
9017
0
            continue;
9018
0
        }
9019
0
        for (i = 0; i + 2 < suite_length; i += 3) {
9020
0
            PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9021
0
            if (suite_i == suite->cipher_suite) {
9022
0
                ss->ssl3.hs.cipher_suite = suite_i;
9023
0
                rv = ssl3_SetupCipherSuite(ss, PR_TRUE);
9024
0
                if (rv != SECSuccess) {
9025
0
                    desc = internal_error;
9026
0
                    errCode = PORT_GetError();
9027
0
                    goto alert_loser;
9028
0
                }
9029
0
                goto suite_found;
9030
0
            }
9031
0
        }
9032
0
    }
9033
0
    errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
9034
0
    goto alert_loser;
9035
0
9036
0
suite_found:
9037
0
9038
0
    /* If the ClientHello version is less than our maximum version, check for a
9039
0
     * TLS_FALLBACK_SCSV and reject the connection if found. */
9040
0
    if (ss->vrange.max > ss->clientHelloVersion) {
9041
0
        for (i = 0; i + 2 < suite_length; i += 3) {
9042
0
            PRUint16 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9043
0
            if (suite_i == TLS_FALLBACK_SCSV) {
9044
0
                desc = inappropriate_fallback;
9045
0
                errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
9046
0
                goto alert_loser;
9047
0
            }
9048
0
        }
9049
0
    }
9050
0
9051
0
    /* Look for the SCSV, and if found, treat it just like an empty RI
9052
0
     * extension by processing a local copy of an empty RI extension.
9053
0
     */
9054
0
    for (i = 0; i + 2 < suite_length; i += 3) {
9055
0
        PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9056
0
        if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
9057
0
            PRUint8 *b2 = (PRUint8 *)emptyRIext;
9058
0
            PRUint32 L2 = sizeof emptyRIext;
9059
0
            (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
9060
0
            break;
9061
0
        }
9062
0
    }
9063
0
9064
0
    if (ss->opt.requireSafeNegotiation &&
9065
0
        !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9066
0
        desc = handshake_failure;
9067
0
        errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
9068
0
        goto alert_loser;
9069
0
    }
9070
0
9071
0
    rv = ssl3_SelectServerCert(ss);
9072
0
    if (rv != SECSuccess) {
9073
0
        errCode = PORT_GetError();
9074
0
        desc = handshake_failure;
9075
0
        goto alert_loser;
9076
0
    }
9077
0
9078
0
    /* we don't even search for a cache hit here.  It's just a miss. */
9079
0
    SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
9080
0
    sid = ssl3_NewSessionID(ss, PR_TRUE);
9081
0
    if (sid == NULL) {
9082
0
        errCode = PORT_GetError();
9083
0
        goto loser; /* memory error is set. */
9084
0
    }
9085
0
    ss->sec.ci.sid = sid;
9086
0
    /* do not worry about memory leak of sid since it now belongs to ci */
9087
0
9088
0
    /* We have to update the handshake hashes before we can send stuff */
9089
0
    rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
9090
0
    if (rv != SECSuccess) {
9091
0
        errCode = PORT_GetError();
9092
0
        goto loser;
9093
0
    }
9094
0
9095
0
    ssl_GetXmitBufLock(ss);
9096
0
    rv = ssl3_SendServerHelloSequence(ss);
9097
0
    ssl_ReleaseXmitBufLock(ss);
9098
0
    if (rv != SECSuccess) {
9099
0
        errCode = PORT_GetError();
9100
0
        goto loser;
9101
0
    }
9102
0
9103
0
    ssl_ReleaseSSL3HandshakeLock(ss);
9104
0
    return SECSuccess;
9105
0
9106
0
alert_loser:
9107
0
    SSL3_SendAlert(ss, alert_fatal, desc);
9108
0
loser:
9109
0
    ssl_ReleaseSSL3HandshakeLock(ss);
9110
0
    PORT_SetError(errCode);
9111
0
    return SECFailure;
9112
0
}
9113
9114
SECStatus
9115
ssl_ConstructServerHello(sslSocket *ss, PRBool helloRetry,
9116
                         const sslBuffer *extensionBuf, sslBuffer *messageBuf)
9117
0
{
9118
0
    SECStatus rv;
9119
0
    SSL3ProtocolVersion version;
9120
0
    sslSessionID *sid = ss->sec.ci.sid;
9121
0
    const PRUint8 *random;
9122
0
9123
0
    version = PR_MIN(ss->version, SSL_LIBRARY_VERSION_TLS_1_2);
9124
0
    if (IS_DTLS(ss)) {
9125
0
        version = dtls_TLSVersionToDTLSVersion(version);
9126
0
    }
9127
0
    rv = sslBuffer_AppendNumber(messageBuf, version, 2);
9128
0
    if (rv != SECSuccess) {
9129
0
        return SECFailure;
9130
0
    }
9131
0
9132
0
    if (helloRetry) {
9133
0
        random = ssl_hello_retry_random;
9134
0
    } else {
9135
0
        rv = ssl_GenerateServerRandom(ss);
9136
0
        if (rv != SECSuccess) {
9137
0
            return SECFailure;
9138
0
        }
9139
0
        random = ss->ssl3.hs.server_random;
9140
0
    }
9141
0
    rv = sslBuffer_Append(messageBuf, random, SSL3_RANDOM_LENGTH);
9142
0
    if (rv != SECSuccess) {
9143
0
        return SECFailure;
9144
0
    }
9145
0
9146
0
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
9147
0
        if (sid) {
9148
0
            rv = sslBuffer_AppendVariable(messageBuf, sid->u.ssl3.sessionID,
9149
0
                                          sid->u.ssl3.sessionIDLength, 1);
9150
0
        } else {
9151
0
            rv = sslBuffer_AppendNumber(messageBuf, 0, 1);
9152
0
        }
9153
0
    } else {
9154
0
        rv = sslBuffer_AppendVariable(messageBuf, ss->ssl3.hs.fakeSid.data,
9155
0
                                      ss->ssl3.hs.fakeSid.len, 1);
9156
0
    }
9157
0
    if (rv != SECSuccess) {
9158
0
        return SECFailure;
9159
0
    }
9160
0
9161
0
    rv = sslBuffer_AppendNumber(messageBuf, ss->ssl3.hs.cipher_suite, 2);
9162
0
    if (rv != SECSuccess) {
9163
0
        return SECFailure;
9164
0
    }
9165
0
    rv = sslBuffer_AppendNumber(messageBuf, ssl_compression_null, 1);
9166
0
    if (rv != SECSuccess) {
9167
0
        return SECFailure;
9168
0
    }
9169
0
    if (SSL_BUFFER_LEN(extensionBuf)) {
9170
0
        rv = sslBuffer_AppendBufferVariable(messageBuf, extensionBuf, 2);
9171
0
        if (rv != SECSuccess) {
9172
0
            return SECFailure;
9173
0
        }
9174
0
    }
9175
0
9176
0
    return SECSuccess;
9177
0
}
9178
9179
/* The negotiated version number has been already placed in ss->version.
9180
**
9181
** Called from:  ssl3_HandleClientHello                     (resuming session),
9182
**  ssl3_SendServerHelloSequence <- ssl3_HandleClientHello   (new session),
9183
**  ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
9184
*/
9185
SECStatus
9186
ssl3_SendServerHello(sslSocket *ss)
9187
0
{
9188
0
    SECStatus rv;
9189
0
    sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
9190
0
    sslBuffer messageBuf = SSL_BUFFER_EMPTY;
9191
0
9192
0
    SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
9193
0
                ss->fd));
9194
0
9195
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9196
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9197
0
9198
0
    PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
9199
0
    if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
9200
0
        PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
9201
0
        return SECFailure;
9202
0
    }
9203
0
9204
0
    rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_server_hello);
9205
0
    if (rv != SECSuccess) {
9206
0
        goto loser;
9207
0
    }
9208
0
9209
0
    rv = ssl_ConstructServerHello(ss, PR_FALSE, &extensionBuf, &messageBuf);
9210
0
    if (rv != SECSuccess) {
9211
0
        goto loser;
9212
0
    }
9213
0
9214
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello,
9215
0
                                    SSL_BUFFER_LEN(&messageBuf));
9216
0
    if (rv != SECSuccess) {
9217
0
        goto loser; /* err set by AppendHandshake. */
9218
0
    }
9219
0
9220
0
    rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&messageBuf),
9221
0
                              SSL_BUFFER_LEN(&messageBuf));
9222
0
    if (rv != SECSuccess) {
9223
0
        goto loser; /* err set by AppendHandshake. */
9224
0
    }
9225
0
9226
0
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
9227
0
        rv = ssl3_SetupBothPendingCipherSpecs(ss);
9228
0
        if (rv != SECSuccess) {
9229
0
            goto loser; /* err set */
9230
0
        }
9231
0
    }
9232
0
9233
0
    sslBuffer_Clear(&extensionBuf);
9234
0
    sslBuffer_Clear(&messageBuf);
9235
0
    return SECSuccess;
9236
0
9237
0
loser:
9238
0
    sslBuffer_Clear(&extensionBuf);
9239
0
    sslBuffer_Clear(&messageBuf);
9240
0
    return SECFailure;
9241
0
}
9242
9243
SECStatus
9244
ssl_CreateDHEKeyPair(const sslNamedGroupDef *groupDef,
9245
                     const ssl3DHParams *params,
9246
                     sslEphemeralKeyPair **keyPair)
9247
0
{
9248
0
    SECKEYDHParams dhParam;
9249
0
    SECKEYPublicKey *pubKey = NULL;   /* Ephemeral DH key */
9250
0
    SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */
9251
0
    sslEphemeralKeyPair *pair;
9252
0
9253
0
    dhParam.prime.data = params->prime.data;
9254
0
    dhParam.prime.len = params->prime.len;
9255
0
    dhParam.base.data = params->base.data;
9256
0
    dhParam.base.len = params->base.len;
9257
0
9258
0
    PRINT_BUF(60, (NULL, "Server DH p", dhParam.prime.data,
9259
0
                   dhParam.prime.len));
9260
0
    PRINT_BUF(60, (NULL, "Server DH g", dhParam.base.data,
9261
0
                   dhParam.base.len));
9262
0
9263
0
    /* Generate ephemeral DH keypair */
9264
0
    privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
9265
0
    if (!privKey || !pubKey) {
9266
0
        ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
9267
0
        return SECFailure;
9268
0
    }
9269
0
9270
0
    pair = ssl_NewEphemeralKeyPair(groupDef, privKey, pubKey);
9271
0
    if (!pair) {
9272
0
        SECKEY_DestroyPrivateKey(privKey);
9273
0
        SECKEY_DestroyPublicKey(pubKey);
9274
0
9275
0
        return SECFailure;
9276
0
    }
9277
0
9278
0
    *keyPair = pair;
9279
0
    return SECSuccess;
9280
0
}
9281
9282
static SECStatus
9283
ssl3_SendDHServerKeyExchange(sslSocket *ss)
9284
0
{
9285
0
    const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
9286
0
    SECStatus rv = SECFailure;
9287
0
    int length;
9288
0
    SECItem signed_hash = { siBuffer, NULL, 0 };
9289
0
    SSL3Hashes hashes;
9290
0
    SSLHashType hashAlg;
9291
0
9292
0
    const ssl3DHParams *params;
9293
0
    sslEphemeralKeyPair *keyPair;
9294
0
    SECKEYPublicKey *pubKey;
9295
0
    SECKEYPrivateKey *certPrivateKey;
9296
0
    const sslNamedGroupDef *groupDef;
9297
0
    /* Do this on the heap, this could be over 2k long. */
9298
0
    sslBuffer dhBuf = SSL_BUFFER_EMPTY;
9299
0
9300
0
    if (kea_def->kea != kea_dhe_dss && kea_def->kea != kea_dhe_rsa) {
9301
0
        /* TODO: Support DH_anon. It might be sufficient to drop the signature.
9302
0
                 See bug 1170510. */
9303
0
        PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9304
0
        return SECFailure;
9305
0
    }
9306
0
9307
0
    rv = ssl_SelectDHEGroup(ss, &groupDef);
9308
0
    if (rv == SECFailure) {
9309
0
        PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
9310
0
        return SECFailure;
9311
0
    }
9312
0
    ss->sec.keaGroup = groupDef;
9313
0
9314
0
    params = ssl_GetDHEParams(groupDef);
9315
0
    rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
9316
0
    if (rv == SECFailure) {
9317
0
        ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
9318
0
        return SECFailure;
9319
0
    }
9320
0
    PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs);
9321
0
9322
0
    if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
9323
0
        hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
9324
0
    } else {
9325
0
        /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
9326
0
        hashAlg = ssl_hash_none;
9327
0
    }
9328
0
9329
0
    pubKey = keyPair->keys->pubKey;
9330
0
    PRINT_BUF(50, (ss, "DH public value:",
9331
0
                   pubKey->u.dh.publicValue.data,
9332
0
                   pubKey->u.dh.publicValue.len));
9333
0
    rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
9334
0
                               pubKey->u.dh.prime,
9335
0
                               pubKey->u.dh.base,
9336
0
                               pubKey->u.dh.publicValue,
9337
0
                               PR_TRUE /* padY */);
9338
0
    if (rv != SECSuccess) {
9339
0
        ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9340
0
        goto loser;
9341
0
    }
9342
0
9343
0
    certPrivateKey = ss->sec.serverCert->serverKeyPair->privKey;
9344
0
    rv = ssl3_SignHashes(ss, &hashes, certPrivateKey, &signed_hash);
9345
0
    if (rv != SECSuccess) {
9346
0
        goto loser; /* ssl3_SignHashes has set err. */
9347
0
    }
9348
0
9349
0
    length = 2 + pubKey->u.dh.prime.len +
9350
0
             2 + pubKey->u.dh.base.len +
9351
0
             2 + pubKey->u.dh.prime.len +
9352
0
             2 + signed_hash.len;
9353
0
9354
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
9355
0
        length += 2;
9356
0
    }
9357
0
9358
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_key_exchange, length);
9359
0
    if (rv != SECSuccess) {
9360
0
        goto loser; /* err set by AppendHandshake. */
9361
0
    }
9362
0
9363
0
    rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.prime.data,
9364
0
                                      pubKey->u.dh.prime.len, 2);
9365
0
    if (rv != SECSuccess) {
9366
0
        goto loser; /* err set by AppendHandshake. */
9367
0
    }
9368
0
9369
0
    rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.base.data,
9370
0
                                      pubKey->u.dh.base.len, 2);
9371
0
    if (rv != SECSuccess) {
9372
0
        goto loser; /* err set by AppendHandshake. */
9373
0
    }
9374
0
9375
0
    rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE);
9376
0
    if (rv != SECSuccess) {
9377
0
        goto loser; /* err set by AppendPaddedDHKeyShare. */
9378
0
    }
9379
0
    rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
9380
0
    if (rv != SECSuccess) {
9381
0
        goto loser; /* err set by AppendHandshake. */
9382
0
    }
9383
0
9384
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
9385
0
        rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
9386
0
        if (rv != SECSuccess) {
9387
0
            goto loser; /* err set by AppendHandshake. */
9388
0
        }
9389
0
    }
9390
0
9391
0
    rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
9392
0
                                      signed_hash.len, 2);
9393
0
    if (rv != SECSuccess) {
9394
0
        goto loser; /* err set by AppendHandshake. */
9395
0
    }
9396
0
9397
0
    sslBuffer_Clear(&dhBuf);
9398
0
    PORT_Free(signed_hash.data);
9399
0
    return SECSuccess;
9400
0
9401
0
loser:
9402
0
    if (signed_hash.data)
9403
0
        PORT_Free(signed_hash.data);
9404
0
    sslBuffer_Clear(&dhBuf);
9405
0
    return SECFailure;
9406
0
}
9407
9408
static SECStatus
9409
ssl3_SendServerKeyExchange(sslSocket *ss)
9410
0
{
9411
0
    const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
9412
0
9413
0
    SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
9414
0
                SSL_GETPID(), ss->fd));
9415
0
9416
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9417
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9418
0
9419
0
    switch (kea_def->exchKeyType) {
9420
0
        case ssl_kea_dh: {
9421
0
            return ssl3_SendDHServerKeyExchange(ss);
9422
0
        }
9423
0
9424
0
        case ssl_kea_ecdh: {
9425
0
            return ssl3_SendECDHServerKeyExchange(ss);
9426
0
        }
9427
0
9428
0
        case ssl_kea_rsa:
9429
0
        case ssl_kea_null:
9430
0
        default:
9431
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
9432
0
            break;
9433
0
    }
9434
0
9435
0
    return SECFailure;
9436
0
}
9437
9438
SECStatus
9439
ssl3_EncodeSigAlgs(const sslSocket *ss, sslBuffer *buf)
9440
0
{
9441
0
    unsigned int lengthOffset;
9442
0
    unsigned int i;
9443
0
    PRBool found = PR_FALSE;
9444
0
    SECStatus rv;
9445
0
9446
0
    rv = sslBuffer_Skip(buf, 2, &lengthOffset);
9447
0
    if (rv != SECSuccess) {
9448
0
        return SECFailure;
9449
0
    }
9450
0
9451
0
    for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
9452
0
        PRUint32 policy = 0;
9453
0
        SSLHashType hashType = ssl_SignatureSchemeToHashType(
9454
0
            ss->ssl3.signatureSchemes[i]);
9455
0
        SECOidTag hashOID = ssl3_HashTypeToOID(hashType);
9456
0
9457
0
        /* Skip RSA-PSS schemes if there are no tokens to verify them. */
9458
0
        if (ssl_IsRsaPssSignatureScheme(ss->ssl3.signatureSchemes[i]) &&
9459
0
            !PK11_TokenExists(auth_alg_defs[ssl_auth_rsa_pss])) {
9460
0
            continue;
9461
0
        }
9462
0
9463
0
        if ((NSS_GetAlgorithmPolicy(hashOID, &policy) != SECSuccess) ||
9464
0
            (policy & NSS_USE_ALG_IN_SSL_KX)) {
9465
0
            rv = sslBuffer_AppendNumber(buf, ss->ssl3.signatureSchemes[i], 2);
9466
0
            if (rv != SECSuccess) {
9467
0
                return SECFailure;
9468
0
            }
9469
0
9470
0
            found = PR_TRUE;
9471
0
        }
9472
0
    }
9473
0
9474
0
    if (!found) {
9475
0
        PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
9476
0
        return SECFailure;
9477
0
    }
9478
0
9479
0
    return sslBuffer_InsertLength(buf, lengthOffset, 2);
9480
0
}
9481
9482
static SECStatus
9483
ssl3_SendCertificateRequest(sslSocket *ss)
9484
0
{
9485
0
    PRBool isTLS12;
9486
0
    const PRUint8 *certTypes;
9487
0
    SECStatus rv;
9488
0
    PRUint32 length;
9489
0
    const SECItem *names;
9490
0
    unsigned int calen;
9491
0
    unsigned int nnames;
9492
0
    const SECItem *name;
9493
0
    unsigned int i;
9494
0
    int certTypesLength;
9495
0
    PRUint8 sigAlgs[2 + MAX_SIGNATURE_SCHEMES * 2];
9496
0
    sslBuffer sigAlgsBuf = SSL_BUFFER(sigAlgs);
9497
0
9498
0
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
9499
0
                SSL_GETPID(), ss->fd));
9500
0
9501
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9502
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9503
0
9504
0
    isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
9505
0
9506
0
    rv = ssl_GetCertificateRequestCAs(ss, &calen, &names, &nnames);
9507
0
    if (rv != SECSuccess) {
9508
0
        return rv;
9509
0
    }
9510
0
    certTypes = certificate_types;
9511
0
    certTypesLength = sizeof certificate_types;
9512
0
9513
0
    length = 1 + certTypesLength + 2 + calen;
9514
0
    if (isTLS12) {
9515
0
        rv = ssl3_EncodeSigAlgs(ss, &sigAlgsBuf);
9516
0
        if (rv != SECSuccess) {
9517
0
            return rv;
9518
0
        }
9519
0
        length += SSL_BUFFER_LEN(&sigAlgsBuf);
9520
0
    }
9521
0
9522
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request, length);
9523
0
    if (rv != SECSuccess) {
9524
0
        return rv; /* err set by AppendHandshake. */
9525
0
    }
9526
0
    rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
9527
0
    if (rv != SECSuccess) {
9528
0
        return rv; /* err set by AppendHandshake. */
9529
0
    }
9530
0
    if (isTLS12) {
9531
0
        rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&sigAlgsBuf),
9532
0
                                  SSL_BUFFER_LEN(&sigAlgsBuf));
9533
0
        if (rv != SECSuccess) {
9534
0
            return rv; /* err set by AppendHandshake. */
9535
0
        }
9536
0
    }
9537
0
    rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
9538
0
    if (rv != SECSuccess) {
9539
0
        return rv; /* err set by AppendHandshake. */
9540
0
    }
9541
0
    for (i = 0, name = names; i < nnames; i++, name++) {
9542
0
        rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
9543
0
        if (rv != SECSuccess) {
9544
0
            return rv; /* err set by AppendHandshake. */
9545
0
        }
9546
0
    }
9547
0
9548
0
    return SECSuccess;
9549
0
}
9550
9551
static SECStatus
9552
ssl3_SendServerHelloDone(sslSocket *ss)
9553
0
{
9554
0
    SECStatus rv;
9555
0
9556
0
    SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
9557
0
                SSL_GETPID(), ss->fd));
9558
0
9559
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9560
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9561
0
9562
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello_done, 0);
9563
0
    if (rv != SECSuccess) {
9564
0
        return rv; /* err set by AppendHandshake. */
9565
0
    }
9566
0
    rv = ssl3_FlushHandshake(ss, 0);
9567
0
    if (rv != SECSuccess) {
9568
0
        return rv; /* error code set by ssl3_FlushHandshake */
9569
0
    }
9570
0
    return SECSuccess;
9571
0
}
9572
9573
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
9574
 * a complete ssl3 Certificate Verify message
9575
 * Caller must hold Handshake and RecvBuf locks.
9576
 */
9577
static SECStatus
9578
ssl3_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
9579
0
{
9580
0
    SECItem signed_hash = { siBuffer, NULL, 0 };
9581
0
    SECStatus rv;
9582
0
    int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
9583
0
    SSL3AlertDescription desc = handshake_failure;
9584
0
    PRBool isTLS;
9585
0
    SSLSignatureScheme sigScheme;
9586
0
    SSL3Hashes hashes;
9587
0
    const PRUint8 *savedMsg = b;
9588
0
    const PRUint32 savedLen = length;
9589
0
9590
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
9591
0
                SSL_GETPID(), ss->fd));
9592
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
9593
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9594
0
9595
0
    if (ss->ssl3.hs.ws != wait_cert_verify) {
9596
0
        desc = unexpected_message;
9597
0
        errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
9598
0
        goto alert_loser;
9599
0
    }
9600
0
9601
0
    /* TLS 1.3 is handled by tls13_HandleCertificateVerify */
9602
0
    PORT_Assert(ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2);
9603
0
9604
0
    if (ss->ssl3.prSpec->version == SSL_LIBRARY_VERSION_TLS_1_2) {
9605
0
        PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_record);
9606
0
        rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
9607
0
        if (rv != SECSuccess) {
9608
0
            goto loser; /* malformed or unsupported. */
9609
0
        }
9610
0
        rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme,
9611
0
                                                 ss->sec.peerCert);
9612
0
        if (rv != SECSuccess) {
9613
0
            errCode = PORT_GetError();
9614
0
            desc = illegal_parameter;
9615
0
            goto alert_loser;
9616
0
        }
9617
0
9618
0
        rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
9619
0
                                       ss->ssl3.hs.messages.len,
9620
0
                                       ssl_SignatureSchemeToHashType(sigScheme),
9621
0
                                       &hashes);
9622
0
    } else {
9623
0
        PORT_Assert(ss->ssl3.hs.hashType != handshake_hash_record);
9624
0
        sigScheme = ssl_sig_none;
9625
0
        rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.prSpec, &hashes, 0);
9626
0
    }
9627
0
9628
0
    if (rv != SECSuccess) {
9629
0
        errCode = SSL_ERROR_DIGEST_FAILURE;
9630
0
        desc = decrypt_error;
9631
0
        goto alert_loser;
9632
0
    }
9633
0
9634
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
9635
0
    if (rv != SECSuccess) {
9636
0
        goto loser; /* malformed. */
9637
0
    }
9638
0
9639
0
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
9640
0
9641
0
    /* XXX verify that the key & kea match */
9642
0
    rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signed_hash);
9643
0
    if (rv != SECSuccess) {
9644
0
        errCode = PORT_GetError();
9645
0
        desc = isTLS ? decrypt_error : handshake_failure;
9646
0
        goto alert_loser;
9647
0
    }
9648
0
9649
0
    signed_hash.data = NULL;
9650
0
9651
0
    if (length != 0) {
9652
0
        desc = isTLS ? decode_error : illegal_parameter;
9653
0
        goto alert_loser; /* malformed */
9654
0
    }
9655
0
9656
0
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify,
9657
0
                                  savedMsg, savedLen);
9658
0
    if (rv != SECSuccess) {
9659
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
9660
0
        return rv;
9661
0
    }
9662
0
9663
0
    ss->ssl3.hs.ws = wait_change_cipher;
9664
0
    return SECSuccess;
9665
0
9666
0
alert_loser:
9667
0
    SSL3_SendAlert(ss, alert_fatal, desc);
9668
0
loser:
9669
0
    PORT_SetError(errCode);
9670
0
    return SECFailure;
9671
0
}
9672
9673
/* find a slot that is able to generate a PMS and wrap it with RSA.
9674
 * Then generate and return the PMS.
9675
 * If the serverKeySlot parameter is non-null, this function will use
9676
 * that slot to do the job, otherwise it will find a slot.
9677
 *
9678
 * Called from  ssl3_DeriveConnectionKeys()  (above)
9679
 *      ssl3_SendRSAClientKeyExchange()     (above)
9680
 *      ssl3_HandleRSAClientKeyExchange()  (below)
9681
 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
9682
 */
9683
static PK11SymKey *
9684
ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
9685
                    PK11SlotInfo *serverKeySlot)
9686
0
{
9687
0
    PK11SymKey *pms = NULL;
9688
0
    PK11SlotInfo *slot = serverKeySlot;
9689
0
    void *pwArg = ss->pkcs11PinArg;
9690
0
    SECItem param;
9691
0
    CK_VERSION version;
9692
0
    CK_MECHANISM_TYPE mechanism_array[3];
9693
0
9694
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9695
0
9696
0
    if (slot == NULL) {
9697
0
        SSLCipherAlgorithm calg;
9698
0
        /* The specReadLock would suffice here, but we cannot assert on
9699
0
        ** read locks.  Also, all the callers who call with a non-null
9700
0
        ** slot already hold the SpecWriteLock.
9701
0
        */
9702
0
        PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
9703
0
        PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
9704
0
9705
0
        calg = spec->cipherDef->calg;
9706
0
9707
0
        /* First get an appropriate slot.  */
9708
0
        mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
9709
0
        mechanism_array[1] = CKM_RSA_PKCS;
9710
0
        mechanism_array[2] = ssl3_Alg2Mech(calg);
9711
0
9712
0
        slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
9713
0
        if (slot == NULL) {
9714
0
            /* can't find a slot with all three, find a slot with the minimum */
9715
0
            slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
9716
0
            if (slot == NULL) {
9717
0
                PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
9718
0
                return pms; /* which is NULL */
9719
0
            }
9720
0
        }
9721
0
    }
9722
0
9723
0
    /* Generate the pre-master secret ...  */
9724
0
    if (IS_DTLS(ss)) {
9725
0
        SSL3ProtocolVersion temp;
9726
0
9727
0
        temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
9728
0
        version.major = MSB(temp);
9729
0
        version.minor = LSB(temp);
9730
0
    } else {
9731
0
        version.major = MSB(ss->clientHelloVersion);
9732
0
        version.minor = LSB(ss->clientHelloVersion);
9733
0
    }
9734
0
9735
0
    param.data = (unsigned char *)&version;
9736
0
    param.len = sizeof version;
9737
0
9738
0
    pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
9739
0
    if (!serverKeySlot)
9740
0
        PK11_FreeSlot(slot);
9741
0
    if (pms == NULL) {
9742
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
9743
0
    }
9744
0
    return pms;
9745
0
}
9746
9747
/* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
9748
 * return any indication of failure of the Client Key Exchange message,
9749
 * where that failure is caused by the content of the client's message.
9750
 * This function must not return SECFailure for any reason that is directly
9751
 * or indirectly caused by the content of the client's encrypted PMS.
9752
 * We must not send an alert and also not drop the connection.
9753
 * Instead, we generate a random PMS.  This will cause a failure
9754
 * in the processing the finished message, which is exactly where
9755
 * the failure must occur.
9756
 *
9757
 * Called from ssl3_HandleClientKeyExchange
9758
 */
9759
static SECStatus
9760
ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
9761
                                PRUint8 *b,
9762
                                PRUint32 length,
9763
                                sslKeyPair *serverKeyPair)
9764
0
{
9765
0
    SECStatus rv;
9766
0
    SECItem enc_pms;
9767
0
    PK11SymKey *tmpPms[2] = { NULL, NULL };
9768
0
    PK11SlotInfo *slot;
9769
0
    int useFauxPms = 0;
9770
0
9771
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
9772
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9773
0
    PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
9774
0
9775
0
    enc_pms.data = b;
9776
0
    enc_pms.len = length;
9777
0
9778
0
    if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
9779
0
        PRUint32 kLen;
9780
0
        rv = ssl3_ConsumeHandshakeNumber(ss, &kLen, 2, &enc_pms.data, &enc_pms.len);
9781
0
        if (rv != SECSuccess) {
9782
0
            PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
9783
0
            return SECFailure;
9784
0
        }
9785
0
        if ((unsigned)kLen < enc_pms.len) {
9786
0
            enc_pms.len = kLen;
9787
0
        }
9788
0
    }
9789
0
9790
0
#define currentPms tmpPms[!useFauxPms]
9791
0
#define unusedPms tmpPms[useFauxPms]
9792
0
#define realPms tmpPms[1]
9793
0
#define fauxPms tmpPms[0]
9794
0
9795
0
    /*
9796
0
     * Get as close to algorithm 2 from RFC 5246; Section 7.4.7.1
9797
0
     * as we can within the constraints of the PKCS#11 interface.
9798
0
     *
9799
0
     * 1. Unconditionally generate a bogus PMS (what RFC 5246
9800
0
     *    calls R).
9801
0
     * 2. Attempt the RSA decryption to recover the PMS (what
9802
0
     *    RFC 5246 calls M).
9803
0
     * 3. Set PMS = (M == NULL) ? R : M
9804
0
     * 4. Use ssl3_ComputeMasterSecret(PMS) to attempt to derive
9805
0
     *    the MS from PMS. This includes performing the version
9806
0
     *    check and length check.
9807
0
     * 5. If either the initial RSA decryption failed or
9808
0
     *    ssl3_ComputeMasterSecret(PMS) failed, then discard
9809
0
     *    M and set PMS = R. Else, discard R and set PMS = M.
9810
0
     *
9811
0
     * We do two derivations here because we can't rely on having
9812
0
     * a function that only performs the PMS version and length
9813
0
     * check. The only redundant cost is that this runs the PRF,
9814
0
     * which isn't necessary here.
9815
0
     */
9816
0
9817
0
    /* Generate the bogus PMS (R) */
9818
0
    slot = PK11_GetSlotFromPrivateKey(serverKeyPair->privKey);
9819
0
    if (!slot) {
9820
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
9821
0
        return SECFailure;
9822
0
    }
9823
0
9824
0
    if (!PK11_DoesMechanism(slot, CKM_SSL3_MASTER_KEY_DERIVE)) {
9825
0
        PK11_FreeSlot(slot);
9826
0
        slot = PK11_GetBestSlot(CKM_SSL3_MASTER_KEY_DERIVE, NULL);
9827
0
        if (!slot) {
9828
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
9829
0
            return SECFailure;
9830
0
        }
9831
0
    }
9832
0
9833
0
    ssl_GetSpecWriteLock(ss);
9834
0
    fauxPms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
9835
0
    ssl_ReleaseSpecWriteLock(ss);
9836
0
    PK11_FreeSlot(slot);
9837
0
9838
0
    if (fauxPms == NULL) {
9839
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
9840
0
        return SECFailure;
9841
0
    }
9842
0
9843
0
    /*
9844
0
     * unwrap pms out of the incoming buffer
9845
0
     * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
9846
0
     *  the unwrap.  Rather, it is the mechanism with which the
9847
0
     *      unwrapped pms will be used.
9848
0
     */
9849
0
    realPms = PK11_PubUnwrapSymKey(serverKeyPair->privKey, &enc_pms,
9850
0
                                   CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
9851
0
    /* Temporarily use the PMS if unwrapping the real PMS fails. */
9852
0
    useFauxPms |= (realPms == NULL);
9853
0
9854
0
    /* Attempt to derive the MS from the PMS. This is the only way to
9855
0
     * check the version field in the RSA PMS. If this fails, we
9856
0
     * then use the faux PMS in place of the PMS. Note that this
9857
0
     * operation should never fail if we are using the faux PMS
9858
0
     * since it is correctly formatted. */
9859
0
    rv = ssl3_ComputeMasterSecret(ss, currentPms, NULL);
9860
0
9861
0
    /* If we succeeded, then select the true PMS and discard the
9862
0
     * FPMS. Else, select the FPMS and select the true PMS */
9863
0
    useFauxPms |= (rv != SECSuccess);
9864
0
9865
0
    if (unusedPms) {
9866
0
        PK11_FreeSymKey(unusedPms);
9867
0
    }
9868
0
9869
0
    /* This step will derive the MS from the PMS, among other things. */
9870
0
    rv = ssl3_InitPendingCipherSpecs(ss, currentPms, PR_TRUE);
9871
0
    PK11_FreeSymKey(currentPms);
9872
0
9873
0
    if (rv != SECSuccess) {
9874
0
        (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
9875
0
        return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
9876
0
    }
9877
0
9878
0
#undef currentPms
9879
0
#undef unusedPms
9880
0
#undef realPms
9881
0
#undef fauxPms
9882
0
9883
0
    return SECSuccess;
9884
0
}
9885
9886
static SECStatus
9887
ssl3_HandleDHClientKeyExchange(sslSocket *ss,
9888
                               PRUint8 *b,
9889
                               PRUint32 length,
9890
                               sslKeyPair *serverKeyPair)
9891
0
{
9892
0
    PK11SymKey *pms;
9893
0
    SECStatus rv;
9894
0
    SECKEYPublicKey clntPubKey;
9895
0
    CK_MECHANISM_TYPE target;
9896
0
    PRBool isTLS;
9897
0
9898
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
9899
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9900
0
9901
0
    clntPubKey.keyType = dhKey;
9902
0
    clntPubKey.u.dh.prime.len = serverKeyPair->pubKey->u.dh.prime.len;
9903
0
    clntPubKey.u.dh.prime.data = serverKeyPair->pubKey->u.dh.prime.data;
9904
0
    clntPubKey.u.dh.base.len = serverKeyPair->pubKey->u.dh.base.len;
9905
0
    clntPubKey.u.dh.base.data = serverKeyPair->pubKey->u.dh.base.data;
9906
0
9907
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.dh.publicValue,
9908
0
                                       2, &b, &length);
9909
0
    if (rv != SECSuccess) {
9910
0
        return SECFailure;
9911
0
    }
9912
0
9913
0
    if (!ssl_IsValidDHEShare(&serverKeyPair->pubKey->u.dh.prime,
9914
0
                             &clntPubKey.u.dh.publicValue)) {
9915
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE);
9916
0
        return SECFailure;
9917
0
    }
9918
0
9919
0
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
9920
0
9921
0
    if (isTLS)
9922
0
        target = CKM_TLS_MASTER_KEY_DERIVE_DH;
9923
0
    else
9924
0
        target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
9925
0
9926
0
    /* Determine the PMS */
9927
0
    pms = PK11_PubDerive(serverKeyPair->privKey, &clntPubKey, PR_FALSE, NULL, NULL,
9928
0
                         CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
9929
0
    if (pms == NULL) {
9930
0
        ssl_FreeEphemeralKeyPairs(ss);
9931
0
        ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
9932
0
        return SECFailure;
9933
0
    }
9934
0
9935
0
    rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
9936
0
    PK11_FreeSymKey(pms);
9937
0
    ssl_FreeEphemeralKeyPairs(ss);
9938
0
    return rv;
9939
0
}
9940
9941
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
9942
 * a complete ssl3 ClientKeyExchange message from the remote client
9943
 * Caller must hold Handshake and RecvBuf locks.
9944
 */
9945
static SECStatus
9946
ssl3_HandleClientKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
9947
0
{
9948
0
    sslKeyPair *serverKeyPair = NULL;
9949
0
    SECStatus rv;
9950
0
    const ssl3KEADef *kea_def;
9951
0
9952
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
9953
0
                SSL_GETPID(), ss->fd));
9954
0
9955
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
9956
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9957
0
9958
0
    if (ss->ssl3.hs.ws != wait_client_key) {
9959
0
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
9960
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
9961
0
        return SECFailure;
9962
0
    }
9963
0
9964
0
    kea_def = ss->ssl3.hs.kea_def;
9965
0
9966
0
    if (kea_def->ephemeral) {
9967
0
        sslEphemeralKeyPair *keyPair;
9968
0
        /* There should be exactly one pair. */
9969
0
        PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
9970
0
        PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==
9971
0
                    PR_NEXT_LINK(&ss->ephemeralKeyPairs));
9972
0
        keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs);
9973
0
        serverKeyPair = keyPair->keys;
9974
0
        ss->sec.keaKeyBits =
9975
0
            SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
9976
0
    } else {
9977
0
        serverKeyPair = ss->sec.serverCert->serverKeyPair;
9978
0
        ss->sec.keaKeyBits = ss->sec.serverCert->serverKeyBits;
9979
0
    }
9980
0
9981
0
    if (!serverKeyPair) {
9982
0
        SSL3_SendAlert(ss, alert_fatal, handshake_failure);
9983
0
        PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
9984
0
        return SECFailure;
9985
0
    }
9986
0
    PORT_Assert(serverKeyPair->pubKey);
9987
0
    PORT_Assert(serverKeyPair->privKey);
9988
0
9989
0
    ss->sec.keaType = kea_def->exchKeyType;
9990
0
9991
0
    switch (kea_def->exchKeyType) {
9992
0
        case ssl_kea_rsa:
9993
0
            rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKeyPair);
9994
0
            break;
9995
0
9996
0
        case ssl_kea_dh:
9997
0
            rv = ssl3_HandleDHClientKeyExchange(ss, b, length, serverKeyPair);
9998
0
            break;
9999
0
10000
0
        case ssl_kea_ecdh:
10001
0
            rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, serverKeyPair);
10002
0
            break;
10003
0
10004
0
        default:
10005
0
            (void)ssl3_HandshakeFailure(ss);
10006
0
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
10007
0
            return SECFailure;
10008
0
    }
10009
0
    ssl_FreeEphemeralKeyPairs(ss);
10010
0
    if (rv == SECSuccess) {
10011
0
        ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
10012
0
    } else {
10013
0
        /* PORT_SetError has been called by all the Handle*ClientKeyExchange
10014
0
         * functions above.  However, not all error paths result in an alert, so
10015
0
         * this ensures that the server knows about the error.  Note that if an
10016
0
         * alert was already sent, SSL3_SendAlert() is a noop. */
10017
0
        PRErrorCode errCode = PORT_GetError();
10018
0
        (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10019
0
        PORT_SetError(errCode);
10020
0
    }
10021
0
    return rv;
10022
0
}
10023
10024
/* This is TLS's equivalent of sending a no_certificate alert. */
10025
SECStatus
10026
ssl3_SendEmptyCertificate(sslSocket *ss)
10027
0
{
10028
0
    SECStatus rv;
10029
0
    unsigned int len = 0;
10030
0
    PRBool isTLS13 = PR_FALSE;
10031
0
    const SECItem *context;
10032
0
10033
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
10034
0
        PORT_Assert(ss->ssl3.hs.clientCertRequested);
10035
0
        context = &ss->xtnData.certReqContext;
10036
0
        len = context->len + 1;
10037
0
        isTLS13 = PR_TRUE;
10038
0
    }
10039
0
10040
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate, len + 3);
10041
0
    if (rv != SECSuccess) {
10042
0
        return rv;
10043
0
    }
10044
0
10045
0
    if (isTLS13) {
10046
0
        rv = ssl3_AppendHandshakeVariable(ss, context->data, context->len, 1);
10047
0
        if (rv != SECSuccess) {
10048
0
            return rv;
10049
0
        }
10050
0
    }
10051
0
10052
0
    return ssl3_AppendHandshakeNumber(ss, 0, 3);
10053
0
}
10054
10055
/*
10056
 * NewSessionTicket
10057
 * Called from ssl3_HandleFinished
10058
 */
10059
static SECStatus
10060
ssl3_SendNewSessionTicket(sslSocket *ss)
10061
0
{
10062
0
    SECItem ticket = { 0, NULL, 0 };
10063
0
    SECStatus rv;
10064
0
    NewSessionTicket nticket = { 0 };
10065
0
10066
0
    rv = ssl3_EncodeSessionTicket(ss, &nticket, NULL, 0,
10067
0
                                  ss->ssl3.pwSpec->masterSecret, &ticket);
10068
0
    if (rv != SECSuccess)
10069
0
        goto loser;
10070
0
10071
0
    /* Serialize the handshake message. Length =
10072
0
     * lifetime (4) + ticket length (2) + ticket. */
10073
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
10074
0
                                    4 + 2 + ticket.len);
10075
0
    if (rv != SECSuccess)
10076
0
        goto loser;
10077
0
10078
0
    /* This is a fixed value. */
10079
0
    rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
10080
0
    if (rv != SECSuccess)
10081
0
        goto loser;
10082
0
10083
0
    /* Encode the ticket. */
10084
0
    rv = ssl3_AppendHandshakeVariable(ss, ticket.data, ticket.len, 2);
10085
0
    if (rv != SECSuccess)
10086
0
        goto loser;
10087
0
10088
0
    rv = SECSuccess;
10089
0
10090
0
loser:
10091
0
    if (ticket.data) {
10092
0
        SECITEM_FreeItem(&ticket, PR_FALSE);
10093
0
    }
10094
0
    return rv;
10095
0
}
10096
10097
static SECStatus
10098
ssl3_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
10099
0
{
10100
0
    SECStatus rv;
10101
0
    SECItem ticketData;
10102
0
    PRUint32 temp;
10103
0
10104
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
10105
0
                SSL_GETPID(), ss->fd));
10106
0
10107
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10108
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10109
0
10110
0
    PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
10111
0
    PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket);
10112
0
10113
0
    if (ss->ssl3.hs.ws != wait_new_session_ticket) {
10114
0
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10115
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
10116
0
        return SECFailure;
10117
0
    }
10118
0
10119
0
    /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid
10120
0
     * until it has verified the server's Finished message." See the comment in
10121
0
     * ssl3_FinishHandshake for more details.
10122
0
     */
10123
0
    ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_TimeUsec();
10124
0
    if (length < 4) {
10125
0
        (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
10126
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
10127
0
        return SECFailure;
10128
0
    }
10129
0
10130
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 4, &b, &length);
10131
0
    if (rv != SECSuccess) {
10132
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
10133
0
        return SECFailure;
10134
0
    }
10135
0
    ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = temp;
10136
0
10137
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length);
10138
0
    if (rv != SECSuccess || length != 0) {
10139
0
        (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
10140
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
10141
0
        return SECFailure; /* malformed */
10142
0
    }
10143
0
    /* If the server sent a zero-length ticket, ignore it and keep the
10144
0
     * existing ticket. */
10145
0
    if (ticketData.len != 0) {
10146
0
        rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket,
10147
0
                              &ticketData);
10148
0
        if (rv != SECSuccess) {
10149
0
            return rv;
10150
0
        }
10151
0
        ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE;
10152
0
    }
10153
0
10154
0
    ss->ssl3.hs.ws = wait_change_cipher;
10155
0
    return SECSuccess;
10156
0
}
10157
10158
#ifdef NISCC_TEST
10159
static PRInt32 connNum = 0;
10160
10161
static SECStatus
10162
get_fake_cert(SECItem *pCertItem, int *pIndex)
10163
{
10164
    PRFileDesc *cf;
10165
    char *testdir;
10166
    char *startat;
10167
    char *stopat;
10168
    const char *extension;
10169
    int fileNum;
10170
    PRInt32 numBytes = 0;
10171
    PRStatus prStatus;
10172
    PRFileInfo info;
10173
    char cfn[100];
10174
10175
    pCertItem->data = 0;
10176
    if ((testdir = PR_GetEnvSecure("NISCC_TEST")) == NULL) {
10177
        return SECSuccess;
10178
    }
10179
    *pIndex = (NULL != strstr(testdir, "root"));
10180
    extension = (strstr(testdir, "simple") ? "" : ".der");
10181
    fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1;
10182
    if ((startat = PR_GetEnvSecure("START_AT")) != NULL) {
10183
        fileNum += atoi(startat);
10184
    }
10185
    if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL &&
10186
        fileNum >= atoi(stopat)) {
10187
        *pIndex = -1;
10188
        return SECSuccess;
10189
    }
10190
    sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension);
10191
    cf = PR_Open(cfn, PR_RDONLY, 0);
10192
    if (!cf) {
10193
        goto loser;
10194
    }
10195
    prStatus = PR_GetOpenFileInfo(cf, &info);
10196
    if (prStatus != PR_SUCCESS) {
10197
        PR_Close(cf);
10198
        goto loser;
10199
    }
10200
    pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
10201
    if (pCertItem) {
10202
        numBytes = PR_Read(cf, pCertItem->data, info.size);
10203
    }
10204
    PR_Close(cf);
10205
    if (numBytes != info.size) {
10206
        SECITEM_FreeItem(pCertItem, PR_FALSE);
10207
        PORT_SetError(SEC_ERROR_IO);
10208
        goto loser;
10209
    }
10210
    fprintf(stderr, "using %s\n", cfn);
10211
    return SECSuccess;
10212
10213
loser:
10214
    fprintf(stderr, "failed to use %s\n", cfn);
10215
    *pIndex = -1;
10216
    return SECFailure;
10217
}
10218
#endif
10219
10220
/*
10221
 * Used by both client and server.
10222
 * Called from HandleServerHelloDone and from SendServerHelloSequence.
10223
 */
10224
static SECStatus
10225
ssl3_SendCertificate(sslSocket *ss)
10226
0
{
10227
0
    SECStatus rv;
10228
0
    CERTCertificateList *certChain;
10229
0
    int certChainLen = 0;
10230
0
    int i;
10231
#ifdef NISCC_TEST
10232
    SECItem fakeCert;
10233
    int ndex = -1;
10234
#endif
10235
0
    PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
10236
0
    SECItem context = { siBuffer, NULL, 0 };
10237
0
    unsigned int contextLen = 0;
10238
0
10239
0
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
10240
0
                SSL_GETPID(), ss->fd));
10241
0
10242
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10243
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10244
0
10245
0
    if (ss->sec.localCert)
10246
0
        CERT_DestroyCertificate(ss->sec.localCert);
10247
0
    if (ss->sec.isServer) {
10248
0
        /* A server certificate is selected in ssl3_HandleClientHello. */
10249
0
        PORT_Assert(ss->sec.serverCert);
10250
0
10251
0
        certChain = ss->sec.serverCert->serverCertChain;
10252
0
        ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
10253
0
    } else {
10254
0
        certChain = ss->ssl3.clientCertChain;
10255
0
        ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
10256
0
    }
10257
0
10258
#ifdef NISCC_TEST
10259
    rv = get_fake_cert(&fakeCert, &ndex);
10260
#endif
10261
10262
0
    if (isTLS13) {
10263
0
        contextLen = 1; /* Size of the context length */
10264
0
        if (!ss->sec.isServer) {
10265
0
            PORT_Assert(ss->ssl3.hs.clientCertRequested);
10266
0
            context = ss->xtnData.certReqContext;
10267
0
            contextLen += context.len;
10268
0
        }
10269
0
    }
10270
0
    if (certChain) {
10271
0
        for (i = 0; i < certChain->len; i++) {
10272
#ifdef NISCC_TEST
10273
            if (fakeCert.len > 0 && i == ndex) {
10274
                certChainLen += fakeCert.len + 3;
10275
            } else {
10276
                certChainLen += certChain->certs[i].len + 3;
10277
            }
10278
#else
10279
            certChainLen += certChain->certs[i].len + 3;
10280
0
#endif
10281
0
        }
10282
0
    }
10283
0
10284
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate,
10285
0
                                    contextLen + certChainLen + 3);
10286
0
    if (rv != SECSuccess) {
10287
0
        return rv; /* err set by AppendHandshake. */
10288
0
    }
10289
0
10290
0
    if (isTLS13) {
10291
0
        rv = ssl3_AppendHandshakeVariable(ss, context.data,
10292
0
                                          context.len, 1);
10293
0
        if (rv != SECSuccess) {
10294
0
            return rv; /* err set by AppendHandshake. */
10295
0
        }
10296
0
    }
10297
0
10298
0
    rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3);
10299
0
    if (rv != SECSuccess) {
10300
0
        return rv; /* err set by AppendHandshake. */
10301
0
    }
10302
0
    if (certChain) {
10303
0
        for (i = 0; i < certChain->len; i++) {
10304
#ifdef NISCC_TEST
10305
            if (fakeCert.len > 0 && i == ndex) {
10306
                rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
10307
                                                  fakeCert.len, 3);
10308
                SECITEM_FreeItem(&fakeCert, PR_FALSE);
10309
            } else {
10310
                rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
10311
                                                  certChain->certs[i].len, 3);
10312
            }
10313
#else
10314
            rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
10315
0
                                              certChain->certs[i].len, 3);
10316
0
#endif
10317
0
            if (rv != SECSuccess) {
10318
0
                return rv; /* err set by AppendHandshake. */
10319
0
            }
10320
0
        }
10321
0
    }
10322
0
10323
0
    return SECSuccess;
10324
0
}
10325
10326
/*
10327
 * Used by server only.
10328
 * single-stapling, send only a single cert status
10329
 */
10330
SECStatus
10331
ssl3_SendCertificateStatus(sslSocket *ss)
10332
0
{
10333
0
    SECStatus rv;
10334
0
    int len = 0;
10335
0
    SECItemArray *statusToSend = NULL;
10336
0
    const sslServerCert *serverCert;
10337
0
10338
0
    SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
10339
0
                SSL_GETPID(), ss->fd));
10340
0
10341
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10342
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10343
0
    PORT_Assert(ss->sec.isServer);
10344
0
10345
0
    if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
10346
0
        return SECSuccess;
10347
0
10348
0
    /* Use certStatus based on the cert being used. */
10349
0
    serverCert = ss->sec.serverCert;
10350
0
    if (serverCert->certStatusArray && serverCert->certStatusArray->len) {
10351
0
        statusToSend = serverCert->certStatusArray;
10352
0
    }
10353
0
    if (!statusToSend)
10354
0
        return SECSuccess;
10355
0
10356
0
    /* Use the array's first item only (single stapling) */
10357
0
    len = 1 + statusToSend->items[0].len + 3;
10358
0
10359
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_status, len);
10360
0
    if (rv != SECSuccess) {
10361
0
        return rv; /* err set by AppendHandshake. */
10362
0
    }
10363
0
    rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
10364
0
    if (rv != SECSuccess)
10365
0
        return rv; /* err set by AppendHandshake. */
10366
0
10367
0
    rv = ssl3_AppendHandshakeVariable(ss,
10368
0
                                      statusToSend->items[0].data,
10369
0
                                      statusToSend->items[0].len,
10370
0
                                      3);
10371
0
    if (rv != SECSuccess)
10372
0
        return rv; /* err set by AppendHandshake. */
10373
0
10374
0
    return SECSuccess;
10375
0
}
10376
10377
/* This is used to delete the CA certificates in the peer certificate chain
10378
 * from the cert database after they've been validated.
10379
 */
10380
void
10381
ssl3_CleanupPeerCerts(sslSocket *ss)
10382
0
{
10383
0
    PLArenaPool *arena = ss->ssl3.peerCertArena;
10384
0
    ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
10385
0
10386
0
    for (; certs; certs = certs->next) {
10387
0
        CERT_DestroyCertificate(certs->cert);
10388
0
    }
10389
0
    if (arena)
10390
0
        PORT_FreeArena(arena, PR_FALSE);
10391
0
    ss->ssl3.peerCertArena = NULL;
10392
0
    ss->ssl3.peerCertChain = NULL;
10393
0
10394
0
    if (ss->sec.peerCert != NULL) {
10395
0
        if (ss->sec.peerKey) {
10396
0
            SECKEY_DestroyPublicKey(ss->sec.peerKey);
10397
0
            ss->sec.peerKey = NULL;
10398
0
        }
10399
0
        CERT_DestroyCertificate(ss->sec.peerCert);
10400
0
        ss->sec.peerCert = NULL;
10401
0
    }
10402
0
}
10403
10404
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10405
 * a complete ssl3 CertificateStatus message.
10406
 * Caller must hold Handshake and RecvBuf locks.
10407
 */
10408
static SECStatus
10409
ssl3_HandleCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
10410
0
{
10411
0
    SECStatus rv;
10412
0
10413
0
    if (ss->ssl3.hs.ws != wait_certificate_status) {
10414
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10415
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
10416
0
        return SECFailure;
10417
0
    }
10418
0
10419
0
    rv = ssl_ReadCertificateStatus(ss, b, length);
10420
0
    if (rv != SECSuccess) {
10421
0
        return SECFailure; /* code already set */
10422
0
    }
10423
0
10424
0
    return ssl3_AuthCertificate(ss);
10425
0
}
10426
10427
SECStatus
10428
ssl_ReadCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
10429
0
{
10430
0
    PRUint32 status, len;
10431
0
    SECStatus rv;
10432
0
10433
0
    PORT_Assert(!ss->sec.isServer);
10434
0
10435
0
    /* Consume the CertificateStatusType enum */
10436
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &status, 1, &b, &length);
10437
0
    if (rv != SECSuccess || status != 1 /* ocsp */) {
10438
0
        return ssl3_DecodeError(ss);
10439
0
    }
10440
0
10441
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &len, 3, &b, &length);
10442
0
    if (rv != SECSuccess || len != length) {
10443
0
        return ssl3_DecodeError(ss);
10444
0
    }
10445
0
10446
0
#define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */
10447
0
    if (length > MAX_CERTSTATUS_LEN) {
10448
0
        ssl3_DecodeError(ss); /* sets error code */
10449
0
        return SECFailure;
10450
0
    }
10451
0
#undef MAX_CERTSTATUS_LEN
10452
0
10453
0
    /* Array size 1, because we currently implement single-stapling only */
10454
0
    SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
10455
0
    if (!ss->sec.ci.sid->peerCertStatus.items)
10456
0
        return SECFailure; /* code already set */
10457
0
10458
0
    ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
10459
0
10460
0
    if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
10461
0
        SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
10462
0
        return SECFailure; /* code already set */
10463
0
    }
10464
0
10465
0
    PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
10466
0
    ss->sec.ci.sid->peerCertStatus.items[0].len = length;
10467
0
    ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
10468
0
    return SECSuccess;
10469
0
}
10470
10471
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10472
 * a complete ssl3 Certificate message.
10473
 * Caller must hold Handshake and RecvBuf locks.
10474
 */
10475
static SECStatus
10476
ssl3_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
10477
0
{
10478
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
10479
0
                SSL_GETPID(), ss->fd));
10480
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10481
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10482
0
10483
0
    if ((ss->sec.isServer && ss->ssl3.hs.ws != wait_client_cert) ||
10484
0
        (!ss->sec.isServer && ss->ssl3.hs.ws != wait_server_cert)) {
10485
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10486
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE);
10487
0
        return SECFailure;
10488
0
    }
10489
0
10490
0
    if (ss->sec.isServer) {
10491
0
        dtls_ReceivedFirstMessageInFlight(ss);
10492
0
    }
10493
0
10494
0
    return ssl3_CompleteHandleCertificate(ss, b, length);
10495
0
}
10496
10497
/* Called from ssl3_HandleCertificate
10498
 */
10499
SECStatus
10500
ssl3_CompleteHandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
10501
0
{
10502
0
    ssl3CertNode *c;
10503
0
    ssl3CertNode *lastCert = NULL;
10504
0
    PRUint32 remaining = 0;
10505
0
    PRUint32 size;
10506
0
    SECStatus rv;
10507
0
    PRBool isServer = ss->sec.isServer;
10508
0
    PRBool isTLS;
10509
0
    SSL3AlertDescription desc;
10510
0
    int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
10511
0
    SECItem certItem;
10512
0
10513
0
    ssl3_CleanupPeerCerts(ss);
10514
0
    isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
10515
0
10516
0
    /* It is reported that some TLS client sends a Certificate message
10517
0
    ** with a zero-length message body.  We'll treat that case like a
10518
0
    ** normal no_certificates message to maximize interoperability.
10519
0
    */
10520
0
    if (length) {
10521
0
        rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 3, &b, &length);
10522
0
        if (rv != SECSuccess)
10523
0
            goto loser; /* fatal alert already sent by ConsumeHandshake. */
10524
0
        if (remaining > length)
10525
0
            goto decode_loser;
10526
0
    }
10527
0
10528
0
    if (!remaining) {
10529
0
        if (!(isTLS && isServer)) {
10530
0
            desc = bad_certificate;
10531
0
            goto alert_loser;
10532
0
        }
10533
0
        /* This is TLS's version of a no_certificate alert. */
10534
0
        /* I'm a server. I've requested a client cert. He hasn't got one. */
10535
0
        rv = ssl3_HandleNoCertificate(ss);
10536
0
        if (rv != SECSuccess) {
10537
0
            errCode = PORT_GetError();
10538
0
            goto loser;
10539
0
        }
10540
0
10541
0
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
10542
0
            ss->ssl3.hs.ws = wait_client_key;
10543
0
        } else {
10544
0
            TLS13_SET_HS_STATE(ss, wait_finished);
10545
0
        }
10546
0
        return SECSuccess;
10547
0
    }
10548
0
10549
0
    ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
10550
0
    if (ss->ssl3.peerCertArena == NULL) {
10551
0
        goto loser; /* don't send alerts on memory errors */
10552
0
    }
10553
0
10554
0
    /* First get the peer cert. */
10555
0
    if (remaining < 3)
10556
0
        goto decode_loser;
10557
0
10558
0
    remaining -= 3;
10559
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
10560
0
    if (rv != SECSuccess)
10561
0
        goto loser; /* fatal alert already sent by ConsumeHandshake. */
10562
0
    if (size == 0 || remaining < size)
10563
0
        goto decode_loser;
10564
0
10565
0
    certItem.data = b;
10566
0
    certItem.len = size;
10567
0
    b += size;
10568
0
    length -= size;
10569
0
    remaining -= size;
10570
0
10571
0
    ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
10572
0
                                               PR_FALSE, PR_TRUE);
10573
0
    if (ss->sec.peerCert == NULL) {
10574
0
        /* We should report an alert if the cert was bad, but not if the
10575
0
         * problem was just some local problem, like memory error.
10576
0
         */
10577
0
        goto ambiguous_err;
10578
0
    }
10579
0
10580
0
    /* Now get all of the CA certs. */
10581
0
    while (remaining > 0) {
10582
0
        if (remaining < 3)
10583
0
            goto decode_loser;
10584
0
10585
0
        remaining -= 3;
10586
0
        rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
10587
0
        if (rv != SECSuccess)
10588
0
            goto loser; /* fatal alert already sent by ConsumeHandshake. */
10589
0
        if (size == 0 || remaining < size)
10590
0
            goto decode_loser;
10591
0
10592
0
        certItem.data = b;
10593
0
        certItem.len = size;
10594
0
        b += size;
10595
0
        length -= size;
10596
0
        remaining -= size;
10597
0
10598
0
        c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
10599
0
        if (c == NULL) {
10600
0
            goto loser; /* don't send alerts on memory errors */
10601
0
        }
10602
0
10603
0
        c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
10604
0
                                          PR_FALSE, PR_TRUE);
10605
0
        if (c->cert == NULL) {
10606
0
            goto ambiguous_err;
10607
0
        }
10608
0
10609
0
        c->next = NULL;
10610
0
        if (lastCert) {
10611
0
            lastCert->next = c;
10612
0
        } else {
10613
0
            ss->ssl3.peerCertChain = c;
10614
0
        }
10615
0
        lastCert = c;
10616
0
    }
10617
0
10618
0
    SECKEY_UpdateCertPQG(ss->sec.peerCert);
10619
0
10620
0
    if (!isServer &&
10621
0
        ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
10622
0
        ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
10623
0
        ss->ssl3.hs.ws = wait_certificate_status;
10624
0
        rv = SECSuccess;
10625
0
    } else {
10626
0
        rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
10627
0
    }
10628
0
10629
0
    return rv;
10630
0
10631
0
ambiguous_err:
10632
0
    errCode = PORT_GetError();
10633
0
    switch (errCode) {
10634
0
        case PR_OUT_OF_MEMORY_ERROR:
10635
0
        case SEC_ERROR_BAD_DATABASE:
10636
0
        case SEC_ERROR_NO_MEMORY:
10637
0
            if (isTLS) {
10638
0
                desc = internal_error;
10639
0
                goto alert_loser;
10640
0
            }
10641
0
            goto loser;
10642
0
    }
10643
0
    ssl3_SendAlertForCertError(ss, errCode);
10644
0
    goto loser;
10645
0
10646
0
decode_loser:
10647
0
    desc = isTLS ? decode_error : bad_certificate;
10648
0
10649
0
alert_loser:
10650
0
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
10651
0
10652
0
loser:
10653
0
    (void)ssl_MapLowLevelError(errCode);
10654
0
    return SECFailure;
10655
0
}
10656
10657
SECStatus
10658
ssl3_AuthCertificate(sslSocket *ss)
10659
0
{
10660
0
    SECStatus rv;
10661
0
    PRBool isServer = ss->sec.isServer;
10662
0
    int errCode;
10663
0
10664
0
    ss->ssl3.hs.authCertificatePending = PR_FALSE;
10665
0
10666
0
    PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
10667
0
                ssl_preinfo_all);
10668
0
    /*
10669
0
     * Ask caller-supplied callback function to validate cert chain.
10670
0
     */
10671
0
    rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
10672
0
                                           PR_TRUE, isServer);
10673
0
    if (rv != SECSuccess) {
10674
0
        errCode = PORT_GetError();
10675
0
        if (errCode == 0) {
10676
0
            errCode = SSL_ERROR_BAD_CERTIFICATE;
10677
0
        }
10678
0
        if (rv != SECWouldBlock) {
10679
0
            if (ss->handleBadCert) {
10680
0
                rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
10681
0
            }
10682
0
        }
10683
0
10684
0
        if (rv == SECWouldBlock) {
10685
0
            if (ss->sec.isServer) {
10686
0
                errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
10687
0
                goto loser;
10688
0
            }
10689
0
10690
0
            ss->ssl3.hs.authCertificatePending = PR_TRUE;
10691
0
            rv = SECSuccess;
10692
0
        }
10693
0
10694
0
        if (rv != SECSuccess) {
10695
0
            ssl3_SendAlertForCertError(ss, errCode);
10696
0
            goto loser;
10697
0
        }
10698
0
    }
10699
0
10700
0
    ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
10701
0
10702
0
    if (!ss->sec.isServer) {
10703
0
        CERTCertificate *cert = ss->sec.peerCert;
10704
0
10705
0
        /* set the server authentication type and size from the value
10706
0
        ** in the cert. */
10707
0
        SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(cert);
10708
0
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
10709
0
            /* These are filled in in tls13_HandleCertificateVerify and
10710
0
             * tls13_HandleServerKeyShare. */
10711
0
            ss->sec.authType = ss->ssl3.hs.kea_def->authKeyType;
10712
0
            ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
10713
0
        }
10714
0
        if (pubKey) {
10715
0
            KeyType pubKeyType;
10716
0
            PRUint32 minKey;
10717
0
            PRInt32 optval;
10718
0
            /* This partly fixes Bug 124230 and may cause problems for
10719
0
             * callers which depend on the old (wrong) behavior. */
10720
0
            ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(pubKey);
10721
0
            pubKeyType = SECKEY_GetPublicKeyType(pubKey);
10722
0
            minKey = ss->sec.authKeyBits;
10723
0
            switch (pubKeyType) {
10724
0
                case rsaKey:
10725
0
                case rsaPssKey:
10726
0
                case rsaOaepKey:
10727
0
                    rv =
10728
0
                        NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &optval);
10729
0
                    if (rv == SECSuccess && optval > 0) {
10730
0
                        minKey = (PRUint32)optval;
10731
0
                    } else {
10732
0
                        minKey = SSL_RSA_MIN_MODULUS_BITS;
10733
0
                    }
10734
0
                    break;
10735
0
                case dsaKey:
10736
0
                    rv =
10737
0
                        NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &optval);
10738
0
                    if (rv == SECSuccess && optval > 0) {
10739
0
                        minKey = (PRUint32)optval;
10740
0
                    } else {
10741
0
                        minKey = SSL_DSA_MIN_P_BITS;
10742
0
                    }
10743
0
                    break;
10744
0
                case dhKey:
10745
0
                    rv =
10746
0
                        NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &optval);
10747
0
                    if (rv == SECSuccess && optval > 0) {
10748
0
                        minKey = (PRUint32)optval;
10749
0
                    } else {
10750
0
                        minKey = SSL_DH_MIN_P_BITS;
10751
0
                    }
10752
0
                    break;
10753
0
                default:
10754
0
                    break;
10755
0
            }
10756
0
10757
0
            /* Too small: not good enough. Send a fatal alert. */
10758
0
            /* We aren't checking EC here on the understanding that we only
10759
0
             * support curves we like, a decision that might need revisiting. */
10760
0
            if (ss->sec.authKeyBits < minKey) {
10761
0
                PORT_SetError(SSL_ERROR_WEAK_SERVER_CERT_KEY);
10762
0
                (void)SSL3_SendAlert(ss, alert_fatal,
10763
0
                                     ss->version >= SSL_LIBRARY_VERSION_TLS_1_0
10764
0
                                         ? insufficient_security
10765
0
                                         : illegal_parameter);
10766
0
                SECKEY_DestroyPublicKey(pubKey);
10767
0
                return SECFailure;
10768
0
            }
10769
0
            SECKEY_DestroyPublicKey(pubKey);
10770
0
            pubKey = NULL;
10771
0
        }
10772
0
10773
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
10774
0
            TLS13_SET_HS_STATE(ss, wait_cert_verify);
10775
0
        } else {
10776
0
            /* Ephemeral suites require ServerKeyExchange. */
10777
0
            if (ss->ssl3.hs.kea_def->ephemeral) {
10778
0
                /* require server_key_exchange */
10779
0
                ss->ssl3.hs.ws = wait_server_key;
10780
0
            } else {
10781
0
                /* disallow server_key_exchange */
10782
0
                ss->ssl3.hs.ws = wait_cert_request;
10783
0
                /* This is static RSA key exchange so set the key exchange
10784
0
                 * details to compensate for that. */
10785
0
                ss->sec.keaKeyBits = ss->sec.authKeyBits;
10786
0
                ss->sec.signatureScheme = ssl_sig_none;
10787
0
                ss->sec.keaGroup = NULL;
10788
0
            }
10789
0
        }
10790
0
    } else {
10791
0
        /* Server */
10792
0
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
10793
0
            ss->ssl3.hs.ws = wait_client_key;
10794
0
        } else {
10795
0
            TLS13_SET_HS_STATE(ss, wait_cert_verify);
10796
0
        }
10797
0
    }
10798
0
10799
0
    PORT_Assert(rv == SECSuccess);
10800
0
    if (rv != SECSuccess) {
10801
0
        errCode = SEC_ERROR_LIBRARY_FAILURE;
10802
0
        goto loser;
10803
0
    }
10804
0
10805
0
    return SECSuccess;
10806
0
10807
0
loser:
10808
0
    (void)ssl_MapLowLevelError(errCode);
10809
0
    return SECFailure;
10810
0
}
10811
10812
static SECStatus ssl3_FinishHandshake(sslSocket *ss);
10813
10814
static SECStatus
10815
ssl3_AlwaysFail(sslSocket *ss)
10816
0
{
10817
0
    PORT_SetError(PR_INVALID_STATE_ERROR);
10818
0
    return SECFailure;
10819
0
}
10820
10821
/* Caller must hold 1stHandshakeLock.
10822
*/
10823
SECStatus
10824
ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
10825
0
{
10826
0
    SECStatus rv;
10827
0
10828
0
    PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
10829
0
10830
0
    if (ss->sec.isServer) {
10831
0
        PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
10832
0
        return SECFailure;
10833
0
    }
10834
0
10835
0
    ssl_GetRecvBufLock(ss);
10836
0
    ssl_GetSSL3HandshakeLock(ss);
10837
0
10838
0
    if (!ss->ssl3.hs.authCertificatePending) {
10839
0
        PORT_SetError(PR_INVALID_STATE_ERROR);
10840
0
        rv = SECFailure;
10841
0
        goto done;
10842
0
    }
10843
0
10844
0
    ss->ssl3.hs.authCertificatePending = PR_FALSE;
10845
0
10846
0
    if (error != 0) {
10847
0
        ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
10848
0
        ssl3_SendAlertForCertError(ss, error);
10849
0
        rv = SECSuccess;
10850
0
    } else if (ss->ssl3.hs.restartTarget != NULL) {
10851
0
        sslRestartTarget target = ss->ssl3.hs.restartTarget;
10852
0
        ss->ssl3.hs.restartTarget = NULL;
10853
0
10854
0
        if (target == ssl3_FinishHandshake) {
10855
0
            SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication lost the race"
10856
0
                        " with peer's finished message",
10857
0
                        SSL_GETPID(), ss->fd));
10858
0
        }
10859
0
10860
0
        rv = target(ss);
10861
0
        /* Even if we blocked here, we have accomplished enough to claim
10862
0
         * success. Any remaining work will be taken care of by subsequent
10863
0
         * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc.
10864
0
         */
10865
0
        if (rv == SECWouldBlock) {
10866
0
            rv = SECSuccess;
10867
0
        }
10868
0
    } else {
10869
0
        SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with"
10870
0
                    " peer's finished message",
10871
0
                    SSL_GETPID(), ss->fd));
10872
0
10873
0
        PORT_Assert(!ss->ssl3.hs.isResuming);
10874
0
        PORT_Assert(ss->ssl3.hs.ws != idle_handshake);
10875
0
10876
0
        if (ss->opt.enableFalseStart &&
10877
0
            !ss->firstHsDone &&
10878
0
            !ss->ssl3.hs.isResuming &&
10879
0
            ssl3_WaitingForServerSecondRound(ss)) {
10880
0
            /* ssl3_SendClientSecondRound deferred the false start check because
10881
0
             * certificate authentication was pending, so we do it now if we still
10882
0
             * haven't received all of the server's second round yet.
10883
0
             */
10884
0
            rv = ssl3_CheckFalseStart(ss);
10885
0
        } else {
10886
0
            rv = SECSuccess;
10887
0
        }
10888
0
    }
10889
0
10890
0
done:
10891
0
    ssl_ReleaseSSL3HandshakeLock(ss);
10892
0
    ssl_ReleaseRecvBufLock(ss);
10893
0
10894
0
    return rv;
10895
0
}
10896
10897
static SECStatus
10898
ssl3_ComputeTLSFinished(sslSocket *ss, ssl3CipherSpec *spec,
10899
                        PRBool isServer,
10900
                        const SSL3Hashes *hashes,
10901
                        TLSFinished *tlsFinished)
10902
0
{
10903
0
    SECStatus rv;
10904
0
    CK_TLS_MAC_PARAMS tls_mac_params;
10905
0
    SECItem param = { siBuffer, NULL, 0 };
10906
0
    PK11Context *prf_context;
10907
0
    unsigned int retLen;
10908
0
10909
0
    PORT_Assert(spec->masterSecret);
10910
0
    if (!spec->masterSecret) {
10911
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10912
0
        return SECFailure;
10913
0
    }
10914
0
10915
0
    if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) {
10916
0
        tls_mac_params.prfMechanism = CKM_TLS_PRF;
10917
0
    } else {
10918
0
        tls_mac_params.prfMechanism = ssl3_GetPrfHashMechanism(ss);
10919
0
    }
10920
0
    tls_mac_params.ulMacLength = 12;
10921
0
    tls_mac_params.ulServerOrClient = isServer ? 1 : 2;
10922
0
    param.data = (unsigned char *)&tls_mac_params;
10923
0
    param.len = sizeof(tls_mac_params);
10924
0
    prf_context = PK11_CreateContextBySymKey(CKM_TLS_MAC, CKA_SIGN,
10925
0
                                             spec->masterSecret, &param);
10926
0
    if (!prf_context)
10927
0
        return SECFailure;
10928
0
10929
0
    rv = PK11_DigestBegin(prf_context);
10930
0
    rv |= PK11_DigestOp(prf_context, hashes->u.raw, hashes->len);
10931
0
    rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data, &retLen,
10932
0
                           sizeof tlsFinished->verify_data);
10933
0
    PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data);
10934
0
10935
0
    PK11_DestroyContext(prf_context, PR_TRUE);
10936
0
10937
0
    return rv;
10938
0
}
10939
10940
/* The calling function must acquire and release the appropriate
10941
 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
10942
 * ss->ssl3.crSpec).
10943
 */
10944
SECStatus
10945
ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec,
10946
                            const char *label, unsigned int labelLen,
10947
                            const unsigned char *val, unsigned int valLen,
10948
                            unsigned char *out, unsigned int outLen)
10949
0
{
10950
0
    SECItem param = { siBuffer, NULL, 0 };
10951
0
    CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
10952
0
    PK11Context *prf_context;
10953
0
    unsigned int retLen;
10954
0
    SECStatus rv;
10955
0
10956
0
    if (!spec->masterSecret) {
10957
0
        PORT_Assert(spec->masterSecret);
10958
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10959
0
        return SECFailure;
10960
0
    }
10961
0
10962
0
    if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
10963
0
        /* Bug 1312976 non-SHA256 exporters are broken. */
10964
0
        if (ssl3_GetPrfHashMechanism(ss) != CKM_SHA256) {
10965
0
            PORT_Assert(0);
10966
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
10967
0
            return SECFailure;
10968
0
        }
10969
0
        mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
10970
0
    }
10971
0
    prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
10972
0
                                             spec->masterSecret, &param);
10973
0
    if (!prf_context)
10974
0
        return SECFailure;
10975
0
10976
0
    rv = PK11_DigestBegin(prf_context);
10977
0
    rv |= PK11_DigestOp(prf_context, (unsigned char *)label, labelLen);
10978
0
    rv |= PK11_DigestOp(prf_context, val, valLen);
10979
0
    rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
10980
0
    PORT_Assert(rv != SECSuccess || retLen == outLen);
10981
0
10982
0
    PK11_DestroyContext(prf_context, PR_TRUE);
10983
0
    return rv;
10984
0
}
10985
10986
/* called from ssl3_SendClientSecondRound
10987
 *             ssl3_HandleFinished
10988
 */
10989
static SECStatus
10990
ssl3_SendNextProto(sslSocket *ss)
10991
0
{
10992
0
    SECStatus rv;
10993
0
    int padding_len;
10994
0
    static const unsigned char padding[32] = { 0 };
10995
0
10996
0
    if (ss->xtnData.nextProto.len == 0 ||
10997
0
        ss->xtnData.nextProtoState == SSL_NEXT_PROTO_SELECTED) {
10998
0
        return SECSuccess;
10999
0
    }
11000
0
11001
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11002
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11003
0
11004
0
    padding_len = 32 - ((ss->xtnData.nextProto.len + 2) % 32);
11005
0
11006
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_next_proto, ss->xtnData.nextProto.len + 2 + padding_len);
11007
0
    if (rv != SECSuccess) {
11008
0
        return rv; /* error code set by AppendHandshakeHeader */
11009
0
    }
11010
0
    rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.nextProto.data,
11011
0
                                      ss->xtnData.nextProto.len, 1);
11012
0
    if (rv != SECSuccess) {
11013
0
        return rv; /* error code set by AppendHandshake */
11014
0
    }
11015
0
    rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
11016
0
    if (rv != SECSuccess) {
11017
0
        return rv; /* error code set by AppendHandshake */
11018
0
    }
11019
0
    return rv;
11020
0
}
11021
11022
/* called from ssl3_SendFinished and tls13_DeriveSecret.
11023
 *
11024
 * This function is simply a debugging aid and therefore does not return a
11025
 * SECStatus. */
11026
void
11027
ssl3_RecordKeyLog(sslSocket *ss, const char *label, PK11SymKey *secret)
11028
0
{
11029
0
#ifdef NSS_ALLOW_SSLKEYLOGFILE
11030
0
    SECStatus rv;
11031
0
    SECItem *keyData;
11032
0
    /* Longest label is "CLIENT_HANDSHAKE_TRAFFIC_SECRET", master secret is 48
11033
0
     * bytes which happens to be the largest in TLS 1.3 as well (SHA384).
11034
0
     * Maximum line length: "CLIENT_HANDSHAKE_TRAFFIC_SECRET" (31) + " " (1) +
11035
0
     * client_random (32*2) + " " (1) +
11036
0
     * traffic_secret (48*2) + "\n" (1) = 194. */
11037
0
    char buf[200];
11038
0
    unsigned int offset, len;
11039
0
11040
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11041
0
11042
0
    if (!ssl_keylog_iob)
11043
0
        return;
11044
0
11045
0
    rv = PK11_ExtractKeyValue(secret);
11046
0
    if (rv != SECSuccess)
11047
0
        return;
11048
0
11049
0
    /* keyData does not need to be freed. */
11050
0
    keyData = PK11_GetKeyData(secret);
11051
0
    if (!keyData || !keyData->data)
11052
0
        return;
11053
0
11054
0
    len = strlen(label) + 1 +          /* label + space */
11055
0
          SSL3_RANDOM_LENGTH * 2 + 1 + /* client random (hex) + space */
11056
0
          keyData->len * 2 + 1;        /* secret (hex) + newline */
11057
0
    PORT_Assert(len <= sizeof(buf));
11058
0
    if (len > sizeof(buf))
11059
0
        return;
11060
0
11061
0
    /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
11062
0
11063
0
    /* There could be multiple, concurrent writers to the
11064
0
     * keylog, so we have to do everything in a single call to
11065
0
     * fwrite. */
11066
0
11067
0
    strcpy(buf, label);
11068
0
    offset = strlen(label);
11069
0
    buf[offset++] += ' ';
11070
0
    hexEncode(buf + offset, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
11071
0
    offset += SSL3_RANDOM_LENGTH * 2;
11072
0
    buf[offset++] = ' ';
11073
0
    hexEncode(buf + offset, keyData->data, keyData->len);
11074
0
    offset += keyData->len * 2;
11075
0
    buf[offset++] = '\n';
11076
0
11077
0
    PORT_Assert(offset == len);
11078
0
11079
0
    PZ_Lock(ssl_keylog_lock);
11080
0
    if (fwrite(buf, len, 1, ssl_keylog_iob) == 1)
11081
0
        fflush(ssl_keylog_iob);
11082
0
    PZ_Unlock(ssl_keylog_lock);
11083
0
#endif
11084
0
}
11085
11086
/* called from ssl3_SendClientSecondRound
11087
 *             ssl3_HandleClientHello
11088
 *             ssl3_HandleFinished
11089
 */
11090
static SECStatus
11091
ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
11092
0
{
11093
0
    ssl3CipherSpec *cwSpec;
11094
0
    PRBool isTLS;
11095
0
    PRBool isServer = ss->sec.isServer;
11096
0
    SECStatus rv;
11097
0
    SSL3Sender sender = isServer ? sender_server : sender_client;
11098
0
    SSL3Hashes hashes;
11099
0
    TLSFinished tlsFinished;
11100
0
11101
0
    SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
11102
0
11103
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11104
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11105
0
11106
0
    ssl_GetSpecReadLock(ss);
11107
0
    cwSpec = ss->ssl3.cwSpec;
11108
0
    isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
11109
0
    rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
11110
0
    if (isTLS && rv == SECSuccess) {
11111
0
        rv = ssl3_ComputeTLSFinished(ss, cwSpec, isServer, &hashes, &tlsFinished);
11112
0
    }
11113
0
    ssl_ReleaseSpecReadLock(ss);
11114
0
    if (rv != SECSuccess) {
11115
0
        goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */
11116
0
    }
11117
0
11118
0
    if (isTLS) {
11119
0
        if (isServer)
11120
0
            ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
11121
0
        else
11122
0
            ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
11123
0
        ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
11124
0
        rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof tlsFinished);
11125
0
        if (rv != SECSuccess)
11126
0
            goto fail; /* err set by AppendHandshake. */
11127
0
        rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
11128
0
        if (rv != SECSuccess)
11129
0
            goto fail; /* err set by AppendHandshake. */
11130
0
    } else {
11131
0
        if (isServer)
11132
0
            ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
11133
0
        else
11134
0
            ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
11135
0
        PORT_Assert(hashes.len == sizeof hashes.u.s);
11136
0
        ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
11137
0
        rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof hashes.u.s);
11138
0
        if (rv != SECSuccess)
11139
0
            goto fail; /* err set by AppendHandshake. */
11140
0
        rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
11141
0
        if (rv != SECSuccess)
11142
0
            goto fail; /* err set by AppendHandshake. */
11143
0
    }
11144
0
    rv = ssl3_FlushHandshake(ss, flags);
11145
0
    if (rv != SECSuccess) {
11146
0
        goto fail; /* error code set by ssl3_FlushHandshake */
11147
0
    }
11148
0
11149
0
    ssl3_RecordKeyLog(ss, "CLIENT_RANDOM", ss->ssl3.cwSpec->masterSecret);
11150
0
11151
0
    return SECSuccess;
11152
0
11153
0
fail:
11154
0
    return rv;
11155
0
}
11156
11157
/* wrap the master secret, and put it into the SID.
11158
 * Caller holds the Spec read lock.
11159
 */
11160
SECStatus
11161
ssl3_CacheWrappedSecret(sslSocket *ss, sslSessionID *sid,
11162
                        PK11SymKey *secret)
11163
0
{
11164
0
    PK11SymKey *wrappingKey = NULL;
11165
0
    PK11SlotInfo *symKeySlot;
11166
0
    void *pwArg = ss->pkcs11PinArg;
11167
0
    SECStatus rv = SECFailure;
11168
0
    PRBool isServer = ss->sec.isServer;
11169
0
    CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
11170
0
11171
0
    symKeySlot = PK11_GetSlotFromKey(secret);
11172
0
    if (!isServer) {
11173
0
        int wrapKeyIndex;
11174
0
        int incarnation;
11175
0
11176
0
        /* these next few functions are mere accessors and don't fail. */
11177
0
        sid->u.ssl3.masterWrapIndex = wrapKeyIndex =
11178
0
            PK11_GetCurrentWrapIndex(symKeySlot);
11179
0
        PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
11180
0
11181
0
        sid->u.ssl3.masterWrapSeries = incarnation =
11182
0
            PK11_GetSlotSeries(symKeySlot);
11183
0
        sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot);
11184
0
        sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
11185
0
        sid->u.ssl3.masterValid = PR_TRUE;
11186
0
        /* Get the default wrapping key, for wrapping the master secret before
11187
0
         * placing it in the SID cache entry. */
11188
0
        wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
11189
0
                                      CKM_INVALID_MECHANISM, incarnation,
11190
0
                                      pwArg);
11191
0
        if (wrappingKey) {
11192
0
            mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
11193
0
        } else {
11194
0
            int keyLength;
11195
0
            /* if the wrappingKey doesn't exist, attempt to create it.
11196
0
             * Note: we intentionally ignore errors here.  If we cannot
11197
0
             * generate a wrapping key, it is not fatal to this SSL connection,
11198
0
             * but we will not be able to restart this session.
11199
0
             */
11200
0
            mechanism = PK11_GetBestWrapMechanism(symKeySlot);
11201
0
            keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
11202
0
            /* Zero length means fixed key length algorithm, or error.
11203
0
             * It's ambiguous.
11204
0
             */
11205
0
            wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
11206
0
                                      keyLength, pwArg);
11207
0
            if (wrappingKey) {
11208
0
                PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
11209
0
            }
11210
0
        }
11211
0
    } else {
11212
0
        /* server socket using session cache. */
11213
0
        mechanism = PK11_GetBestWrapMechanism(symKeySlot);
11214
0
        if (mechanism != CKM_INVALID_MECHANISM) {
11215
0
            wrappingKey =
11216
0
                ssl3_GetWrappingKey(ss, symKeySlot, mechanism, pwArg);
11217
0
            if (wrappingKey) {
11218
0
                mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
11219
0
            }
11220
0
        }
11221
0
    }
11222
0
11223
0
    sid->u.ssl3.masterWrapMech = mechanism;
11224
0
    PK11_FreeSlot(symKeySlot);
11225
0
11226
0
    if (wrappingKey) {
11227
0
        SECItem wmsItem;
11228
0
11229
0
        wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
11230
0
        wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret;
11231
0
        rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
11232
0
                             secret, &wmsItem);
11233
0
        /* rv is examined below. */
11234
0
        sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
11235
0
        PK11_FreeSymKey(wrappingKey);
11236
0
    }
11237
0
    return rv;
11238
0
}
11239
11240
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11241
 * a complete ssl3 Finished message from the peer.
11242
 * Caller must hold Handshake and RecvBuf locks.
11243
 */
11244
static SECStatus
11245
ssl3_HandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
11246
0
{
11247
0
    sslSessionID *sid = ss->sec.ci.sid;
11248
0
    SECStatus rv = SECSuccess;
11249
0
    PRBool isServer = ss->sec.isServer;
11250
0
    PRBool isTLS;
11251
0
    SSL3Hashes hashes;
11252
0
11253
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11254
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11255
0
11256
0
    SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
11257
0
                SSL_GETPID(), ss->fd));
11258
0
11259
0
    if (ss->ssl3.hs.ws != wait_finished) {
11260
0
        SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11261
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
11262
0
        return SECFailure;
11263
0
    }
11264
0
11265
0
    if (!ss->sec.isServer || !ss->opt.requestCertificate) {
11266
0
        dtls_ReceivedFirstMessageInFlight(ss);
11267
0
    }
11268
0
11269
0
    rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.crSpec, &hashes,
11270
0
                                     isServer ? sender_client : sender_server);
11271
0
    if (rv != SECSuccess) {
11272
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11273
0
        return SECFailure;
11274
0
    }
11275
0
11276
0
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
11277
0
    if (rv != SECSuccess) {
11278
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11279
0
        return rv;
11280
0
    }
11281
0
11282
0
    isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
11283
0
    if (isTLS) {
11284
0
        TLSFinished tlsFinished;
11285
0
11286
0
        if (length != sizeof(tlsFinished)) {
11287
0
#ifndef UNSAFE_FUZZER_MODE
11288
0
            (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
11289
0
            PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
11290
0
            return SECFailure;
11291
0
#endif
11292
0
        }
11293
0
        rv = ssl3_ComputeTLSFinished(ss, ss->ssl3.crSpec, !isServer,
11294
0
                                     &hashes, &tlsFinished);
11295
0
        if (!isServer)
11296
0
            ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
11297
0
        else
11298
0
            ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
11299
0
        ss->ssl3.hs.finishedBytes = sizeof(tlsFinished);
11300
0
        if (rv != SECSuccess ||
11301
0
            0 != NSS_SecureMemcmp(&tlsFinished, b,
11302
0
                                  PR_MIN(length, ss->ssl3.hs.finishedBytes))) {
11303
0
#ifndef UNSAFE_FUZZER_MODE
11304
0
            (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
11305
0
            PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
11306
0
            return SECFailure;
11307
0
#endif
11308
0
        }
11309
0
    } else {
11310
0
        if (length != sizeof(SSL3Finished)) {
11311
0
            (void)ssl3_IllegalParameter(ss);
11312
0
            PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
11313
0
            return SECFailure;
11314
0
        }
11315
0
11316
0
        if (!isServer)
11317
0
            ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
11318
0
        else
11319
0
            ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
11320
0
        PORT_Assert(hashes.len == sizeof hashes.u.s);
11321
0
        ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
11322
0
        if (0 != NSS_SecureMemcmp(&hashes.u.s, b, length)) {
11323
0
            (void)ssl3_HandshakeFailure(ss);
11324
0
            PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
11325
0
            return SECFailure;
11326
0
        }
11327
0
    }
11328
0
11329
0
    ssl_GetXmitBufLock(ss); /*************************************/
11330
0
11331
0
    if ((isServer && !ss->ssl3.hs.isResuming) ||
11332
0
        (!isServer && ss->ssl3.hs.isResuming)) {
11333
0
        PRInt32 flags = 0;
11334
0
11335
0
        /* Send a NewSessionTicket message if the client sent us
11336
0
         * either an empty session ticket, or one that did not verify.
11337
0
         * (Note that if either of these conditions was met, then the
11338
0
         * server has sent a SessionTicket extension in the
11339
0
         * ServerHello message.)
11340
0
         */
11341
0
        if (isServer && !ss->ssl3.hs.isResuming &&
11342
0
            ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
11343
0
            ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
11344
0
            /* RFC 5077 Section 3.3: "In the case of a full handshake, the
11345
0
             * server MUST verify the client's Finished message before sending
11346
0
             * the ticket." Presumably, this also means that the client's
11347
0
             * certificate, if any, must be verified beforehand too.
11348
0
             */
11349
0
            rv = ssl3_SendNewSessionTicket(ss);
11350
0
            if (rv != SECSuccess) {
11351
0
                goto xmit_loser;
11352
0
            }
11353
0
        }
11354
0
11355
0
        rv = ssl3_SendChangeCipherSpecs(ss);
11356
0
        if (rv != SECSuccess) {
11357
0
            goto xmit_loser; /* err is set. */
11358
0
        }
11359
0
        /* If this thread is in SSL_SecureSend (trying to write some data)
11360
0
        ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
11361
0
        ** last two handshake messages (change cipher spec and finished)
11362
0
        ** will be sent in the same send/write call as the application data.
11363
0
        */
11364
0
        if (ss->writerThread == PR_GetCurrentThread()) {
11365
0
            flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
11366
0
        }
11367
0
11368
0
        if (!isServer && !ss->firstHsDone) {
11369
0
            rv = ssl3_SendNextProto(ss);
11370
0
            if (rv != SECSuccess) {
11371
0
                goto xmit_loser; /* err code was set. */
11372
0
            }
11373
0
        }
11374
0
11375
0
        if (IS_DTLS(ss)) {
11376
0
            flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
11377
0
        }
11378
0
11379
0
        rv = ssl3_SendFinished(ss, flags);
11380
0
        if (rv != SECSuccess) {
11381
0
            goto xmit_loser; /* err is set. */
11382
0
        }
11383
0
    }
11384
0
11385
0
xmit_loser:
11386
0
    ssl_ReleaseXmitBufLock(ss); /*************************************/
11387
0
    if (rv != SECSuccess) {
11388
0
        return rv;
11389
0
    }
11390
0
11391
0
    if (sid->cached == never_cached && !ss->opt.noCache) {
11392
0
        rv = ssl3_FillInCachedSID(ss, sid, ss->ssl3.crSpec->masterSecret);
11393
0
11394
0
        /* If the wrap failed, we don't cache the sid.
11395
0
         * The connection continues normally however.
11396
0
         */
11397
0
        ss->ssl3.hs.cacheSID = rv == SECSuccess;
11398
0
    }
11399
0
11400
0
    if (ss->ssl3.hs.authCertificatePending) {
11401
0
        if (ss->ssl3.hs.restartTarget) {
11402
0
            PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
11403
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11404
0
            return SECFailure;
11405
0
        }
11406
0
11407
0
        ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
11408
0
        return SECWouldBlock;
11409
0
    }
11410
0
11411
0
    rv = ssl3_FinishHandshake(ss);
11412
0
    return rv;
11413
0
}
11414
11415
SECStatus
11416
ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid, PK11SymKey *secret)
11417
0
{
11418
0
    PORT_Assert(secret);
11419
0
11420
0
    /* fill in the sid */
11421
0
    sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
11422
0
    sid->u.ssl3.policy = ss->ssl3.policy;
11423
0
    sid->version = ss->version;
11424
0
    sid->authType = ss->sec.authType;
11425
0
    sid->authKeyBits = ss->sec.authKeyBits;
11426
0
    sid->keaType = ss->sec.keaType;
11427
0
    sid->keaKeyBits = ss->sec.keaKeyBits;
11428
0
    if (ss->sec.keaGroup) {
11429
0
        sid->keaGroup = ss->sec.keaGroup->name;
11430
0
    } else {
11431
0
        sid->keaGroup = ssl_grp_none;
11432
0
    }
11433
0
    sid->sigScheme = ss->sec.signatureScheme;
11434
0
    sid->lastAccessTime = sid->creationTime = ssl_TimeUsec();
11435
0
    sid->expirationTime = sid->creationTime + ssl3_sid_timeout * PR_USEC_PER_SEC;
11436
0
    sid->localCert = CERT_DupCertificate(ss->sec.localCert);
11437
0
    if (ss->sec.isServer) {
11438
0
        sid->namedCurve = ss->sec.serverCert->namedCurve;
11439
0
    }
11440
0
11441
0
    if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
11442
0
        ss->xtnData.nextProto.data) {
11443
0
        SECITEM_FreeItem(&sid->u.ssl3.alpnSelection, PR_FALSE);
11444
0
        if (SECITEM_CopyItem(
11445
0
                NULL, &sid->u.ssl3.alpnSelection, &ss->xtnData.nextProto) != SECSuccess) {
11446
0
            return SECFailure; /* error already set. */
11447
0
        }
11448
0
    }
11449
0
11450
0
    /* Copy the master secret (wrapped or unwrapped) into the sid */
11451
0
    return ssl3_CacheWrappedSecret(ss, ss->sec.ci.sid, secret);
11452
0
}
11453
11454
/* The return type is SECStatus instead of void because this function needs
11455
 * to have type sslRestartTarget.
11456
 */
11457
SECStatus
11458
ssl3_FinishHandshake(sslSocket *ss)
11459
0
{
11460
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11461
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11462
0
    PORT_Assert(ss->ssl3.hs.restartTarget == NULL);
11463
0
11464
0
    /* The first handshake is now completed. */
11465
0
    ss->handshake = NULL;
11466
0
11467
0
    /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid
11468
0
     * until it has verified the server's Finished message." When the server
11469
0
     * sends a NewSessionTicket in a resumption handshake, we must wait until
11470
0
     * the handshake is finished (we have verified the server's Finished
11471
0
     * AND the server's certificate) before we update the ticket in the sid.
11472
0
     *
11473
0
     * This must be done before we call ssl_CacheSessionID(ss)
11474
0
     * because CacheSID requires the session ticket to already be set, and also
11475
0
     * because of the lazy lock creation scheme used by CacheSID and
11476
0
     * ssl3_SetSIDSessionTicket.
11477
0
     */
11478
0
    if (ss->ssl3.hs.receivedNewSessionTicket) {
11479
0
        PORT_Assert(!ss->sec.isServer);
11480
0
        ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ss->ssl3.hs.newSessionTicket);
11481
0
        /* The sid took over the ticket data */
11482
0
        PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
11483
0
        ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
11484
0
    }
11485
0
11486
0
    if (ss->ssl3.hs.cacheSID) {
11487
0
        PORT_Assert(ss->sec.ci.sid->cached == never_cached);
11488
0
        ssl_CacheSessionID(ss);
11489
0
        ss->ssl3.hs.cacheSID = PR_FALSE;
11490
0
    }
11491
0
11492
0
    ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */
11493
0
    ss->ssl3.hs.ws = idle_handshake;
11494
0
11495
0
    ssl_FinishHandshake(ss);
11496
0
11497
0
    return SECSuccess;
11498
0
}
11499
11500
SECStatus
11501
ssl_HashHandshakeMessageInt(sslSocket *ss, SSLHandshakeType ct,
11502
                            PRUint32 dtlsSeq,
11503
                            const PRUint8 *b, PRUint32 length)
11504
0
{
11505
0
    PRUint8 hdr[4];
11506
0
    PRUint8 dtlsData[8];
11507
0
    SECStatus rv;
11508
0
11509
0
    PRINT_BUF(50, (ss, "Hash handshake message:", b, length));
11510
0
11511
0
    hdr[0] = (PRUint8)ct;
11512
0
    hdr[1] = (PRUint8)(length >> 16);
11513
0
    hdr[2] = (PRUint8)(length >> 8);
11514
0
    hdr[3] = (PRUint8)(length);
11515
0
11516
0
    rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char *)hdr, 4);
11517
0
    if (rv != SECSuccess)
11518
0
        return rv; /* err code already set. */
11519
0
11520
0
    /* Extra data to simulate a complete DTLS handshake fragment */
11521
0
    if (IS_DTLS(ss)) {
11522
0
        /* Sequence number */
11523
0
        dtlsData[0] = MSB(dtlsSeq);
11524
0
        dtlsData[1] = LSB(dtlsSeq);
11525
0
11526
0
        /* Fragment offset */
11527
0
        dtlsData[2] = 0;
11528
0
        dtlsData[3] = 0;
11529
0
        dtlsData[4] = 0;
11530
0
11531
0
        /* Fragment length */
11532
0
        dtlsData[5] = (PRUint8)(length >> 16);
11533
0
        dtlsData[6] = (PRUint8)(length >> 8);
11534
0
        dtlsData[7] = (PRUint8)(length);
11535
0
11536
0
        rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char *)dtlsData,
11537
0
                                        sizeof(dtlsData));
11538
0
        if (rv != SECSuccess)
11539
0
            return rv; /* err code already set. */
11540
0
    }
11541
0
11542
0
    /* The message body */
11543
0
    rv = ssl3_UpdateHandshakeHashes(ss, b, length);
11544
0
    if (rv != SECSuccess)
11545
0
        return rv; /* err code already set. */
11546
0
11547
0
    return SECSuccess;
11548
0
}
11549
11550
SECStatus
11551
ssl_HashHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
11552
                         const PRUint8 *b, PRUint32 length)
11553
0
{
11554
0
    return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
11555
0
                                       b, length);
11556
0
}
11557
11558
/* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
11559
 * handshake message.
11560
 * Caller must hold Handshake and RecvBuf locks.
11561
 */
11562
SECStatus
11563
ssl3_HandleHandshakeMessage(sslSocket *ss, PRUint8 *b, PRUint32 length,
11564
                            PRBool endOfRecord)
11565
0
{
11566
0
    SECStatus rv = SECSuccess;
11567
0
    PRUint16 epoch;
11568
0
11569
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11570
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11571
0
11572
0
    SSL_TRC(30, ("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
11573
0
                 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
11574
0
11575
0
    /* Start new handshake hashes when we start a new handshake. */
11576
0
    if (ss->ssl3.hs.msg_type == ssl_hs_client_hello) {
11577
0
        ssl3_RestartHandshakeHashes(ss);
11578
0
    }
11579
0
    switch (ss->ssl3.hs.msg_type) {
11580
0
        case ssl_hs_hello_request:
11581
0
        case ssl_hs_hello_verify_request:
11582
0
            /* We don't include hello_request and hello_verify_request messages
11583
0
             * in the handshake hashes */
11584
0
            break;
11585
0
11586
0
        /* Defer hashing of these messages until the message handlers. */
11587
0
        case ssl_hs_client_hello:
11588
0
        case ssl_hs_server_hello:
11589
0
        case ssl_hs_certificate_verify:
11590
0
        case ssl_hs_finished:
11591
0
            break;
11592
0
11593
0
        default:
11594
0
            rv = ssl_HashHandshakeMessage(ss, ss->ssl3.hs.msg_type, b, length);
11595
0
            if (rv != SECSuccess) {
11596
0
                return SECFailure;
11597
0
            }
11598
0
    }
11599
0
11600
0
    PORT_SetError(0); /* each message starts with no error. */
11601
0
11602
0
    if (ss->ssl3.hs.ws == wait_certificate_status &&
11603
0
        ss->ssl3.hs.msg_type != ssl_hs_certificate_status) {
11604
0
        /* If we negotiated the certificate_status extension then we deferred
11605
0
         * certificate validation until we get the CertificateStatus messsage.
11606
0
         * But the CertificateStatus message is optional. If the server did
11607
0
         * not send it then we need to validate the certificate now. If the
11608
0
         * server does send the CertificateStatus message then we will
11609
0
         * authenticate the certificate in ssl3_HandleCertificateStatus.
11610
0
         */
11611
0
        rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
11612
0
        PORT_Assert(rv != SECWouldBlock);
11613
0
        if (rv != SECSuccess) {
11614
0
            return rv;
11615
0
        }
11616
0
    }
11617
0
11618
0
    epoch = ss->ssl3.crSpec->epoch;
11619
0
    switch (ss->ssl3.hs.msg_type) {
11620
0
        case ssl_hs_client_hello:
11621
0
            if (!ss->sec.isServer) {
11622
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11623
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
11624
0
                return SECFailure;
11625
0
            }
11626
0
            rv = ssl3_HandleClientHello(ss, b, length);
11627
0
            break;
11628
0
        case ssl_hs_server_hello:
11629
0
            if (ss->sec.isServer) {
11630
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11631
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
11632
0
                return SECFailure;
11633
0
            }
11634
0
            rv = ssl3_HandleServerHello(ss, b, length);
11635
0
            break;
11636
0
        default:
11637
0
            if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11638
0
                rv = ssl3_HandlePostHelloHandshakeMessage(ss, b, length);
11639
0
            } else {
11640
0
                rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length);
11641
0
            }
11642
0
            break;
11643
0
    }
11644
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
11645
0
        (epoch != ss->ssl3.crSpec->epoch) && !endOfRecord) {
11646
0
        /* If we changed read cipher states, there must not be any
11647
0
         * data in the input queue. */
11648
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11649
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
11650
0
        return SECFailure;
11651
0
    }
11652
0
11653
0
    if (IS_DTLS(ss) && (rv != SECFailure)) {
11654
0
        /* Increment the expected sequence number */
11655
0
        ss->ssl3.hs.recvMessageSeq++;
11656
0
    }
11657
0
11658
0
    /* Taint the message so that it's easier to detect UAFs. */
11659
0
    PORT_Memset(b, 'N', length);
11660
0
11661
0
    return rv;
11662
0
}
11663
11664
static SECStatus
11665
ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b,
11666
                                     PRUint32 length)
11667
0
{
11668
0
    SECStatus rv;
11669
0
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
11670
0
11671
0
    switch (ss->ssl3.hs.msg_type) {
11672
0
        case ssl_hs_hello_request:
11673
0
            if (length != 0) {
11674
0
                (void)ssl3_DecodeError(ss);
11675
0
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
11676
0
                return SECFailure;
11677
0
            }
11678
0
            if (ss->sec.isServer) {
11679
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11680
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
11681
0
                return SECFailure;
11682
0
            }
11683
0
            rv = ssl3_HandleHelloRequest(ss);
11684
0
            break;
11685
0
11686
0
        case ssl_hs_hello_verify_request:
11687
0
            if (!IS_DTLS(ss) || ss->sec.isServer) {
11688
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11689
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
11690
0
                return SECFailure;
11691
0
            }
11692
0
            rv = dtls_HandleHelloVerifyRequest(ss, b, length);
11693
0
            break;
11694
0
        case ssl_hs_certificate:
11695
0
            rv = ssl3_HandleCertificate(ss, b, length);
11696
0
            break;
11697
0
        case ssl_hs_certificate_status:
11698
0
            rv = ssl3_HandleCertificateStatus(ss, b, length);
11699
0
            break;
11700
0
        case ssl_hs_server_key_exchange:
11701
0
            if (ss->sec.isServer) {
11702
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11703
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
11704
0
                return SECFailure;
11705
0
            }
11706
0
            rv = ssl3_HandleServerKeyExchange(ss, b, length);
11707
0
            break;
11708
0
        case ssl_hs_certificate_request:
11709
0
            if (ss->sec.isServer) {
11710
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11711
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
11712
0
                return SECFailure;
11713
0
            }
11714
0
            rv = ssl3_HandleCertificateRequest(ss, b, length);
11715
0
            break;
11716
0
        case ssl_hs_server_hello_done:
11717
0
            if (length != 0) {
11718
0
                (void)ssl3_DecodeError(ss);
11719
0
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
11720
0
                return SECFailure;
11721
0
            }
11722
0
            if (ss->sec.isServer) {
11723
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11724
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
11725
0
                return SECFailure;
11726
0
            }
11727
0
            rv = ssl3_HandleServerHelloDone(ss);
11728
0
            break;
11729
0
        case ssl_hs_certificate_verify:
11730
0
            if (!ss->sec.isServer) {
11731
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11732
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
11733
0
                return SECFailure;
11734
0
            }
11735
0
            rv = ssl3_HandleCertificateVerify(ss, b, length);
11736
0
            break;
11737
0
        case ssl_hs_client_key_exchange:
11738
0
            if (!ss->sec.isServer) {
11739
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11740
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
11741
0
                return SECFailure;
11742
0
            }
11743
0
            rv = ssl3_HandleClientKeyExchange(ss, b, length);
11744
0
            break;
11745
0
        case ssl_hs_new_session_ticket:
11746
0
            if (ss->sec.isServer) {
11747
0
                (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11748
0
                PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
11749
0
                return SECFailure;
11750
0
            }
11751
0
            rv = ssl3_HandleNewSessionTicket(ss, b, length);
11752
0
            break;
11753
0
        case ssl_hs_finished:
11754
0
            rv = ssl3_HandleFinished(ss, b, length);
11755
0
            break;
11756
0
        default:
11757
0
            (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11758
0
            PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
11759
0
            rv = SECFailure;
11760
0
    }
11761
0
11762
0
    return rv;
11763
0
}
11764
11765
/* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
11766
 * origBuf is the decrypted ssl record content.
11767
 * Caller must hold the handshake and RecvBuf locks.
11768
 */
11769
static SECStatus
11770
ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
11771
0
{
11772
0
    /*
11773
0
     * There may be a partial handshake message already in the handshake
11774
0
     * state. The incoming buffer may contain another portion, or a
11775
0
     * complete message or several messages followed by another portion.
11776
0
     *
11777
0
     * Each message is made contiguous before being passed to the actual
11778
0
     * message parser.
11779
0
     */
11780
0
    sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer pointer */
11781
0
    SECStatus rv;
11782
0
11783
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11784
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11785
0
11786
0
    if (buf->buf == NULL) {
11787
0
        *buf = *origBuf;
11788
0
    }
11789
0
    while (buf->len > 0) {
11790
0
        if (ss->ssl3.hs.header_bytes < 4) {
11791
0
            PRUint8 t;
11792
0
            t = *(buf->buf++);
11793
0
            buf->len--;
11794
0
            if (ss->ssl3.hs.header_bytes++ == 0)
11795
0
                ss->ssl3.hs.msg_type = (SSLHandshakeType)t;
11796
0
            else
11797
0
                ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
11798
0
            if (ss->ssl3.hs.header_bytes < 4)
11799
0
                continue;
11800
0
11801
0
#define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
11802
0
            if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
11803
0
                (void)ssl3_DecodeError(ss);
11804
0
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
11805
0
                return SECFailure;
11806
0
            }
11807
0
#undef MAX_HANDSHAKE_MSG_LEN
11808
0
11809
0
            /* If msg_len is zero, be sure we fall through,
11810
0
            ** even if buf->len is zero.
11811
0
            */
11812
0
            if (ss->ssl3.hs.msg_len > 0)
11813
0
                continue;
11814
0
        }
11815
0
11816
0
        /*
11817
0
         * Header has been gathered and there is at least one byte of new
11818
0
         * data available for this message. If it can be done right out
11819
0
         * of the original buffer, then use it from there.
11820
0
         */
11821
0
        if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) {
11822
0
            /* handle it from input buffer */
11823
0
            rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len,
11824
0
                                             buf->len == ss->ssl3.hs.msg_len);
11825
0
            if (rv == SECFailure) {
11826
0
                /* This test wants to fall through on either
11827
0
                 * SECSuccess or SECWouldBlock.
11828
0
                 * ssl3_HandleHandshakeMessage MUST set the error code.
11829
0
                 */
11830
0
                return rv;
11831
0
            }
11832
0
            buf->buf += ss->ssl3.hs.msg_len;
11833
0
            buf->len -= ss->ssl3.hs.msg_len;
11834
0
            ss->ssl3.hs.msg_len = 0;
11835
0
            ss->ssl3.hs.header_bytes = 0;
11836
0
            if (rv != SECSuccess) { /* return if SECWouldBlock. */
11837
0
                return rv;
11838
0
            }
11839
0
        } else {
11840
0
            /* must be copied to msg_body and dealt with from there */
11841
0
            unsigned int bytes;
11842
0
11843
0
            PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
11844
0
            bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
11845
0
11846
0
            /* Grow the buffer if needed */
11847
0
            rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
11848
0
            if (rv != SECSuccess) {
11849
0
                /* sslBuffer_Grow has set a memory error code. */
11850
0
                return SECFailure;
11851
0
            }
11852
0
11853
0
            PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
11854
0
                        buf->buf, bytes);
11855
0
            ss->ssl3.hs.msg_body.len += bytes;
11856
0
            buf->buf += bytes;
11857
0
            buf->len -= bytes;
11858
0
11859
0
            PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
11860
0
11861
0
            /* if we have a whole message, do it */
11862
0
            if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
11863
0
                rv = ssl3_HandleHandshakeMessage(
11864
0
                    ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len,
11865
0
                    buf->len == 0);
11866
0
                if (rv == SECFailure) {
11867
0
                    /* This test wants to fall through on either
11868
0
                     * SECSuccess or SECWouldBlock.
11869
0
                     * ssl3_HandleHandshakeMessage MUST set error code.
11870
0
                     */
11871
0
                    return rv;
11872
0
                }
11873
0
                ss->ssl3.hs.msg_body.len = 0;
11874
0
                ss->ssl3.hs.msg_len = 0;
11875
0
                ss->ssl3.hs.header_bytes = 0;
11876
0
                if (rv != SECSuccess) { /* return if SECWouldBlock. */
11877
0
                    return rv;
11878
0
                }
11879
0
            } else {
11880
0
                PORT_Assert(buf->len == 0);
11881
0
                break;
11882
0
            }
11883
0
        }
11884
0
    } /* end loop */
11885
0
11886
0
    origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
11887
0
    buf->buf = NULL;  /* not a leak. */
11888
0
    return SECSuccess;
11889
0
}
11890
11891
/* These macros return the given value with the MSB copied to all the other
11892
 * bits. They use the fact that arithmetic shift shifts-in the sign bit.
11893
 * However, this is not ensured by the C standard so you may need to replace
11894
 * them with something else for odd compilers. */
11895
0
#define DUPLICATE_MSB_TO_ALL(x) ((unsigned)((int)(x) >> (sizeof(int) * 8 - 1)))
11896
0
#define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x)))
11897
11898
/* SECStatusToMask returns, in constant time, a mask value of all ones if
11899
 * rv == SECSuccess.  Otherwise it returns zero. */
11900
static unsigned int
11901
SECStatusToMask(SECStatus rv)
11902
0
{
11903
0
    unsigned int good;
11904
0
    /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results
11905
0
     * in the MSB being set to one iff it was zero before. */
11906
0
    good = rv ^ SECSuccess;
11907
0
    good--;
11908
0
    return DUPLICATE_MSB_TO_ALL(good);
11909
0
}
11910
11911
/* ssl_ConstantTimeGE returns 0xff if a>=b and 0x00 otherwise. */
11912
static unsigned char
11913
ssl_ConstantTimeGE(unsigned int a, unsigned int b)
11914
0
{
11915
0
    a -= b;
11916
0
    return DUPLICATE_MSB_TO_ALL(~a);
11917
0
}
11918
11919
/* ssl_ConstantTimeEQ8 returns 0xff if a==b and 0x00 otherwise. */
11920
static unsigned char
11921
ssl_ConstantTimeEQ8(unsigned char a, unsigned char b)
11922
0
{
11923
0
    unsigned int c = a ^ b;
11924
0
    c--;
11925
0
    return DUPLICATE_MSB_TO_ALL_8(c);
11926
0
}
11927
11928
/* ssl_constantTimeSelect return a if mask is 0xFF and b if mask is 0x00 */
11929
static unsigned char
11930
ssl_constantTimeSelect(unsigned char mask, unsigned char a, unsigned char b)
11931
0
{
11932
0
    return (mask & a) | (~mask & b);
11933
0
}
11934
11935
static SECStatus
11936
ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
11937
                          unsigned int blockSize,
11938
                          unsigned int macSize)
11939
0
{
11940
0
    unsigned int paddingLength, good, t;
11941
0
    const unsigned int overhead = 1 /* padding length byte */ + macSize;
11942
0
11943
0
    /* These lengths are all public so we can test them in non-constant
11944
0
     * time. */
11945
0
    if (overhead > plaintext->len) {
11946
0
        return SECFailure;
11947
0
    }
11948
0
11949
0
    paddingLength = plaintext->buf[plaintext->len - 1];
11950
0
    /* SSLv3 padding bytes are random and cannot be checked. */
11951
0
    t = plaintext->len;
11952
0
    t -= paddingLength + overhead;
11953
0
    /* If len >= paddingLength+overhead then the MSB of t is zero. */
11954
0
    good = DUPLICATE_MSB_TO_ALL(~t);
11955
0
    /* SSLv3 requires that the padding is minimal. */
11956
0
    t = blockSize - (paddingLength + 1);
11957
0
    good &= DUPLICATE_MSB_TO_ALL(~t);
11958
0
    plaintext->len -= good & (paddingLength + 1);
11959
0
    return (good & SECSuccess) | (~good & SECFailure);
11960
0
}
11961
11962
SECStatus
11963
ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
11964
0
{
11965
0
    unsigned int paddingLength, good, t, toCheck, i;
11966
0
    const unsigned int overhead = 1 /* padding length byte */ + macSize;
11967
0
11968
0
    /* These lengths are all public so we can test them in non-constant
11969
0
     * time. */
11970
0
    if (overhead > plaintext->len) {
11971
0
        return SECFailure;
11972
0
    }
11973
0
11974
0
    paddingLength = plaintext->buf[plaintext->len - 1];
11975
0
    t = plaintext->len;
11976
0
    t -= paddingLength + overhead;
11977
0
    /* If len >= paddingLength+overhead then the MSB of t is zero. */
11978
0
    good = DUPLICATE_MSB_TO_ALL(~t);
11979
0
11980
0
    /* The padding consists of a length byte at the end of the record and then
11981
0
     * that many bytes of padding, all with the same value as the length byte.
11982
0
     * Thus, with the length byte included, there are paddingLength+1 bytes of
11983
0
     * padding.
11984
0
     *
11985
0
     * We can't check just |paddingLength+1| bytes because that leaks
11986
0
     * decrypted information. Therefore we always have to check the maximum
11987
0
     * amount of padding possible. (Again, the length of the record is
11988
0
     * public information so we can use it.) */
11989
0
    toCheck = 256; /* maximum amount of padding + 1. */
11990
0
    if (toCheck > plaintext->len) {
11991
0
        toCheck = plaintext->len;
11992
0
    }
11993
0
11994
0
    for (i = 0; i < toCheck; i++) {
11995
0
        t = paddingLength - i;
11996
0
        /* If i <= paddingLength then the MSB of t is zero and mask is
11997
0
         * 0xff.  Otherwise, mask is 0. */
11998
0
        unsigned char mask = DUPLICATE_MSB_TO_ALL(~t);
11999
0
        unsigned char b = plaintext->buf[plaintext->len - 1 - i];
12000
0
        /* The final |paddingLength+1| bytes should all have the value
12001
0
         * |paddingLength|. Therefore the XOR should be zero. */
12002
0
        good &= ~(mask & (paddingLength ^ b));
12003
0
    }
12004
0
12005
0
    /* If any of the final |paddingLength+1| bytes had the wrong value,
12006
0
     * one or more of the lower eight bits of |good| will be cleared. We
12007
0
     * AND the bottom 8 bits together and duplicate the result to all the
12008
0
     * bits. */
12009
0
    good &= good >> 4;
12010
0
    good &= good >> 2;
12011
0
    good &= good >> 1;
12012
0
    good <<= sizeof(good) * 8 - 1;
12013
0
    good = DUPLICATE_MSB_TO_ALL(good);
12014
0
12015
0
    plaintext->len -= good & (paddingLength + 1);
12016
0
    return (good & SECSuccess) | (~good & SECFailure);
12017
0
}
12018
12019
/* On entry:
12020
 *   originalLength >= macSize
12021
 *   macSize <= MAX_MAC_LENGTH
12022
 *   plaintext->len >= macSize
12023
 */
12024
static void
12025
ssl_CBCExtractMAC(sslBuffer *plaintext,
12026
                  unsigned int originalLength,
12027
                  PRUint8 *out,
12028
                  unsigned int macSize)
12029
0
{
12030
0
    unsigned char rotatedMac[MAX_MAC_LENGTH];
12031
0
    /* macEnd is the index of |plaintext->buf| just after the end of the
12032
0
     * MAC. */
12033
0
    unsigned macEnd = plaintext->len;
12034
0
    unsigned macStart = macEnd - macSize;
12035
0
    /* scanStart contains the number of bytes that we can ignore because
12036
0
     * the MAC's position can only vary by 255 bytes. */
12037
0
    unsigned scanStart = 0;
12038
0
    unsigned i, j;
12039
0
    unsigned char rotateOffset;
12040
0
12041
0
    if (originalLength > macSize + 255 + 1) {
12042
0
        scanStart = originalLength - (macSize + 255 + 1);
12043
0
    }
12044
0
12045
0
    /* We want to compute
12046
0
     * rotateOffset = (macStart - scanStart) % macSize
12047
0
     * But the time to compute this varies based on the amount of padding. Thus
12048
0
     * we explicitely handle all mac sizes with (hopefully) constant time modulo
12049
0
     * using Barrett reduction:
12050
0
     *  q := (rotateOffset * m) >> k
12051
0
     *  rotateOffset -= q * n
12052
0
     *  if (n <= rotateOffset) rotateOffset -= n
12053
0
     */
12054
0
    rotateOffset = macStart - scanStart;
12055
0
    /* rotateOffset < 255 + 1 + 48 = 304 */
12056
0
    if (macSize == 16) {
12057
0
        rotateOffset &= 15;
12058
0
    } else if (macSize == 20) {
12059
0
        /*
12060
0
         * Correctness: rotateOffset * ( 1/20 - 25/2^9 ) < 1
12061
0
         *              with rotateOffset <= 853
12062
0
         */
12063
0
        unsigned q = (rotateOffset * 25) >> 9;
12064
0
        rotateOffset -= q * 20;
12065
0
        rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 20),
12066
0
                                               20, 0);
12067
0
    } else if (macSize == 32) {
12068
0
        rotateOffset &= 31;
12069
0
    } else if (macSize == 48) {
12070
0
        /*
12071
0
         * Correctness: rotateOffset * ( 1/48 - 10/2^9 ) < 1
12072
0
         *              with rotateOffset < 768
12073
0
         */
12074
0
        unsigned q = (rotateOffset * 10) >> 9;
12075
0
        rotateOffset -= q * 48;
12076
0
        rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 48),
12077
0
                                               48, 0);
12078
0
    } else {
12079
0
        /*
12080
0
         * SHA384 (macSize == 48) is the largest we support. We should never
12081
0
         * get here.
12082
0
         */
12083
0
        PORT_Assert(0);
12084
0
        rotateOffset = rotateOffset % macSize;
12085
0
    }
12086
0
12087
0
    memset(rotatedMac, 0, macSize);
12088
0
    for (i = scanStart; i < originalLength;) {
12089
0
        for (j = 0; j < macSize && i < originalLength; i++, j++) {
12090
0
            unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
12091
0
            unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
12092
0
            unsigned char b = 0;
12093
0
            b = plaintext->buf[i];
12094
0
            rotatedMac[j] |= b & macStarted & ~macEnded;
12095
0
        }
12096
0
    }
12097
0
12098
0
    /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
12099
0
     * we could line-align |rotatedMac| and rotate in place. */
12100
0
    memset(out, 0, macSize);
12101
0
    rotateOffset = macSize - rotateOffset;
12102
0
    rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
12103
0
                                          0, rotateOffset);
12104
0
    for (i = 0; i < macSize; i++) {
12105
0
        for (j = 0; j < macSize; j++) {
12106
0
            out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, rotateOffset);
12107
0
        }
12108
0
        rotateOffset++;
12109
0
        rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
12110
0
                                              0, rotateOffset);
12111
0
    }
12112
0
}
12113
12114
/* Unprotect an SSL3 record and leave the result in plaintext.
12115
 *
12116
 * If SECFailure is returned, we:
12117
 * 1. Set |*alert| to the alert to be sent.
12118
 * 2. Call PORT_SetError() with an appropriate code.
12119
 *
12120
 * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
12121
 * Therefore, we MUST not call SSL3_SendAlert().
12122
 *
12123
 */
12124
static SECStatus
12125
ssl3_UnprotectRecord(sslSocket *ss,
12126
                     ssl3CipherSpec *spec,
12127
                     SSL3Ciphertext *cText, sslBuffer *plaintext,
12128
                     SSL3AlertDescription *alert)
12129
0
{
12130
0
    const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
12131
0
    PRBool isTLS;
12132
0
    unsigned int good;
12133
0
    unsigned int ivLen = 0;
12134
0
    SSLContentType rType;
12135
0
    SSL3ProtocolVersion rVersion;
12136
0
    unsigned int minLength;
12137
0
    unsigned int originalLen = 0;
12138
0
    PRUint8 headerBuf[13];
12139
0
    sslBuffer header = SSL_BUFFER(headerBuf);
12140
0
    PRUint8 hash[MAX_MAC_LENGTH];
12141
0
    PRUint8 givenHashBuf[MAX_MAC_LENGTH];
12142
0
    PRUint8 *givenHash;
12143
0
    unsigned int hashBytes = MAX_MAC_LENGTH + 1;
12144
0
    SECStatus rv;
12145
0
12146
0
    PORT_Assert(spec->direction == CipherSpecRead);
12147
0
12148
0
    good = ~0U;
12149
0
    minLength = spec->macDef->mac_size;
12150
0
    if (cipher_def->type == type_block) {
12151
0
        /* CBC records have a padding length byte at the end. */
12152
0
        minLength++;
12153
0
        if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
12154
0
            /* With >= TLS 1.1, CBC records have an explicit IV. */
12155
0
            minLength += cipher_def->iv_size;
12156
0
        }
12157
0
    } else if (cipher_def->type == type_aead) {
12158
0
        minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
12159
0
    }
12160
0
12161
0
    /* We can perform this test in variable time because the record's total
12162
0
     * length and the ciphersuite are both public knowledge. */
12163
0
    if (cText->buf->len < minLength) {
12164
0
        goto decrypt_loser;
12165
0
    }
12166
0
12167
0
    if (cipher_def->type == type_block &&
12168
0
        spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
12169
0
        /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
12170
0
         * "The receiver decrypts the entire GenericBlockCipher structure and
12171
0
         * then discards the first cipher block corresponding to the IV
12172
0
         * component." Instead, we decrypt the first cipher block and then
12173
0
         * discard it before decrypting the rest.
12174
0
         */
12175
0
        PRUint8 iv[MAX_IV_LENGTH];
12176
0
        int decoded;
12177
0
12178
0
        ivLen = cipher_def->iv_size;
12179
0
        if (ivLen < 8 || ivLen > sizeof(iv)) {
12180
0
            *alert = internal_error;
12181
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12182
0
            return SECFailure;
12183
0
        }
12184
0
12185
0
        PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
12186
0
12187
0
        /* The decryption result is garbage, but since we just throw away
12188
0
         * the block it doesn't matter.  The decryption of the next block
12189
0
         * depends only on the ciphertext of the IV block.
12190
0
         */
12191
0
        rv = spec->cipher(spec->cipherContext, iv, &decoded,
12192
0
                          sizeof(iv), cText->buf->buf, ivLen);
12193
0
12194
0
        good &= SECStatusToMask(rv);
12195
0
    }
12196
0
12197
0
    PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
12198
0
                   cText->buf->len - ivLen));
12199
0
12200
0
    isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
12201
0
12202
0
    if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) {
12203
0
        *alert = record_overflow;
12204
0
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
12205
0
        return SECFailure;
12206
0
    }
12207
0
12208
0
    rType = (SSLContentType)cText->hdr[0];
12209
0
    rVersion = ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
12210
0
               (SSL3ProtocolVersion)cText->hdr[2];
12211
0
    if (cipher_def->type == type_aead) {
12212
0
        /* XXX For many AEAD ciphers, the plaintext is shorter than the
12213
0
         * ciphertext by a fixed byte count, but it is not true in general.
12214
0
         * Each AEAD cipher should provide a function that returns the
12215
0
         * plaintext length for a given ciphertext. */
12216
0
        unsigned int decryptedLen =
12217
0
            cText->buf->len - cipher_def->explicit_nonce_size -
12218
0
            cipher_def->tag_size;
12219
0
        rv = ssl3_BuildRecordPseudoHeader(
12220
0
            spec->epoch, cText->seqNum,
12221
0
            rType, isTLS, rVersion, IS_DTLS(ss), decryptedLen, &header);
12222
0
        PORT_Assert(rv == SECSuccess);
12223
0
        rv = spec->aead(&spec->keyMaterial,
12224
0
                        PR_TRUE,                /* do decrypt */
12225
0
                        plaintext->buf,         /* out */
12226
0
                        (int *)&plaintext->len, /* outlen */
12227
0
                        plaintext->space,       /* maxout */
12228
0
                        cText->buf->buf,        /* in */
12229
0
                        cText->buf->len,        /* inlen */
12230
0
                        SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header));
12231
0
        if (rv != SECSuccess) {
12232
0
            good = 0;
12233
0
        }
12234
0
    } else {
12235
0
        if (cipher_def->type == type_block &&
12236
0
            ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
12237
0
            goto decrypt_loser;
12238
0
        }
12239
0
12240
0
        /* decrypt from cText buf to plaintext. */
12241
0
        rv = spec->cipher(
12242
0
            spec->cipherContext, plaintext->buf, (int *)&plaintext->len,
12243
0
            plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
12244
0
        if (rv != SECSuccess) {
12245
0
            goto decrypt_loser;
12246
0
        }
12247
0
12248
0
        PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
12249
0
12250
0
        originalLen = plaintext->len;
12251
0
12252
0
        /* If it's a block cipher, check and strip the padding. */
12253
0
        if (cipher_def->type == type_block) {
12254
0
            const unsigned int blockSize = cipher_def->block_size;
12255
0
            const unsigned int macSize = spec->macDef->mac_size;
12256
0
12257
0
            if (!isTLS) {
12258
0
                good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
12259
0
                    plaintext, blockSize, macSize));
12260
0
            } else {
12261
0
                good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
12262
0
                    plaintext, macSize));
12263
0
            }
12264
0
        }
12265
0
12266
0
        /* compute the MAC */
12267
0
        rv = ssl3_BuildRecordPseudoHeader(
12268
0
            spec->epoch, cText->seqNum,
12269
0
            rType, isTLS, rVersion, IS_DTLS(ss),
12270
0
            plaintext->len - spec->macDef->mac_size, &header);
12271
0
        PORT_Assert(rv == SECSuccess);
12272
0
        if (cipher_def->type == type_block) {
12273
0
            rv = ssl3_ComputeRecordMACConstantTime(
12274
0
                spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
12275
0
                plaintext->buf, plaintext->len, originalLen,
12276
0
                hash, &hashBytes);
12277
0
12278
0
            ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
12279
0
                              spec->macDef->mac_size);
12280
0
            givenHash = givenHashBuf;
12281
0
12282
0
            /* plaintext->len will always have enough space to remove the MAC
12283
0
             * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
12284
0
             * plaintext->len if the result has enough space for the MAC and we
12285
0
             * tested the unadjusted size against minLength, above. */
12286
0
            plaintext->len -= spec->macDef->mac_size;
12287
0
        } else {
12288
0
            /* This is safe because we checked the minLength above. */
12289
0
            plaintext->len -= spec->macDef->mac_size;
12290
0
12291
0
            rv = ssl3_ComputeRecordMAC(
12292
0
                spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
12293
0
                plaintext->buf, plaintext->len, hash, &hashBytes);
12294
0
12295
0
            /* We can read the MAC directly from the record because its location
12296
0
             * is public when a stream cipher is used. */
12297
0
            givenHash = plaintext->buf + plaintext->len;
12298
0
        }
12299
0
12300
0
        good &= SECStatusToMask(rv);
12301
0
12302
0
        if (hashBytes != (unsigned)spec->macDef->mac_size ||
12303
0
            NSS_SecureMemcmp(givenHash, hash, spec->macDef->mac_size) != 0) {
12304
0
            /* We're allowed to leak whether or not the MAC check was correct */
12305
0
            good = 0;
12306
0
        }
12307
0
    }
12308
0
12309
0
    if (good == 0) {
12310
0
    decrypt_loser:
12311
0
        /* always log mac error, in case attacker can read server logs. */
12312
0
        PORT_SetError(SSL_ERROR_BAD_MAC_READ);
12313
0
        *alert = bad_record_mac;
12314
0
        return SECFailure;
12315
0
    }
12316
0
    return SECSuccess;
12317
0
}
12318
12319
SECStatus
12320
ssl3_HandleNonApplicationData(sslSocket *ss, SSLContentType rType,
12321
                              DTLSEpoch epoch, sslSequenceNumber seqNum,
12322
                              sslBuffer *databuf)
12323
0
{
12324
0
    SECStatus rv;
12325
0
12326
0
    /* check for Token Presence */
12327
0
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
12328
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
12329
0
        return SECFailure;
12330
0
    }
12331
0
12332
0
    ssl_GetSSL3HandshakeLock(ss);
12333
0
12334
0
    /* All the functions called in this switch MUST set error code if
12335
0
    ** they return SECFailure or SECWouldBlock.
12336
0
    */
12337
0
    switch (rType) {
12338
0
        case ssl_ct_change_cipher_spec:
12339
0
            rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
12340
0
            break;
12341
0
        case ssl_ct_alert:
12342
0
            rv = ssl3_HandleAlert(ss, databuf);
12343
0
            break;
12344
0
        case ssl_ct_handshake:
12345
0
            if (!IS_DTLS(ss)) {
12346
0
                rv = ssl3_HandleHandshake(ss, databuf);
12347
0
            } else {
12348
0
                rv = dtls_HandleHandshake(ss, epoch, seqNum, databuf);
12349
0
            }
12350
0
            break;
12351
0
        case ssl_ct_ack:
12352
0
            if (IS_DTLS(ss) && tls13_MaybeTls13(ss)) {
12353
0
                rv = dtls13_HandleAck(ss, databuf);
12354
0
                break;
12355
0
            }
12356
0
        /* Fall through. */
12357
0
        default:
12358
0
            SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
12359
0
                     SSL_GETPID(), ss->fd, rType));
12360
0
            PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
12361
0
            ssl3_DecodeError(ss);
12362
0
            rv = SECFailure;
12363
0
            break;
12364
0
    }
12365
0
12366
0
    ssl_ReleaseSSL3HandshakeLock(ss);
12367
0
    return rv;
12368
0
}
12369
12370
/* Find the cipher spec to use for a given record. For TLS, this
12371
 * is the current cipherspec. For DTLS, we look up by epoch.
12372
 * In DTLS < 1.3 this just means the current epoch or nothing,
12373
 * but in DTLS >= 1.3, we keep multiple reading cipherspecs.
12374
 * Returns NULL if no appropriate cipher spec is found.
12375
 */
12376
static ssl3CipherSpec *
12377
ssl3_GetCipherSpec(sslSocket *ss, SSL3Ciphertext *cText)
12378
0
{
12379
0
    ssl3CipherSpec *crSpec = ss->ssl3.crSpec;
12380
0
    ssl3CipherSpec *newSpec = NULL;
12381
0
    DTLSEpoch epoch;
12382
0
12383
0
    if (!IS_DTLS(ss)) {
12384
0
        return crSpec;
12385
0
    }
12386
0
    epoch = dtls_ReadEpoch(crSpec, cText->hdr);
12387
0
    if (crSpec->epoch == epoch) {
12388
0
        return crSpec;
12389
0
    }
12390
0
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
12391
0
        /* Try to find the cipher spec. */
12392
0
        newSpec = ssl_FindCipherSpecByEpoch(ss, CipherSpecRead,
12393
0
                                            epoch);
12394
0
        if (newSpec != NULL) {
12395
0
            return newSpec;
12396
0
        }
12397
0
    }
12398
0
    SSL_TRC(10, ("%d: DTLS[%d]: Couldn't find cipherspec from epoch %d",
12399
0
                 SSL_GETPID(), ss->fd, epoch));
12400
0
    return NULL;
12401
0
}
12402
12403
/* MAX_EXPANSION is the amount by which a record might plausibly be expanded
12404
 * when protected.  It's the worst case estimate, so the sum of block cipher
12405
 * padding (up to 256 octets) and HMAC (48 octets for SHA-384). */
12406
0
#define MAX_EXPANSION (256 + 48)
12407
12408
/* if cText is non-null, then decipher and check the MAC of the
12409
 * SSL record from cText->buf (typically gs->inbuf)
12410
 * into databuf (typically gs->buf), and any previous contents of databuf
12411
 * is lost.  Then handle databuf according to its SSL record type,
12412
 * unless it's an application record.
12413
 *
12414
 * If cText is NULL, then the ciphertext has previously been deciphered and
12415
 * checked, and is already sitting in databuf.  It is processed as an SSL
12416
 * Handshake message.
12417
 *
12418
 * DOES NOT process the decrypted application data.
12419
 * On return, databuf contains the decrypted record.
12420
 *
12421
 * Called from ssl3_GatherCompleteHandshake
12422
 *             ssl3_RestartHandshakeAfterCertReq
12423
 *
12424
 * Caller must hold the RecvBufLock.
12425
 *
12426
 * This function aquires and releases the SSL3Handshake Lock, holding the
12427
 * lock around any calls to functions that handle records other than
12428
 * Application Data records.
12429
 */
12430
SECStatus
12431
ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText)
12432
0
{
12433
0
    SECStatus rv;
12434
0
    PRBool isTLS;
12435
0
    DTLSEpoch epoch;
12436
0
    ssl3CipherSpec *spec = NULL;
12437
0
    PRUint16 recordSizeLimit;
12438
0
    PRBool outOfOrderSpec = PR_FALSE;
12439
0
    SSLContentType rType;
12440
0
    sslBuffer *plaintext = &ss->gs.buf;
12441
0
    SSL3AlertDescription alert = internal_error;
12442
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12443
0
12444
0
    /* check for Token Presence */
12445
0
    if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
12446
0
        PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
12447
0
        return SECFailure;
12448
0
    }
12449
0
12450
0
    /* Clear out the buffer in case this exits early.  Any data then won't be
12451
0
     * processed twice. */
12452
0
    plaintext->len = 0;
12453
0
12454
0
    /* We're waiting for another ClientHello, which will appear unencrypted.
12455
0
     * Use the content type to tell whether this should be discarded. */
12456
0
    if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr &&
12457
0
        cText->hdr[0] == ssl_ct_application_data) {
12458
0
        PORT_Assert(ss->ssl3.hs.ws == wait_client_hello);
12459
0
        return SECSuccess;
12460
0
    }
12461
0
12462
0
    ssl_GetSpecReadLock(ss); /******************************************/
12463
0
    spec = ssl3_GetCipherSpec(ss, cText);
12464
0
    if (!spec) {
12465
0
        PORT_Assert(IS_DTLS(ss));
12466
0
        ssl_ReleaseSpecReadLock(ss); /*****************************/
12467
0
        return SECSuccess;
12468
0
    }
12469
0
    if (spec != ss->ssl3.crSpec) {
12470
0
        PORT_Assert(IS_DTLS(ss));
12471
0
        SSL_TRC(3, ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d",
12472
0
                    SSL_GETPID(), ss->fd, spec->epoch));
12473
0
        outOfOrderSpec = PR_TRUE;
12474
0
    }
12475
0
    isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
12476
0
    if (IS_DTLS(ss)) {
12477
0
        if (!dtls_IsRelevant(ss, spec, cText, &cText->seqNum)) {
12478
0
            ssl_ReleaseSpecReadLock(ss); /*****************************/
12479
0
            return SECSuccess;
12480
0
        }
12481
0
    } else {
12482
0
        cText->seqNum = spec->nextSeqNum;
12483
0
    }
12484
0
    if (cText->seqNum >= spec->cipherDef->max_records) {
12485
0
        ssl_ReleaseSpecReadLock(ss); /*****************************/
12486
0
        SSL_TRC(3, ("%d: SSL[%d]: read sequence number at limit 0x%0llx",
12487
0
                    SSL_GETPID(), ss->fd, cText->seqNum));
12488
0
        PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
12489
0
        return SECFailure;
12490
0
    }
12491
0
12492
0
    recordSizeLimit = spec->recordSizeLimit;
12493
0
    if (cText->buf->len > recordSizeLimit + MAX_EXPANSION) {
12494
0
        ssl_ReleaseSpecReadLock(ss); /*****************************/
12495
0
        SSL3_SendAlert(ss, alert_fatal, record_overflow);
12496
0
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
12497
0
        return SECFailure;
12498
0
    }
12499
0
12500
0
    if (plaintext->space < recordSizeLimit + MAX_EXPANSION) {
12501
0
        rv = sslBuffer_Grow(plaintext, recordSizeLimit + MAX_EXPANSION);
12502
0
        if (rv != SECSuccess) {
12503
0
            ssl_ReleaseSpecReadLock(ss); /*************************/
12504
0
            SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
12505
0
                     SSL_GETPID(), ss->fd, recordSizeLimit + MAX_EXPANSION));
12506
0
            /* sslBuffer_Grow has set a memory error code. */
12507
0
            /* Perhaps we should send an alert. (but we have no memory!) */
12508
0
            return SECFailure;
12509
0
        }
12510
0
    }
12511
0
12512
0
    /* Most record types aside from protected TLS 1.3 records carry the content
12513
0
     * type in the first octet. TLS 1.3 will override this value later. */
12514
0
    rType = cText->hdr[0];
12515
0
    /* Encrypted application data records could arrive before the handshake
12516
0
     * completes in DTLS 1.3. These can look like valid TLS 1.2 application_data
12517
0
     * records in epoch 0, which is never valid. Pretend they didn't decrypt. */
12518
0
    if (spec->epoch == 0 && rType == ssl_ct_application_data) {
12519
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
12520
0
        alert = unexpected_message;
12521
0
        rv = SECFailure;
12522
0
    } else {
12523
#ifdef UNSAFE_FUZZER_MODE
12524
        rv = Null_Cipher(NULL, plaintext->buf, (int *)&plaintext->len,
12525
                         plaintext->space, cText->buf->buf, cText->buf->len);
12526
#else
12527
        /* IMPORTANT: Unprotect functions MUST NOT send alerts
12528
0
         * because we still hold the spec read lock. Instead, if they
12529
0
         * return SECFailure, they set *alert to the alert to be sent. */
12530
0
        if (spec->version < SSL_LIBRARY_VERSION_TLS_1_3 ||
12531
0
            spec->epoch == 0) {
12532
0
            rv = ssl3_UnprotectRecord(ss, spec, cText, plaintext, &alert);
12533
0
        } else {
12534
0
            rv = tls13_UnprotectRecord(ss, spec, cText, plaintext, &rType,
12535
0
                                       &alert);
12536
0
        }
12537
0
#endif
12538
0
    }
12539
0
12540
0
    if (rv != SECSuccess) {
12541
0
        ssl_ReleaseSpecReadLock(ss); /***************************/
12542
0
12543
0
        SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
12544
0
12545
0
        /* Ensure that we don't process this data again. */
12546
0
        plaintext->len = 0;
12547
0
12548
0
        /* Ignore a CCS if compatibility mode is negotiated.  Note that this
12549
0
         * will fail if the server fails to negotiate compatibility mode in a
12550
0
         * 0-RTT session that is resumed from a session that did negotiate it.
12551
0
         * We don't care about that corner case right now. */
12552
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
12553
0
            cText->hdr[0] == ssl_ct_change_cipher_spec &&
12554
0
            ss->ssl3.hs.ws != idle_handshake &&
12555
0
            cText->buf->len == 1 &&
12556
0
            cText->buf->buf[0] == change_cipher_spec_choice) {
12557
0
            /* Ignore the CCS. */
12558
0
            return SECSuccess;
12559
0
        }
12560
0
12561
0
        if (IS_DTLS(ss) ||
12562
0
            (ss->sec.isServer &&
12563
0
             ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_trial)) {
12564
0
            /* Silently drop the packet unless we sent a fatal alert. */
12565
0
            if (ss->ssl3.fatalAlertSent) {
12566
0
                return SECFailure;
12567
0
            }
12568
0
            return SECSuccess;
12569
0
        }
12570
0
12571
0
        int errCode = PORT_GetError();
12572
0
        SSL3_SendAlert(ss, alert_fatal, alert);
12573
0
        /* Reset the error code in case SSL3_SendAlert called
12574
0
         * PORT_SetError(). */
12575
0
        PORT_SetError(errCode);
12576
0
        return SECFailure;
12577
0
    }
12578
0
12579
0
    /* SECSuccess */
12580
0
    if (IS_DTLS(ss)) {
12581
0
        dtls_RecordSetRecvd(&spec->recvdRecords, cText->seqNum);
12582
0
        spec->nextSeqNum = PR_MAX(spec->nextSeqNum, cText->seqNum + 1);
12583
0
    } else {
12584
0
        ++spec->nextSeqNum;
12585
0
    }
12586
0
    epoch = spec->epoch;
12587
0
12588
0
    ssl_ReleaseSpecReadLock(ss); /*****************************************/
12589
0
12590
0
    /*
12591
0
     * The decrypted data is now in plaintext.
12592
0
     */
12593
0
12594
0
    /* IMPORTANT: We are in DTLS 1.3 mode and we have processed something
12595
0
     * from the wrong epoch. Divert to a divert processing function to make
12596
0
     * sure we don't accidentally use the data unsafely. */
12597
0
    if (outOfOrderSpec) {
12598
0
        PORT_Assert(IS_DTLS(ss) && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
12599
0
        return dtls13_HandleOutOfEpochRecord(ss, spec, rType, plaintext);
12600
0
    }
12601
0
12602
0
    /* Check the length of the plaintext. */
12603
0
    if (isTLS && plaintext->len > recordSizeLimit) {
12604
0
        plaintext->len = 0;
12605
0
        SSL3_SendAlert(ss, alert_fatal, record_overflow);
12606
0
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
12607
0
        return SECFailure;
12608
0
    }
12609
0
12610
0
    /* Application data records are processed by the caller of this
12611
0
    ** function, not by this function.
12612
0
    */
12613
0
    if (rType == ssl_ct_application_data) {
12614
0
        if (ss->firstHsDone)
12615
0
            return SECSuccess;
12616
0
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
12617
0
            ss->sec.isServer &&
12618
0
            ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
12619
0
            return tls13_HandleEarlyApplicationData(ss, plaintext);
12620
0
        }
12621
0
        plaintext->len = 0;
12622
0
        (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12623
0
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
12624
0
        return SECFailure;
12625
0
    }
12626
0
12627
0
    return ssl3_HandleNonApplicationData(ss, rType, epoch, cText->seqNum,
12628
0
                                         plaintext);
12629
0
}
12630
12631
/*
12632
 * Initialization functions
12633
 */
12634
12635
void
12636
ssl_InitSecState(sslSecurityInfo *sec)
12637
0
{
12638
0
    sec->authType = ssl_auth_null;
12639
0
    sec->authKeyBits = 0;
12640
0
    sec->signatureScheme = ssl_sig_none;
12641
0
    sec->keaType = ssl_kea_null;
12642
0
    sec->keaKeyBits = 0;
12643
0
    sec->keaGroup = NULL;
12644
0
}
12645
12646
SECStatus
12647
ssl3_InitState(sslSocket *ss)
12648
0
{
12649
0
    SECStatus rv;
12650
0
12651
0
    ss->ssl3.policy = SSL_ALLOWED;
12652
0
12653
0
    ssl_InitSecState(&ss->sec);
12654
0
12655
0
    ssl_GetSpecWriteLock(ss);
12656
0
    PR_INIT_CLIST(&ss->ssl3.hs.cipherSpecs);
12657
0
    rv = ssl_SetupNullCipherSpec(ss, CipherSpecRead);
12658
0
    rv |= ssl_SetupNullCipherSpec(ss, CipherSpecWrite);
12659
0
    ss->ssl3.pwSpec = ss->ssl3.prSpec = NULL;
12660
0
    ssl_ReleaseSpecWriteLock(ss);
12661
0
    if (rv != SECSuccess) {
12662
0
        /* Rely on ssl_CreateNullCipherSpec() to set error code. */
12663
0
        return SECFailure;
12664
0
    }
12665
0
12666
0
    ss->ssl3.hs.sendingSCSV = PR_FALSE;
12667
0
    ss->ssl3.hs.preliminaryInfo = 0;
12668
0
    ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : idle_handshake;
12669
0
12670
0
    ssl3_ResetExtensionData(&ss->xtnData, ss);
12671
0
    PR_INIT_CLIST(&ss->ssl3.hs.remoteExtensions);
12672
0
    if (IS_DTLS(ss)) {
12673
0
        ss->ssl3.hs.sendMessageSeq = 0;
12674
0
        ss->ssl3.hs.recvMessageSeq = 0;
12675
0
        ss->ssl3.hs.rtTimer->timeout = DTLS_RETRANSMIT_INITIAL_MS;
12676
0
        ss->ssl3.hs.rtRetries = 0;
12677
0
        ss->ssl3.hs.recvdHighWater = -1;
12678
0
        PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
12679
0
        dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
12680
0
    }
12681
0
12682
0
    ss->ssl3.hs.currentSecret = NULL;
12683
0
    ss->ssl3.hs.resumptionMasterSecret = NULL;
12684
0
    ss->ssl3.hs.dheSecret = NULL;
12685
0
    ss->ssl3.hs.pskBinderKey = NULL;
12686
0
    ss->ssl3.hs.clientEarlyTrafficSecret = NULL;
12687
0
    ss->ssl3.hs.clientHsTrafficSecret = NULL;
12688
0
    ss->ssl3.hs.serverHsTrafficSecret = NULL;
12689
0
    ss->ssl3.hs.clientTrafficSecret = NULL;
12690
0
    ss->ssl3.hs.serverTrafficSecret = NULL;
12691
0
12692
0
    PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
12693
0
    ss->ssl3.hs.messages.buf = NULL;
12694
0
    ss->ssl3.hs.messages.space = 0;
12695
0
12696
0
    ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
12697
0
    PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0,
12698
0
                sizeof(ss->ssl3.hs.newSessionTicket));
12699
0
12700
0
    ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
12701
0
12702
0
    return SECSuccess;
12703
0
}
12704
12705
/* record the export policy for this cipher suite */
12706
SECStatus
12707
ssl3_SetPolicy(ssl3CipherSuite which, int policy)
12708
0
{
12709
0
    ssl3CipherSuiteCfg *suite;
12710
0
12711
0
    suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
12712
0
    if (suite == NULL) {
12713
0
        return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
12714
0
    }
12715
0
    suite->policy = policy;
12716
0
12717
0
    return SECSuccess;
12718
0
}
12719
12720
SECStatus
12721
ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
12722
0
{
12723
0
    const ssl3CipherSuiteCfg *suite;
12724
0
    PRInt32 policy;
12725
0
    SECStatus rv;
12726
0
12727
0
    suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
12728
0
    if (suite) {
12729
0
        policy = suite->policy;
12730
0
        rv = SECSuccess;
12731
0
    } else {
12732
0
        policy = SSL_NOT_ALLOWED;
12733
0
        rv = SECFailure; /* err code was set by Lookup. */
12734
0
    }
12735
0
    *oPolicy = policy;
12736
0
    return rv;
12737
0
}
12738
12739
/* record the user preference for this suite */
12740
SECStatus
12741
ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
12742
0
{
12743
0
    ssl3CipherSuiteCfg *suite;
12744
0
12745
0
    suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
12746
0
    if (suite == NULL) {
12747
0
        return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
12748
0
    }
12749
0
    suite->enabled = enabled;
12750
0
    return SECSuccess;
12751
0
}
12752
12753
/* return the user preference for this suite */
12754
SECStatus
12755
ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
12756
0
{
12757
0
    const ssl3CipherSuiteCfg *suite;
12758
0
    PRBool pref;
12759
0
    SECStatus rv;
12760
0
12761
0
    suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
12762
0
    if (suite) {
12763
0
        pref = suite->enabled;
12764
0
        rv = SECSuccess;
12765
0
    } else {
12766
0
        pref = SSL_NOT_ALLOWED;
12767
0
        rv = SECFailure; /* err code was set by Lookup. */
12768
0
    }
12769
0
    *enabled = pref;
12770
0
    return rv;
12771
0
}
12772
12773
SECStatus
12774
ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
12775
0
{
12776
0
    ssl3CipherSuiteCfg *suite;
12777
0
12778
0
    suite = ssl_LookupCipherSuiteCfgMutable(which, ss->cipherSuites);
12779
0
    if (suite == NULL) {
12780
0
        return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
12781
0
    }
12782
0
    suite->enabled = enabled;
12783
0
    return SECSuccess;
12784
0
}
12785
12786
SECStatus
12787
ssl3_CipherPrefGet(const sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
12788
0
{
12789
0
    const ssl3CipherSuiteCfg *suite;
12790
0
    PRBool pref;
12791
0
    SECStatus rv;
12792
0
12793
0
    suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
12794
0
    if (suite) {
12795
0
        pref = suite->enabled;
12796
0
        rv = SECSuccess;
12797
0
    } else {
12798
0
        pref = SSL_NOT_ALLOWED;
12799
0
        rv = SECFailure; /* err code was set by Lookup. */
12800
0
    }
12801
0
    *enabled = pref;
12802
0
    return rv;
12803
0
}
12804
12805
SECStatus
12806
SSL_SignatureSchemePrefSet(PRFileDesc *fd, const SSLSignatureScheme *schemes,
12807
                           unsigned int count)
12808
0
{
12809
0
    sslSocket *ss;
12810
0
    unsigned int i;
12811
0
    unsigned int supported = 0;
12812
0
12813
0
    ss = ssl_FindSocket(fd);
12814
0
    if (!ss) {
12815
0
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefSet",
12816
0
                 SSL_GETPID(), fd));
12817
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
12818
0
        return SECFailure;
12819
0
    }
12820
0
12821
0
    if (!count) {
12822
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
12823
0
        return SECFailure;
12824
0
    }
12825
0
12826
0
    for (i = 0; i < count; ++i) {
12827
0
        if (ssl_IsSupportedSignatureScheme(schemes[i])) {
12828
0
            ++supported;
12829
0
        }
12830
0
    }
12831
0
    /* We don't check for duplicates, so it's possible to get too many. */
12832
0
    if (supported > MAX_SIGNATURE_SCHEMES) {
12833
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
12834
0
        return SECFailure;
12835
0
    }
12836
0
12837
0
    ss->ssl3.signatureSchemeCount = 0;
12838
0
    for (i = 0; i < count; ++i) {
12839
0
        if (!ssl_IsSupportedSignatureScheme(schemes[i])) {
12840
0
            SSL_DBG(("%d: SSL[%d]: invalid signature scheme %d ignored",
12841
0
                     SSL_GETPID(), fd, schemes[i]));
12842
0
            continue;
12843
0
        }
12844
0
12845
0
        ss->ssl3.signatureSchemes[ss->ssl3.signatureSchemeCount++] = schemes[i];
12846
0
    }
12847
0
12848
0
    if (ss->ssl3.signatureSchemeCount == 0) {
12849
0
        PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
12850
0
        return SECFailure;
12851
0
    }
12852
0
    return SECSuccess;
12853
0
}
12854
12855
SECStatus
12856
SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms,
12857
                     unsigned int count)
12858
0
{
12859
0
    SSLSignatureScheme schemes[MAX_SIGNATURE_SCHEMES];
12860
0
    unsigned int i;
12861
0
12862
0
    count = PR_MIN(PR_ARRAY_SIZE(schemes), count);
12863
0
    for (i = 0; i < count; ++i) {
12864
0
        schemes[i] = (algorithms[i].hashAlg << 8) | algorithms[i].sigAlg;
12865
0
    }
12866
0
    return SSL_SignatureSchemePrefSet(fd, schemes, count);
12867
0
}
12868
12869
SECStatus
12870
SSL_SignatureSchemePrefGet(PRFileDesc *fd, SSLSignatureScheme *schemes,
12871
                           unsigned int *count, unsigned int maxCount)
12872
0
{
12873
0
    sslSocket *ss;
12874
0
12875
0
    ss = ssl_FindSocket(fd);
12876
0
    if (!ss) {
12877
0
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefGet",
12878
0
                 SSL_GETPID(), fd));
12879
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
12880
0
        return SECFailure;
12881
0
    }
12882
0
12883
0
    if (!schemes || !count ||
12884
0
        maxCount < ss->ssl3.signatureSchemeCount) {
12885
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
12886
0
        return SECFailure;
12887
0
    }
12888
0
12889
0
    PORT_Memcpy(schemes, ss->ssl3.signatureSchemes,
12890
0
                ss->ssl3.signatureSchemeCount * sizeof(SSLSignatureScheme));
12891
0
    *count = ss->ssl3.signatureSchemeCount;
12892
0
    return SECSuccess;
12893
0
}
12894
12895
SECStatus
12896
SSL_SignaturePrefGet(PRFileDesc *fd, SSLSignatureAndHashAlg *algorithms,
12897
                     unsigned int *count, unsigned int maxCount)
12898
0
{
12899
0
    sslSocket *ss;
12900
0
    unsigned int i;
12901
0
12902
0
    ss = ssl_FindSocket(fd);
12903
0
    if (!ss) {
12904
0
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignaturePrefGet",
12905
0
                 SSL_GETPID(), fd));
12906
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
12907
0
        return SECFailure;
12908
0
    }
12909
0
12910
0
    if (!algorithms || !count ||
12911
0
        maxCount < ss->ssl3.signatureSchemeCount) {
12912
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
12913
0
        return SECFailure;
12914
0
    }
12915
0
12916
0
    for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
12917
0
        algorithms[i].hashAlg = (ss->ssl3.signatureSchemes[i] >> 8) & 0xff;
12918
0
        algorithms[i].sigAlg = ss->ssl3.signatureSchemes[i] & 0xff;
12919
0
    }
12920
0
    *count = ss->ssl3.signatureSchemeCount;
12921
0
    return SECSuccess;
12922
0
}
12923
12924
unsigned int
12925
SSL_SignatureMaxCount(void)
12926
0
{
12927
0
    return MAX_SIGNATURE_SCHEMES;
12928
0
}
12929
12930
/* copy global default policy into socket. */
12931
void
12932
ssl3_InitSocketPolicy(sslSocket *ss)
12933
0
{
12934
0
    PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof(cipherSuites));
12935
0
    PORT_Memcpy(ss->ssl3.signatureSchemes, defaultSignatureSchemes,
12936
0
                sizeof(defaultSignatureSchemes));
12937
0
    ss->ssl3.signatureSchemeCount = PR_ARRAY_SIZE(defaultSignatureSchemes);
12938
0
}
12939
12940
/*
12941
** If ssl3 socket has completed the first handshake, and is in idle state,
12942
** then start a new handshake.
12943
** If flushCache is true, the SID cache will be flushed first, forcing a
12944
** "Full" handshake (not a session restart handshake), to be done.
12945
**
12946
** called from SSL_RedoHandshake(), which already holds the handshake locks.
12947
*/
12948
SECStatus
12949
ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
12950
0
{
12951
0
    sslSessionID *sid = ss->sec.ci.sid;
12952
0
    SECStatus rv;
12953
0
12954
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12955
0
12956
0
    if (!ss->firstHsDone || (ss->ssl3.hs.ws != idle_handshake)) {
12957
0
        PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
12958
0
        return SECFailure;
12959
0
    }
12960
0
12961
0
    if (IS_DTLS(ss)) {
12962
0
        dtls_RehandshakeCleanup(ss);
12963
0
    }
12964
0
12965
0
    if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER ||
12966
0
        ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
12967
0
        PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
12968
0
        return SECFailure;
12969
0
    }
12970
0
    if (ss->version > ss->vrange.max || ss->version < ss->vrange.min) {
12971
0
        PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
12972
0
        return SECFailure;
12973
0
    }
12974
0
12975
0
    if (sid && flushCache) {
12976
0
        ssl_UncacheSessionID(ss); /* remove it from whichever cache it's in. */
12977
0
        ssl_FreeSID(sid);         /* dec ref count and free if zero. */
12978
0
        ss->sec.ci.sid = NULL;
12979
0
    }
12980
0
12981
0
    ssl_GetXmitBufLock(ss); /**************************************/
12982
0
12983
0
    /* start off a new handshake. */
12984
0
    if (ss->sec.isServer) {
12985
0
        rv = ssl3_SendHelloRequest(ss);
12986
0
    } else {
12987
0
        rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
12988
0
    }
12989
0
12990
0
    ssl_ReleaseXmitBufLock(ss); /**************************************/
12991
0
    return rv;
12992
0
}
12993
12994
/* Called from ssl_DestroySocketContents() in sslsock.c */
12995
void
12996
ssl3_DestroySSL3Info(sslSocket *ss)
12997
0
{
12998
0
12999
0
    if (ss->ssl3.clientCertificate != NULL)
13000
0
        CERT_DestroyCertificate(ss->ssl3.clientCertificate);
13001
0
13002
0
    if (ss->ssl3.clientPrivateKey != NULL)
13003
0
        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
13004
0
13005
0
    if (ss->ssl3.peerCertArena != NULL)
13006
0
        ssl3_CleanupPeerCerts(ss);
13007
0
13008
0
    if (ss->ssl3.clientCertChain != NULL) {
13009
0
        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
13010
0
        ss->ssl3.clientCertChain = NULL;
13011
0
    }
13012
0
    if (ss->ssl3.ca_list) {
13013
0
        CERT_FreeDistNames(ss->ssl3.ca_list);
13014
0
    }
13015
0
13016
0
    /* clean up handshake */
13017
0
    if (ss->ssl3.hs.md5) {
13018
0
        PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
13019
0
    }
13020
0
    if (ss->ssl3.hs.sha) {
13021
0
        PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
13022
0
    }
13023
0
    if (ss->ssl3.hs.messages.buf) {
13024
0
        sslBuffer_Clear(&ss->ssl3.hs.messages);
13025
0
    }
13026
0
13027
0
    /* free the SSL3Buffer (msg_body) */
13028
0
    PORT_Free(ss->ssl3.hs.msg_body.buf);
13029
0
13030
0
    SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
13031
0
    SECITEM_FreeItem(&ss->ssl3.hs.srvVirtName, PR_FALSE);
13032
0
    SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
13033
0
13034
0
    /* Destroy the DTLS data */
13035
0
    if (IS_DTLS(ss)) {
13036
0
        dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
13037
0
        if (ss->ssl3.hs.recvdFragments.buf) {
13038
0
            PORT_Free(ss->ssl3.hs.recvdFragments.buf);
13039
0
        }
13040
0
    }
13041
0
13042
0
    /* Destroy remote extensions */
13043
0
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
13044
0
    ssl3_DestroyExtensionData(&ss->xtnData);
13045
0
13046
0
    /* Destroy cipher specs */
13047
0
    ssl_DestroyCipherSpecs(&ss->ssl3.hs.cipherSpecs);
13048
0
13049
0
    /* Destroy TLS 1.3 keys */
13050
0
    if (ss->ssl3.hs.currentSecret)
13051
0
        PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
13052
0
    if (ss->ssl3.hs.resumptionMasterSecret)
13053
0
        PK11_FreeSymKey(ss->ssl3.hs.resumptionMasterSecret);
13054
0
    if (ss->ssl3.hs.dheSecret)
13055
0
        PK11_FreeSymKey(ss->ssl3.hs.dheSecret);
13056
0
    if (ss->ssl3.hs.pskBinderKey)
13057
0
        PK11_FreeSymKey(ss->ssl3.hs.pskBinderKey);
13058
0
    if (ss->ssl3.hs.clientEarlyTrafficSecret)
13059
0
        PK11_FreeSymKey(ss->ssl3.hs.clientEarlyTrafficSecret);
13060
0
    if (ss->ssl3.hs.clientHsTrafficSecret)
13061
0
        PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
13062
0
    if (ss->ssl3.hs.serverHsTrafficSecret)
13063
0
        PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
13064
0
    if (ss->ssl3.hs.clientTrafficSecret)
13065
0
        PK11_FreeSymKey(ss->ssl3.hs.clientTrafficSecret);
13066
0
    if (ss->ssl3.hs.serverTrafficSecret)
13067
0
        PK11_FreeSymKey(ss->ssl3.hs.serverTrafficSecret);
13068
0
    if (ss->ssl3.hs.earlyExporterSecret)
13069
0
        PK11_FreeSymKey(ss->ssl3.hs.earlyExporterSecret);
13070
0
    if (ss->ssl3.hs.exporterSecret)
13071
0
        PK11_FreeSymKey(ss->ssl3.hs.exporterSecret);
13072
0
13073
0
    ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
13074
0
    /* Destroy TLS 1.3 buffered early data. */
13075
0
    tls13_DestroyEarlyData(&ss->ssl3.hs.bufferedEarlyData);
13076
0
}
13077
13078
0
#define MAP_NULL(x) (((x) != 0) ? (x) : SEC_OID_NULL_CIPHER)
13079
13080
SECStatus
13081
ssl3_ApplyNSSPolicy(void)
13082
0
{
13083
0
    unsigned i;
13084
0
    SECStatus rv;
13085
0
    PRUint32 policy = 0;
13086
0
13087
0
    rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy);
13088
0
    if (rv != SECSuccess || !(policy & NSS_USE_POLICY_IN_SSL)) {
13089
0
        return SECSuccess; /* do nothing */
13090
0
    }
13091
0
13092
0
    /* disable every ciphersuite */
13093
0
    for (i = 1; i < PR_ARRAY_SIZE(cipher_suite_defs); ++i) {
13094
0
        const ssl3CipherSuiteDef *suite = &cipher_suite_defs[i];
13095
0
        SECOidTag policyOid;
13096
0
13097
0
        policyOid = MAP_NULL(kea_defs[suite->key_exchange_alg].oid);
13098
0
        rv = NSS_GetAlgorithmPolicy(policyOid, &policy);
13099
0
        if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL_KX)) {
13100
0
            ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE);
13101
0
            ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED);
13102
0
            continue;
13103
0
        }
13104
0
13105
0
        policyOid = MAP_NULL(ssl_GetBulkCipherDef(suite)->oid);
13106
0
        rv = NSS_GetAlgorithmPolicy(policyOid, &policy);
13107
0
        if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL)) {
13108
0
            ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE);
13109
0
            ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED);
13110
0
            continue;
13111
0
        }
13112
0
13113
0
        if (ssl_GetBulkCipherDef(suite)->type != type_aead) {
13114
0
            policyOid = MAP_NULL(ssl_GetMacDefByAlg(suite->mac_alg)->oid);
13115
0
            rv = NSS_GetAlgorithmPolicy(policyOid, &policy);
13116
0
            if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL)) {
13117
0
                ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE);
13118
0
                ssl_CipherPolicySet(suite->cipher_suite,
13119
0
                                    SSL_NOT_ALLOWED);
13120
0
                continue;
13121
0
            }
13122
0
        }
13123
0
    }
13124
0
13125
0
    rv = ssl3_ConstrainRangeByPolicy();
13126
0
13127
0
    return rv;
13128
0
}
13129
13130
/* End of ssl3con.c */