Coverage Report

Created: 2025-04-22 06:15

/src/nss/lib/ssl/tls13con.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
 * TLS 1.3 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
#include "sslt.h"
10
#include "stdarg.h"
11
#include "cert.h"
12
#include "ssl.h"
13
#include "keyhi.h"
14
#include "pk11func.h"
15
#include "prerr.h"
16
#include "secitem.h"
17
#include "secmod.h"
18
#include "sslimpl.h"
19
#include "sslproto.h"
20
#include "sslerr.h"
21
#include "ssl3exthandle.h"
22
#include "tls13hkdf.h"
23
#include "tls13con.h"
24
#include "tls13err.h"
25
#include "tls13ech.h"
26
#include "tls13exthandle.h"
27
#include "tls13hashstate.h"
28
#include "tls13subcerts.h"
29
#include "tls13psk.h"
30
31
static SECStatus tls13_SetCipherSpec(sslSocket *ss, PRUint16 epoch,
32
                                     SSLSecretDirection install,
33
                                     PRBool deleteSecret);
34
static SECStatus tls13_SendServerHelloSequence(sslSocket *ss);
35
static SECStatus tls13_SendEncryptedExtensions(sslSocket *ss);
36
static void tls13_SetKeyExchangeType(sslSocket *ss, const sslNamedGroupDef *group);
37
static SECStatus tls13_HandleClientKeyShare(sslSocket *ss,
38
                                            TLS13KeyShareEntry *peerShare);
39
static SECStatus tls13_SendHelloRetryRequest(
40
    sslSocket *ss, const sslNamedGroupDef *selectedGroup,
41
    const PRUint8 *token, unsigned int tokenLen);
42
43
static SECStatus tls13_HandleServerKeyShare(sslSocket *ss);
44
static SECStatus tls13_HandleEncryptedExtensions(sslSocket *ss, PRUint8 *b,
45
                                                 PRUint32 length);
46
static SECStatus tls13_SendCertificate(sslSocket *ss);
47
static SECStatus tls13_HandleCertificateDecode(
48
    sslSocket *ss, PRUint8 *b, PRUint32 length);
49
static SECStatus tls13_HandleCertificate(
50
    sslSocket *ss, PRUint8 *b, PRUint32 length, PRBool alreadyHashed);
51
static SECStatus tls13_ReinjectHandshakeTranscript(sslSocket *ss);
52
static SECStatus tls13_SendCertificateRequest(sslSocket *ss);
53
static SECStatus tls13_HandleCertificateRequest(sslSocket *ss, PRUint8 *b,
54
                                                PRUint32 length);
55
static SECStatus
56
tls13_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey);
57
static SECStatus tls13_HandleCertificateVerify(
58
    sslSocket *ss, PRUint8 *b, PRUint32 length);
59
static SECStatus tls13_RecoverWrappedSharedSecret(sslSocket *ss,
60
                                                  sslSessionID *sid);
61
static SECStatus
62
tls13_DeriveSecretWrap(sslSocket *ss, PK11SymKey *key,
63
                       const char *prefix,
64
                       const char *suffix,
65
                       const char *keylogLabel,
66
                       PK11SymKey **dest);
67
SECStatus
68
tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key,
69
                   const char *label,
70
                   unsigned int labelLen,
71
                   const SSL3Hashes *hashes,
72
                   PK11SymKey **dest,
73
                   SSLHashType hash);
74
static SECStatus tls13_SendEndOfEarlyData(sslSocket *ss);
75
static SECStatus tls13_HandleEndOfEarlyData(sslSocket *ss, const PRUint8 *b,
76
                                            PRUint32 length);
77
static SECStatus tls13_MaybeHandleSuppressedEndOfEarlyData(sslSocket *ss);
78
static SECStatus tls13_SendFinished(sslSocket *ss, PK11SymKey *baseKey);
79
static SECStatus tls13_ComputePskBinderHash(sslSocket *ss, PRUint8 *b, size_t length,
80
                                            SSL3Hashes *hashes, SSLHashType type);
81
static SECStatus tls13_VerifyFinished(sslSocket *ss, SSLHandshakeType message,
82
                                      PK11SymKey *secret,
83
                                      PRUint8 *b, PRUint32 length,
84
                                      const SSL3Hashes *hashes);
85
static SECStatus tls13_ClientHandleFinished(sslSocket *ss,
86
                                            PRUint8 *b, PRUint32 length);
87
static SECStatus tls13_ServerHandleFinished(sslSocket *ss,
88
                                            PRUint8 *b, PRUint32 length);
89
static SECStatus tls13_SendNewSessionTicket(sslSocket *ss,
90
                                            const PRUint8 *appToken,
91
                                            unsigned int appTokenLen);
92
static SECStatus tls13_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b,
93
                                              PRUint32 length);
94
static SECStatus tls13_ComputeEarlySecretsWithPsk(sslSocket *ss);
95
static SECStatus tls13_ComputeHandshakeSecrets(sslSocket *ss);
96
static SECStatus tls13_ComputeApplicationSecrets(sslSocket *ss);
97
static SECStatus tls13_ComputeFinalSecrets(sslSocket *ss);
98
static SECStatus tls13_ComputeFinished(
99
    sslSocket *ss, PK11SymKey *baseKey, SSLHashType hashType,
100
    const SSL3Hashes *hashes, PRBool sending, PRUint8 *output,
101
    unsigned int *outputLen, unsigned int maxOutputLen);
102
static SECStatus tls13_SendClientSecondRound(sslSocket *ss);
103
static SECStatus tls13_SendClientSecondFlight(sslSocket *ss);
104
static SECStatus tls13_FinishHandshake(sslSocket *ss);
105
106
const char kHkdfLabelClient[] = "c";
107
const char kHkdfLabelServer[] = "s";
108
const char kHkdfLabelDerivedSecret[] = "derived";
109
const char kHkdfLabelResPskBinderKey[] = "res binder";
110
const char kHkdfLabelExtPskBinderKey[] = "ext binder";
111
const char kHkdfLabelEarlyTrafficSecret[] = "e traffic";
112
const char kHkdfLabelEarlyExporterSecret[] = "e exp master";
113
const char kHkdfLabelHandshakeTrafficSecret[] = "hs traffic";
114
const char kHkdfLabelApplicationTrafficSecret[] = "ap traffic";
115
const char kHkdfLabelFinishedSecret[] = "finished";
116
const char kHkdfLabelResumptionMasterSecret[] = "res master";
117
const char kHkdfLabelExporterMasterSecret[] = "exp master";
118
const char kHkdfLabelResumption[] = "resumption";
119
const char kHkdfLabelTrafficUpdate[] = "traffic upd";
120
const char kHkdfPurposeKey[] = "key";
121
const char kHkdfPurposeSn[] = "sn";
122
const char kHkdfPurposeIv[] = "iv";
123
124
const char keylogLabelClientEarlyTrafficSecret[] = "CLIENT_EARLY_TRAFFIC_SECRET";
125
const char keylogLabelClientHsTrafficSecret[] = "CLIENT_HANDSHAKE_TRAFFIC_SECRET";
126
const char keylogLabelServerHsTrafficSecret[] = "SERVER_HANDSHAKE_TRAFFIC_SECRET";
127
const char keylogLabelClientTrafficSecret[] = "CLIENT_TRAFFIC_SECRET_0";
128
const char keylogLabelServerTrafficSecret[] = "SERVER_TRAFFIC_SECRET_0";
129
const char keylogLabelEarlyExporterSecret[] = "EARLY_EXPORTER_SECRET";
130
const char keylogLabelExporterSecret[] = "EXPORTER_SECRET";
131
132
/* Belt and suspenders in case we ever add a TLS 1.4. */
133
PR_STATIC_ASSERT(SSL_LIBRARY_VERSION_MAX_SUPPORTED <=
134
                 SSL_LIBRARY_VERSION_TLS_1_3);
135
136
void
137
tls13_FatalError(sslSocket *ss, PRErrorCode prError, SSL3AlertDescription desc)
138
238
{
139
238
    PORT_Assert(desc != internal_error); /* These should never happen */
140
238
    (void)SSL3_SendAlert(ss, alert_fatal, desc);
141
238
    PORT_SetError(prError);
142
238
}
143
144
#ifdef TRACE
145
#define STATE_CASE(a) \
146
1.43k
    case a:           \
147
1.43k
        return #a
148
static char *
149
tls13_HandshakeState(SSL3WaitState st)
150
1.43k
{
151
1.43k
    switch (st) {
152
0
        STATE_CASE(idle_handshake);
153
0
        STATE_CASE(wait_client_hello);
154
0
        STATE_CASE(wait_end_of_early_data);
155
0
        STATE_CASE(wait_client_cert);
156
0
        STATE_CASE(wait_client_key);
157
0
        STATE_CASE(wait_cert_verify);
158
0
        STATE_CASE(wait_change_cipher);
159
0
        STATE_CASE(wait_finished);
160
0
        STATE_CASE(wait_server_hello);
161
0
        STATE_CASE(wait_certificate_status);
162
0
        STATE_CASE(wait_server_cert);
163
0
        STATE_CASE(wait_server_key);
164
0
        STATE_CASE(wait_cert_request);
165
0
        STATE_CASE(wait_hello_done);
166
0
        STATE_CASE(wait_new_session_ticket);
167
1.43k
        STATE_CASE(wait_encrypted_extensions);
168
0
        default:
169
0
            break;
170
1.43k
    }
171
0
    PORT_Assert(0);
172
0
    return "unknown";
173
1.43k
}
174
#endif
175
176
3.33k
#define TLS13_WAIT_STATE_MASK 0x80
177
178
#define TLS13_BASE_WAIT_STATE(ws) (ws & ~TLS13_WAIT_STATE_MASK)
179
/* We don't mask idle_handshake because other parts of the code use it*/
180
1.89k
#define TLS13_WAIT_STATE(ws) (((ws == idle_handshake) || (ws == wait_server_hello)) ? ws : ws | TLS13_WAIT_STATE_MASK)
181
#define TLS13_CHECK_HS_STATE(ss, err, ...)                          \
182
13
    tls13_CheckHsState(ss, err, #err, __func__, __FILE__, __LINE__, \
183
13
                       __VA_ARGS__,                                 \
184
13
                       wait_invalid)
185
void
186
tls13_SetHsState(sslSocket *ss, SSL3WaitState ws,
187
                 const char *func, const char *file, int line)
188
1.43k
{
189
1.43k
#ifdef TRACE
190
1.43k
    const char *new_state_name =
191
1.43k
        tls13_HandshakeState(ws);
192
193
1.43k
    SSL_TRC(3, ("%d: TLS13[%d]: %s state change from %s->%s in %s (%s:%d)",
194
1.43k
                SSL_GETPID(), ss->fd, SSL_ROLE(ss),
195
1.43k
                tls13_HandshakeState(TLS13_BASE_WAIT_STATE(ss->ssl3.hs.ws)),
196
1.43k
                new_state_name,
197
1.43k
                func, file, line));
198
1.43k
#endif
199
200
1.43k
    ss->ssl3.hs.ws = TLS13_WAIT_STATE(ws);
201
1.43k
}
202
203
static PRBool
204
tls13_InHsStateV(sslSocket *ss, va_list ap)
205
452
{
206
452
    SSL3WaitState ws;
207
208
642
    while ((ws = va_arg(ap, SSL3WaitState)) != wait_invalid) {
209
456
        if (TLS13_WAIT_STATE(ws) == ss->ssl3.hs.ws) {
210
266
            return PR_TRUE;
211
266
        }
212
456
    }
213
186
    return PR_FALSE;
214
452
}
215
216
PRBool
217
tls13_InHsState(sslSocket *ss, ...)
218
439
{
219
439
    PRBool found;
220
439
    va_list ap;
221
222
439
    va_start(ap, ss);
223
439
    found = tls13_InHsStateV(ss, ap);
224
439
    va_end(ap);
225
226
439
    return found;
227
439
}
228
229
static SECStatus
230
tls13_CheckHsState(sslSocket *ss, int err, const char *error_name,
231
                   const char *func, const char *file, int line,
232
                   ...)
233
13
{
234
13
    va_list ap;
235
13
    va_start(ap, line);
236
13
    if (tls13_InHsStateV(ss, ap)) {
237
0
        va_end(ap);
238
0
        return SECSuccess;
239
0
    }
240
13
    va_end(ap);
241
242
13
    SSL_TRC(3, ("%d: TLS13[%d]: error %s state is (%s) at %s (%s:%d)",
243
13
                SSL_GETPID(), ss->fd,
244
13
                error_name,
245
13
                tls13_HandshakeState(TLS13_BASE_WAIT_STATE(ss->ssl3.hs.ws)),
246
13
                func, file, line));
247
13
    tls13_FatalError(ss, err, unexpected_message);
248
13
    return SECFailure;
249
13
}
250
251
PRBool
252
tls13_IsPostHandshake(const sslSocket *ss)
253
9.93k
{
254
9.93k
    return ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 && ss->firstHsDone;
255
9.93k
}
256
257
SSLHashType
258
tls13_GetHashForCipherSuite(ssl3CipherSuite suite)
259
10
{
260
10
    const ssl3CipherSuiteDef *cipherDef =
261
10
        ssl_LookupCipherSuiteDef(suite);
262
10
    PORT_Assert(cipherDef);
263
10
    if (!cipherDef) {
264
0
        return ssl_hash_none;
265
0
    }
266
10
    return cipherDef->prf_hash;
267
10
}
268
269
SSLHashType
270
tls13_GetHash(const sslSocket *ss)
271
18.8k
{
272
    /* suite_def may not be set yet when doing EPSK 0-Rtt. */
273
18.8k
    if (!ss->ssl3.hs.suite_def) {
274
0
        if (ss->xtnData.selectedPsk) {
275
0
            return ss->xtnData.selectedPsk->hash;
276
0
        }
277
        /* This should never happen. */
278
0
        PORT_Assert(0);
279
0
        return ssl_hash_none;
280
0
    }
281
282
    /* All TLS 1.3 cipher suites must have an explict PRF hash. */
283
18.8k
    PORT_Assert(ss->ssl3.hs.suite_def->prf_hash != ssl_hash_none);
284
18.8k
    return ss->ssl3.hs.suite_def->prf_hash;
285
18.8k
}
286
287
SECStatus
288
tls13_GetHashAndCipher(PRUint16 version, PRUint16 cipherSuite,
289
                       SSLHashType *hash, const ssl3BulkCipherDef **cipher)
290
1.60k
{
291
1.60k
    if (version < SSL_LIBRARY_VERSION_TLS_1_3) {
292
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
293
0
        return SECFailure;
294
0
    }
295
296
    // Lookup and check the suite.
297
1.60k
    SSLVersionRange vrange = { version, version };
298
1.60k
    if (!ssl3_CipherSuiteAllowedForVersionRange(cipherSuite, &vrange)) {
299
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
300
0
        return SECFailure;
301
0
    }
302
1.60k
    const ssl3CipherSuiteDef *suiteDef = ssl_LookupCipherSuiteDef(cipherSuite);
303
1.60k
    const ssl3BulkCipherDef *cipherDef = ssl_GetBulkCipherDef(suiteDef);
304
1.60k
    if (cipherDef->type != type_aead) {
305
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
306
0
        return SECFailure;
307
0
    }
308
1.60k
    *hash = suiteDef->prf_hash;
309
1.60k
    if (cipher != NULL) {
310
1.60k
        *cipher = cipherDef;
311
1.60k
    }
312
1.60k
    return SECSuccess;
313
1.60k
}
314
315
unsigned int
316
tls13_GetHashSizeForHash(SSLHashType hash)
317
43.3k
{
318
43.3k
    switch (hash) {
319
21.3k
        case ssl_hash_sha256:
320
21.3k
            return 32;
321
21.9k
        case ssl_hash_sha384:
322
21.9k
            return 48;
323
0
        default:
324
0
            PORT_Assert(0);
325
43.3k
    }
326
0
    return 32;
327
43.3k
}
328
329
unsigned int
330
tls13_GetHashSize(const sslSocket *ss)
331
2.86k
{
332
2.86k
    return tls13_GetHashSizeForHash(tls13_GetHash(ss));
333
2.86k
}
334
335
static CK_MECHANISM_TYPE
336
tls13_GetHmacMechanismFromHash(SSLHashType hashType)
337
9.03k
{
338
9.03k
    switch (hashType) {
339
2.95k
        case ssl_hash_sha256:
340
2.95k
            return CKM_SHA256_HMAC;
341
6.07k
        case ssl_hash_sha384:
342
6.07k
            return CKM_SHA384_HMAC;
343
0
        default:
344
0
            PORT_Assert(0);
345
9.03k
    }
346
0
    return CKM_SHA256_HMAC;
347
9.03k
}
348
349
static CK_MECHANISM_TYPE
350
tls13_GetHmacMechanism(const sslSocket *ss)
351
0
{
352
0
    return tls13_GetHmacMechanismFromHash(tls13_GetHash(ss));
353
0
}
354
355
SECStatus
356
tls13_ComputeHash(sslSocket *ss, SSL3Hashes *hashes,
357
                  const PRUint8 *buf, unsigned int len,
358
                  SSLHashType hash)
359
8.13k
{
360
8.13k
    SECStatus rv;
361
362
8.13k
    rv = PK11_HashBuf(ssl3_HashTypeToOID(hash), hashes->u.raw, buf, len);
363
8.13k
    if (rv != SECSuccess) {
364
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
365
0
        return SECFailure;
366
0
    }
367
8.13k
    hashes->len = tls13_GetHashSizeForHash(hash);
368
369
8.13k
    return SECSuccess;
370
8.13k
}
371
372
static SECStatus
373
tls13_CreateKEMKeyPair(sslSocket *ss, const sslNamedGroupDef *groupDef,
374
                       sslKeyPair **outKeyPair)
375
40
{
376
40
    PORT_Assert(groupDef);
377
378
40
    sslKeyPair *keyPair = NULL;
379
40
    SECKEYPrivateKey *privKey = NULL;
380
40
    SECKEYPublicKey *pubKey = NULL;
381
40
    CK_MECHANISM_TYPE mechanism;
382
40
    CK_NSS_KEM_PARAMETER_SET_TYPE paramSet;
383
384
40
    switch (groupDef->name) {
385
0
        case ssl_grp_kem_xyber768d00:
386
0
            mechanism = CKM_NSS_KYBER_KEY_PAIR_GEN;
387
0
            paramSet = CKP_NSS_KYBER_768_ROUND3;
388
0
            break;
389
40
        case ssl_grp_kem_mlkem768x25519:
390
40
            mechanism = CKM_NSS_ML_KEM_KEY_PAIR_GEN;
391
40
            paramSet = CKP_NSS_ML_KEM_768;
392
40
            break;
393
0
        default:
394
0
            PORT_Assert(0);
395
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
396
0
            return SECFailure;
397
40
    }
398
399
40
    PK11SlotInfo *slot = PK11_GetBestSlot(mechanism, ss->pkcs11PinArg);
400
40
    if (!slot) {
401
0
        goto loser;
402
0
    }
403
404
40
    privKey = PK11_GenerateKeyPairWithOpFlags(slot, mechanism,
405
40
                                              &paramSet, &pubKey, PK11_ATTR_SESSION | PK11_ATTR_INSENSITIVE | PK11_ATTR_PUBLIC,
406
40
                                              CKF_DERIVE, CKF_DERIVE, ss->pkcs11PinArg);
407
408
40
    if (!privKey) {
409
0
        privKey = PK11_GenerateKeyPairWithOpFlags(slot, mechanism,
410
0
                                                  &paramSet, &pubKey, PK11_ATTR_SESSION | PK11_ATTR_SENSITIVE | PK11_ATTR_PRIVATE,
411
0
                                                  CKF_DERIVE, CKF_DERIVE, ss->pkcs11PinArg);
412
0
    }
413
414
40
    PK11_FreeSlot(slot);
415
40
    if (!privKey || !pubKey) {
416
0
        goto loser;
417
0
    }
418
419
40
    keyPair = ssl_NewKeyPair(privKey, pubKey);
420
40
    if (!keyPair) {
421
0
        goto loser;
422
0
    }
423
424
40
    SSL_TRC(50, ("%d: SSL[%d]: Create Kyber ephemeral key %d",
425
40
                 SSL_GETPID(), ss ? ss->fd : NULL, groupDef->name));
426
40
    PRINT_BUF(50, (ss, "Public Key", pubKey->u.kyber.publicValue.data,
427
40
                   pubKey->u.kyber.publicValue.len));
428
40
#ifdef TRACE
429
40
    if (ssl_trace >= 50) {
430
0
        SECItem d = { siBuffer, NULL, 0 };
431
0
        SECStatus rv = PK11_ReadRawAttribute(PK11_TypePrivKey, privKey, CKA_VALUE, &d);
432
0
        if (rv == SECSuccess) {
433
0
            PRINT_BUF(50, (ss, "Private Key", d.data, d.len));
434
0
            SECITEM_FreeItem(&d, PR_FALSE);
435
0
        } else {
436
0
            SSL_TRC(50, ("Error extracting private key"));
437
0
        }
438
0
    }
439
40
#endif
440
441
40
    *outKeyPair = keyPair;
442
40
    return SECSuccess;
443
444
0
loser:
445
0
    SECKEY_DestroyPrivateKey(privKey);
446
0
    SECKEY_DestroyPublicKey(pubKey);
447
0
    ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
448
0
    return SECFailure;
449
40
}
450
451
SECStatus
452
tls13_CreateKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef,
453
                     sslEphemeralKeyPair **outKeyPair)
454
9.24k
{
455
9.24k
    SECStatus rv;
456
9.24k
    const ssl3DHParams *params;
457
9.24k
    sslEphemeralKeyPair *keyPair = NULL;
458
459
9.24k
    PORT_Assert(groupDef);
460
9.24k
    switch (groupDef->keaType) {
461
40
        case ssl_kea_ecdh_hybrid:
462
40
            if (groupDef->name != ssl_grp_kem_xyber768d00 && groupDef->name != ssl_grp_kem_mlkem768x25519) {
463
0
                PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
464
0
                return SECFailure;
465
0
            }
466
40
            const sslNamedGroupDef *x25519 = ssl_LookupNamedGroup(ssl_grp_ec_curve25519);
467
40
            sslEphemeralKeyPair *x25519Pair = ssl_LookupEphemeralKeyPair(ss, x25519);
468
40
            if (x25519Pair) {
469
0
                keyPair = ssl_CopyEphemeralKeyPair(x25519Pair);
470
0
            }
471
40
            if (!keyPair) {
472
40
                rv = ssl_CreateECDHEphemeralKeyPair(ss, x25519, &keyPair);
473
40
                if (rv != SECSuccess) {
474
0
                    return SECFailure;
475
0
                }
476
40
            }
477
40
            keyPair->group = groupDef;
478
40
            break;
479
8.07k
        case ssl_kea_ecdh:
480
8.07k
            if (groupDef->name == ssl_grp_ec_curve25519) {
481
7.97k
                sslEphemeralKeyPair *hybridPair = ssl_LookupEphemeralKeyPair(ss, ssl_LookupNamedGroup(ssl_grp_kem_mlkem768x25519));
482
7.97k
                if (!hybridPair) {
483
7.97k
                    hybridPair = ssl_LookupEphemeralKeyPair(ss, ssl_LookupNamedGroup(ssl_grp_kem_xyber768d00));
484
7.97k
                }
485
7.97k
                if (hybridPair) {
486
                    // We could use ssl_CopyEphemeralKeyPair here, but we would need to free
487
                    // the KEM components. We should pull this out into a utility function when
488
                    // we refactor to support multiple hybrid mechanisms.
489
0
                    keyPair = PORT_ZNew(sslEphemeralKeyPair);
490
0
                    if (!keyPair) {
491
0
                        return SECFailure;
492
0
                    }
493
0
                    PR_INIT_CLIST(&keyPair->link);
494
0
                    keyPair->group = groupDef;
495
0
                    keyPair->keys = ssl_GetKeyPairRef(hybridPair->keys);
496
0
                }
497
7.97k
            }
498
8.07k
            if (!keyPair) {
499
8.07k
                rv = ssl_CreateECDHEphemeralKeyPair(ss, groupDef, &keyPair);
500
8.07k
                if (rv != SECSuccess) {
501
0
                    return SECFailure;
502
0
                }
503
8.07k
            }
504
8.07k
            break;
505
8.07k
        case ssl_kea_dh:
506
1.13k
            params = ssl_GetDHEParams(groupDef);
507
1.13k
            PORT_Assert(params->name != ssl_grp_ffdhe_custom);
508
1.13k
            rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
509
1.13k
            if (rv != SECSuccess) {
510
0
                return SECFailure;
511
0
            }
512
1.13k
            break;
513
1.13k
        default:
514
0
            PORT_Assert(0);
515
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
516
0
            return SECFailure;
517
9.24k
    }
518
519
    // If we're creating an ECDH + KEM hybrid share and we're the client, then
520
    // we still need to generate the KEM key pair. Otherwise we're done.
521
9.24k
    if (groupDef->keaType == ssl_kea_ecdh_hybrid && !ss->sec.isServer) {
522
40
        rv = tls13_CreateKEMKeyPair(ss, groupDef, &keyPair->kemKeys);
523
40
        if (rv != SECSuccess) {
524
0
            ssl_FreeEphemeralKeyPair(keyPair);
525
0
            return SECFailure;
526
0
        }
527
40
    }
528
529
9.24k
    *outKeyPair = keyPair;
530
9.24k
    return SECSuccess;
531
9.24k
}
532
533
SECStatus
534
tls13_AddKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef)
535
9.24k
{
536
9.24k
    sslEphemeralKeyPair *keyPair = NULL;
537
9.24k
    SECStatus rv;
538
539
9.24k
    rv = tls13_CreateKeyShare(ss, groupDef, &keyPair);
540
9.24k
    if (rv != SECSuccess) {
541
0
        return SECFailure;
542
0
    }
543
9.24k
    PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs);
544
9.24k
    return SECSuccess;
545
9.24k
}
546
547
SECStatus
548
SSL_SendAdditionalKeyShares(PRFileDesc *fd, unsigned int count)
549
0
{
550
0
    sslSocket *ss = ssl_FindSocket(fd);
551
0
    if (!ss) {
552
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
553
0
        return SECFailure;
554
0
    }
555
556
0
    ss->additionalShares = count;
557
0
    return SECSuccess;
558
0
}
559
560
/*
561
 * Generate shares for ECDHE and FFDHE.  This picks the first enabled group of
562
 * the requisite type and creates a share for that.
563
 *
564
 * Called from ssl3_SendClientHello.
565
 */
566
SECStatus
567
tls13_SetupClientHello(sslSocket *ss, sslClientHelloType chType)
568
9.52k
{
569
9.52k
    unsigned int i;
570
9.52k
    SSL3Statistics *ssl3stats = SSL_GetStatistics();
571
9.52k
    NewSessionTicket *session_ticket = NULL;
572
9.52k
    sslSessionID *sid = ss->sec.ci.sid;
573
9.52k
    unsigned int numShares = 0;
574
9.52k
    SECStatus rv;
575
576
9.52k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
577
9.52k
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
578
579
9.52k
    rv = tls13_ClientSetupEch(ss, chType);
580
9.52k
    if (rv != SECSuccess) {
581
0
        return SECFailure;
582
0
    }
583
584
    /* Everything below here is only run on the first CH. */
585
9.52k
    if (chType != client_hello_initial) {
586
1.55k
        return SECSuccess;
587
1.55k
    }
588
589
7.97k
    rv = tls13_ClientGreaseSetup(ss);
590
7.97k
    if (rv != SECSuccess) {
591
0
        return SECFailure;
592
0
    }
593
594
    /* Select the first enabled group.
595
     * TODO(ekr@rtfm.com): be smarter about offering the group
596
     * that the other side negotiated if we are resuming. */
597
7.97k
    PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
598
7.97k
    for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
599
7.97k
        if (!ss->namedGroupPreferences[i]) {
600
0
            continue;
601
0
        }
602
7.97k
        rv = tls13_AddKeyShare(ss, ss->namedGroupPreferences[i]);
603
7.97k
        if (rv != SECSuccess) {
604
0
            return SECFailure;
605
0
        }
606
7.97k
        if (++numShares > ss->additionalShares) {
607
7.97k
            break;
608
7.97k
        }
609
7.97k
    }
610
611
7.97k
    if (PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs)) {
612
0
        PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
613
0
        return SECFailure;
614
0
    }
615
616
    /* Try to do stateless resumption, if we can. */
617
7.97k
    if (sid->cached != never_cached &&
618
7.97k
        sid->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
619
        /* The caller must be holding sid->u.ssl3.lock for reading. */
620
0
        session_ticket = &sid->u.ssl3.locked.sessionTicket;
621
0
        PORT_Assert(session_ticket && session_ticket->ticket.data);
622
623
0
        if (ssl_TicketTimeValid(ss, session_ticket)) {
624
0
            ss->statelessResume = PR_TRUE;
625
0
        }
626
627
0
        if (ss->statelessResume) {
628
0
            PORT_Assert(ss->sec.ci.sid);
629
0
            rv = tls13_RecoverWrappedSharedSecret(ss, ss->sec.ci.sid);
630
0
            if (rv != SECSuccess) {
631
0
                FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
632
0
                SSL_AtomicIncrementLong(&ssl3stats->sch_sid_cache_not_ok);
633
0
                ssl_UncacheSessionID(ss);
634
0
                ssl_FreeSID(ss->sec.ci.sid);
635
0
                ss->sec.ci.sid = NULL;
636
0
                return SECFailure;
637
0
            }
638
639
0
            ss->ssl3.hs.cipher_suite = ss->sec.ci.sid->u.ssl3.cipherSuite;
640
0
            rv = ssl3_SetupCipherSuite(ss, PR_FALSE);
641
0
            if (rv != SECSuccess) {
642
0
                FATAL_ERROR(ss, PORT_GetError(), internal_error);
643
0
                return SECFailure;
644
0
            }
645
0
            PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
646
0
        }
647
0
    }
648
649
    /* Derive the binder keys if any PSKs. */
650
7.97k
    if (!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)) {
651
        /* If an External PSK specified a suite, use that. */
652
3.99k
        sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
653
3.99k
        if (!ss->statelessResume &&
654
3.99k
            psk->type == ssl_psk_external &&
655
3.99k
            psk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL) {
656
0
            ss->ssl3.hs.cipher_suite = psk->zeroRttSuite;
657
0
        }
658
659
3.99k
        rv = tls13_ComputeEarlySecretsWithPsk(ss);
660
3.99k
        if (rv != SECSuccess) {
661
0
            FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
662
0
            return SECFailure;
663
0
        }
664
3.99k
    }
665
666
7.97k
    return SECSuccess;
667
7.97k
}
668
669
static SECStatus
670
tls13_ImportDHEKeyShare(SECKEYPublicKey *peerKey,
671
                        PRUint8 *b, PRUint32 length,
672
                        SECKEYPublicKey *pubKey)
673
949
{
674
949
    SECStatus rv;
675
949
    SECItem publicValue = { siBuffer, NULL, 0 };
676
677
949
    publicValue.data = b;
678
949
    publicValue.len = length;
679
949
    if (!ssl_IsValidDHEShare(&pubKey->u.dh.prime, &publicValue)) {
680
9
        PORT_SetError(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE);
681
9
        return SECFailure;
682
9
    }
683
684
940
    peerKey->keyType = dhKey;
685
940
    rv = SECITEM_CopyItem(peerKey->arena, &peerKey->u.dh.prime,
686
940
                          &pubKey->u.dh.prime);
687
940
    if (rv != SECSuccess)
688
0
        return SECFailure;
689
940
    rv = SECITEM_CopyItem(peerKey->arena, &peerKey->u.dh.base,
690
940
                          &pubKey->u.dh.base);
691
940
    if (rv != SECSuccess)
692
0
        return SECFailure;
693
940
    rv = SECITEM_CopyItem(peerKey->arena, &peerKey->u.dh.publicValue,
694
940
                          &publicValue);
695
940
    if (rv != SECSuccess)
696
0
        return SECFailure;
697
698
940
    return SECSuccess;
699
940
}
700
701
static SECStatus
702
tls13_ImportKEMKeyShare(SECKEYPublicKey *peerKey, TLS13KeyShareEntry *entry)
703
0
{
704
0
    SECItem pk = { siBuffer, NULL, 0 };
705
0
    SECStatus rv;
706
0
    size_t expected_len;
707
708
0
    switch (entry->group->name) {
709
0
        case ssl_grp_kem_xyber768d00:
710
0
            expected_len = X25519_PUBLIC_KEY_BYTES + KYBER768_PUBLIC_KEY_BYTES;
711
0
            break;
712
0
        case ssl_grp_kem_mlkem768x25519:
713
0
            expected_len = X25519_PUBLIC_KEY_BYTES + KYBER768_PUBLIC_KEY_BYTES;
714
0
            break;
715
0
        default:
716
0
            PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
717
0
            return SECFailure;
718
0
    }
719
720
0
    if (entry->key_exchange.len != expected_len) {
721
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_HYBRID_KEY_SHARE);
722
0
        return SECFailure;
723
0
    }
724
725
0
    switch (entry->group->name) {
726
0
        case ssl_grp_kem_xyber768d00:
727
0
            peerKey->keyType = kyberKey;
728
0
            peerKey->u.kyber.params = params_kyber768_round3;
729
            // key_exchange.data is `x25519 || kyber768`
730
0
            pk.data = entry->key_exchange.data + X25519_PUBLIC_KEY_BYTES;
731
0
            pk.len = KYBER768_PUBLIC_KEY_BYTES;
732
0
            break;
733
0
        case ssl_grp_kem_mlkem768x25519:
734
0
            peerKey->keyType = kyberKey;
735
0
            peerKey->u.kyber.params = params_ml_kem768;
736
            // key_exchange.data is `mlkem768 || x25519`
737
0
            pk.data = entry->key_exchange.data;
738
0
            pk.len = KYBER768_PUBLIC_KEY_BYTES;
739
0
            break;
740
0
        default:
741
0
            PORT_Assert(0);
742
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
743
0
            return SECFailure;
744
0
    }
745
746
0
    rv = SECITEM_CopyItem(peerKey->arena, &peerKey->u.kyber.publicValue, &pk);
747
0
    if (rv != SECSuccess) {
748
0
        PORT_SetError(SEC_ERROR_NO_MEMORY);
749
0
        return SECFailure;
750
0
    }
751
752
0
    return SECSuccess;
753
0
}
754
755
static SECStatus
756
tls13_HandleKEMCiphertext(sslSocket *ss, TLS13KeyShareEntry *entry, sslKeyPair *keyPair, PK11SymKey **outKey)
757
0
{
758
0
    SECItem ct = { siBuffer, NULL, 0 };
759
0
    SECStatus rv;
760
761
0
    switch (entry->group->name) {
762
0
        case ssl_grp_kem_xyber768d00:
763
0
            if (entry->key_exchange.len != X25519_PUBLIC_KEY_BYTES + KYBER768_CIPHERTEXT_BYTES) {
764
0
                ssl_MapLowLevelError(SSL_ERROR_RX_MALFORMED_HYBRID_KEY_SHARE);
765
0
                return SECFailure;
766
0
            }
767
0
            ct.data = entry->key_exchange.data + X25519_PUBLIC_KEY_BYTES;
768
0
            ct.len = KYBER768_CIPHERTEXT_BYTES;
769
0
            break;
770
0
        case ssl_grp_kem_mlkem768x25519:
771
0
            if (entry->key_exchange.len != X25519_PUBLIC_KEY_BYTES + KYBER768_CIPHERTEXT_BYTES) {
772
0
                ssl_MapLowLevelError(SSL_ERROR_RX_MALFORMED_HYBRID_KEY_SHARE);
773
0
                return SECFailure;
774
0
            }
775
0
            ct.data = entry->key_exchange.data;
776
0
            ct.len = KYBER768_CIPHERTEXT_BYTES;
777
0
            break;
778
0
        default:
779
0
            PORT_Assert(0);
780
0
            ssl_MapLowLevelError(SEC_ERROR_LIBRARY_FAILURE);
781
0
            return SECFailure;
782
0
    }
783
784
0
    rv = PK11_Decapsulate(keyPair->privKey, &ct, CKM_HKDF_DERIVE, PK11_ATTR_SESSION | PK11_ATTR_INSENSITIVE, CKF_DERIVE, outKey);
785
0
    if (rv != SECSuccess) {
786
0
        ssl_MapLowLevelError(SSL_ERROR_KEY_EXCHANGE_FAILURE);
787
0
    }
788
0
    return rv;
789
0
}
790
791
static SECStatus
792
tls13_HandleKEMKey(sslSocket *ss,
793
                   TLS13KeyShareEntry *entry,
794
                   PK11SymKey **key,
795
                   SECItem **ciphertext)
796
0
{
797
0
    PORTCheapArenaPool arena;
798
0
    SECKEYPublicKey *peerKey;
799
0
    CK_OBJECT_HANDLE handle;
800
0
    SECStatus rv;
801
802
0
    PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE);
803
0
    peerKey = PORT_ArenaZNew(&arena.arena, SECKEYPublicKey);
804
0
    if (peerKey == NULL) {
805
0
        goto loser;
806
0
    }
807
0
    peerKey->arena = &arena.arena;
808
0
    peerKey->pkcs11Slot = NULL;
809
0
    peerKey->pkcs11ID = CK_INVALID_HANDLE;
810
811
0
    rv = tls13_ImportKEMKeyShare(peerKey, entry);
812
0
    if (rv != SECSuccess) {
813
0
        goto loser;
814
0
    }
815
816
0
    PK11SlotInfo *slot = PK11_GetBestSlot(CKM_NSS_KYBER, ss->pkcs11PinArg);
817
0
    if (!slot) {
818
0
        goto loser;
819
0
    }
820
821
0
    handle = PK11_ImportPublicKey(slot, peerKey, PR_FALSE);
822
0
    PK11_FreeSlot(slot); /* peerKey holds a slot reference on success. */
823
0
    if (handle == CK_INVALID_HANDLE) {
824
0
        goto loser;
825
0
    }
826
827
0
    rv = PK11_Encapsulate(peerKey,
828
0
                          CKM_HKDF_DERIVE, PK11_ATTR_SESSION | PK11_ATTR_INSENSITIVE | PK11_ATTR_PUBLIC,
829
0
                          CKF_DERIVE, key, ciphertext);
830
831
    /* Destroy the imported public key */
832
0
    PORT_Assert(peerKey->pkcs11Slot);
833
0
    PK11_DestroyObject(peerKey->pkcs11Slot, peerKey->pkcs11ID);
834
0
    PK11_FreeSlot(peerKey->pkcs11Slot);
835
836
0
    PORT_DestroyCheapArena(&arena);
837
0
    return rv;
838
839
0
loser:
840
0
    PORT_DestroyCheapArena(&arena);
841
0
    return SECFailure;
842
0
}
843
844
SECStatus
845
tls13_HandleKeyShare(sslSocket *ss,
846
                     TLS13KeyShareEntry *entry,
847
                     sslKeyPair *keyPair,
848
                     SSLHashType hash,
849
                     PK11SymKey **out)
850
1.49k
{
851
1.49k
    PORTCheapArenaPool arena;
852
1.49k
    SECKEYPublicKey *peerKey;
853
1.49k
    CK_MECHANISM_TYPE mechanism;
854
1.49k
    PK11SymKey *key;
855
1.49k
    unsigned char *ec_data;
856
1.49k
    SECStatus rv;
857
1.49k
    int keySize = 0;
858
859
1.49k
    PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE);
860
1.49k
    peerKey = PORT_ArenaZNew(&arena.arena, SECKEYPublicKey);
861
1.49k
    if (peerKey == NULL) {
862
0
        goto loser;
863
0
    }
864
1.49k
    peerKey->arena = &arena.arena;
865
1.49k
    peerKey->pkcs11Slot = NULL;
866
1.49k
    peerKey->pkcs11ID = CK_INVALID_HANDLE;
867
868
1.49k
    switch (entry->group->keaType) {
869
0
        case ssl_kea_ecdh_hybrid:
870
0
            switch (entry->group->name) {
871
0
                case ssl_grp_kem_xyber768d00:
872
                    // x25519 share is at the beginning
873
0
                    ec_data = entry->key_exchange.len < X25519_PUBLIC_KEY_BYTES
874
0
                                  ? NULL
875
0
                                  : entry->key_exchange.data;
876
0
                    break;
877
0
                case ssl_grp_kem_mlkem768x25519:
878
                    // x25519 share is at the end
879
0
                    ec_data = entry->key_exchange.len < X25519_PUBLIC_KEY_BYTES
880
0
                                  ? NULL
881
0
                                  : entry->key_exchange.data + entry->key_exchange.len - X25519_PUBLIC_KEY_BYTES;
882
0
                    break;
883
0
                default:
884
0
                    ec_data = NULL;
885
0
                    break;
886
0
            }
887
0
            if (!ec_data) {
888
0
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HYBRID_KEY_SHARE);
889
0
                goto loser;
890
0
            }
891
0
            rv = ssl_ImportECDHKeyShare(peerKey,
892
0
                                        ec_data,
893
0
                                        X25519_PUBLIC_KEY_BYTES,
894
0
                                        ssl_LookupNamedGroup(ssl_grp_ec_curve25519));
895
0
            mechanism = CKM_ECDH1_DERIVE;
896
0
            break;
897
541
        case ssl_kea_ecdh:
898
541
            rv = ssl_ImportECDHKeyShare(peerKey,
899
541
                                        entry->key_exchange.data,
900
541
                                        entry->key_exchange.len,
901
541
                                        entry->group);
902
541
            mechanism = CKM_ECDH1_DERIVE;
903
541
            break;
904
949
        case ssl_kea_dh:
905
949
            rv = tls13_ImportDHEKeyShare(peerKey,
906
949
                                         entry->key_exchange.data,
907
949
                                         entry->key_exchange.len,
908
949
                                         keyPair->pubKey);
909
949
            mechanism = CKM_DH_PKCS_DERIVE;
910
949
            keySize = peerKey->u.dh.publicValue.len;
911
949
            break;
912
0
        default:
913
0
            PORT_Assert(0);
914
0
            goto loser;
915
1.49k
    }
916
1.49k
    if (rv != SECSuccess) {
917
10
        goto loser;
918
10
    }
919
920
1.48k
    key = PK11_PubDeriveWithKDF(
921
1.48k
        keyPair->privKey, peerKey, PR_FALSE, NULL, NULL, mechanism,
922
1.48k
        CKM_HKDF_DERIVE, CKA_DERIVE, keySize, CKD_NULL, NULL, NULL);
923
1.48k
    if (!key) {
924
46
        ssl_MapLowLevelError(SSL_ERROR_KEY_EXCHANGE_FAILURE);
925
46
        goto loser;
926
46
    }
927
928
1.43k
    *out = key;
929
1.43k
    PORT_DestroyCheapArena(&arena);
930
1.43k
    return SECSuccess;
931
932
56
loser:
933
56
    PORT_DestroyCheapArena(&arena);
934
56
    return SECFailure;
935
1.48k
}
936
937
static PRBool
938
tls13_UseServerSecret(sslSocket *ss, SSLSecretDirection direction)
939
1.60k
{
940
1.60k
    return ss->sec.isServer == (direction == ssl_secret_write);
941
1.60k
}
942
943
static PK11SymKey **
944
tls13_TrafficSecretRef(sslSocket *ss, SSLSecretDirection direction)
945
0
{
946
0
    if (tls13_UseServerSecret(ss, direction)) {
947
0
        return &ss->ssl3.hs.serverTrafficSecret;
948
0
    }
949
0
    return &ss->ssl3.hs.clientTrafficSecret;
950
0
}
951
952
SECStatus
953
tls13_UpdateTrafficKeys(sslSocket *ss, SSLSecretDirection direction)
954
0
{
955
0
    PK11SymKey **secret;
956
0
    PK11SymKey *updatedSecret;
957
0
    PRUint16 epoch;
958
0
    SECStatus rv;
959
960
0
    secret = tls13_TrafficSecretRef(ss, direction);
961
0
    rv = tls13_HkdfExpandLabel(*secret, tls13_GetHash(ss),
962
0
                               NULL, 0,
963
0
                               kHkdfLabelTrafficUpdate,
964
0
                               strlen(kHkdfLabelTrafficUpdate),
965
0
                               tls13_GetHmacMechanism(ss),
966
0
                               tls13_GetHashSize(ss),
967
0
                               ss->protocolVariant,
968
0
                               &updatedSecret);
969
0
    if (rv != SECSuccess) {
970
0
        return SECFailure;
971
0
    }
972
973
0
    PK11_FreeSymKey(*secret);
974
0
    *secret = updatedSecret;
975
976
0
    ssl_GetSpecReadLock(ss);
977
0
    if (direction == ssl_secret_read) {
978
0
        epoch = ss->ssl3.crSpec->epoch;
979
0
    } else {
980
0
        epoch = ss->ssl3.cwSpec->epoch;
981
0
    }
982
0
    ssl_ReleaseSpecReadLock(ss);
983
984
0
    if (epoch == PR_UINT16_MAX) {
985
        /* Good chance that this is an overflow from too many updates. */
986
0
        FATAL_ERROR(ss, SSL_ERROR_TOO_MANY_KEY_UPDATES, internal_error);
987
0
        return SECFailure;
988
0
    }
989
0
    ++epoch;
990
991
0
    if (ss->secretCallback) {
992
0
        ss->secretCallback(ss->fd, epoch, direction, updatedSecret,
993
0
                           ss->secretCallbackArg);
994
0
    }
995
0
    rv = tls13_SetCipherSpec(ss, epoch, direction, PR_FALSE);
996
0
    if (rv != SECSuccess) {
997
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
998
0
        return SECFailure;
999
0
    }
1000
0
    return SECSuccess;
1001
0
}
1002
1003
SECStatus
1004
tls13_SendKeyUpdate(sslSocket *ss, tls13KeyUpdateRequest request, PRBool buffer)
1005
0
{
1006
0
    SECStatus rv;
1007
1008
0
    SSL_TRC(3, ("%d: TLS13[%d]: %s send key update, response %s",
1009
0
                SSL_GETPID(), ss->fd, SSL_ROLE(ss),
1010
0
                (request == update_requested) ? "requested"
1011
0
                                              : "not requested"));
1012
1013
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1014
0
    PORT_Assert(!ss->sec.isServer || !ss->ssl3.clientCertRequested);
1015
1016
0
    if (!tls13_IsPostHandshake(ss)) {
1017
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1018
0
        return SECFailure;
1019
0
    }
1020
1021
0
    rv = TLS13_CHECK_HS_STATE(ss, SEC_ERROR_LIBRARY_FAILURE,
1022
0
                              idle_handshake);
1023
0
    if (rv != SECSuccess) {
1024
0
        return SECFailure;
1025
0
    }
1026
1027
0
    if (IS_DTLS(ss)) {
1028
0
        rv = dtls13_MaybeSendKeyUpdate(ss, request, buffer);
1029
0
        if (rv != SECSuccess) {
1030
            /* Error code set already. */
1031
0
            return SECFailure;
1032
0
        }
1033
0
        return rv;
1034
0
    }
1035
1036
0
    ssl_GetXmitBufLock(ss);
1037
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_key_update, 1);
1038
0
    if (rv != SECSuccess) {
1039
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
1040
0
        goto loser;
1041
0
    }
1042
0
    rv = ssl3_AppendHandshakeNumber(ss, request, 1);
1043
0
    if (rv != SECSuccess) {
1044
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
1045
0
        goto loser;
1046
0
    }
1047
1048
    /* If we have been asked to buffer, then do so.  This allows us to coalesce
1049
     * a KeyUpdate with a pending write. */
1050
0
    rv = ssl3_FlushHandshake(ss, buffer ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
1051
0
    if (rv != SECSuccess) {
1052
0
        goto loser; /* error code set by ssl3_FlushHandshake */
1053
0
    }
1054
0
    ssl_ReleaseXmitBufLock(ss);
1055
1056
0
    rv = tls13_UpdateTrafficKeys(ss, ssl_secret_write);
1057
0
    if (rv != SECSuccess) {
1058
0
        goto loser; /* error code set by tls13_UpdateTrafficKeys */
1059
0
    }
1060
1061
0
    return SECSuccess;
1062
1063
0
loser:
1064
0
    ssl_ReleaseXmitBufLock(ss);
1065
0
    return SECFailure;
1066
0
}
1067
1068
SECStatus
1069
SSLExp_KeyUpdate(PRFileDesc *fd, PRBool requestUpdate)
1070
0
{
1071
0
    SECStatus rv;
1072
0
    sslSocket *ss = ssl_FindSocket(fd);
1073
0
    if (!ss) {
1074
0
        return SECFailure;
1075
0
    }
1076
1077
0
    if (!tls13_IsPostHandshake(ss)) {
1078
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1079
0
        return SECFailure;
1080
0
    }
1081
1082
0
    if (ss->ssl3.clientCertRequested) {
1083
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
1084
0
        return SECFailure;
1085
0
    }
1086
1087
0
    rv = TLS13_CHECK_HS_STATE(ss, SEC_ERROR_INVALID_ARGS,
1088
0
                              idle_handshake);
1089
0
    if (rv != SECSuccess) {
1090
0
        return SECFailure;
1091
0
    }
1092
1093
0
    ssl_GetSSL3HandshakeLock(ss);
1094
0
    rv = tls13_SendKeyUpdate(ss, requestUpdate ? update_requested : update_not_requested,
1095
0
                             PR_FALSE /* don't buffer */);
1096
1097
    /* Remember that we are the ones that initiated this KeyUpdate. */
1098
0
    if (rv == SECSuccess) {
1099
0
        ss->ssl3.peerRequestedKeyUpdate = PR_FALSE;
1100
0
    }
1101
0
    ssl_ReleaseSSL3HandshakeLock(ss);
1102
0
    return rv;
1103
0
}
1104
1105
SECStatus
1106
SSLExp_SetCertificateCompressionAlgorithm(PRFileDesc *fd, SSLCertificateCompressionAlgorithm alg)
1107
4.57k
{
1108
4.57k
    sslSocket *ss = ssl_FindSocket(fd);
1109
4.57k
    if (!ss) {
1110
0
        return SECFailure; /* Code already set. */
1111
0
    }
1112
1113
4.57k
    ssl_GetSSL3HandshakeLock(ss);
1114
4.57k
    if (ss->ssl3.supportedCertCompressionAlgorithmsCount == MAX_SUPPORTED_CERTIFICATE_COMPRESSION_ALGS) {
1115
0
        goto loser;
1116
0
    }
1117
1118
    /* Reserved ID */
1119
4.57k
    if (alg.id == 0) {
1120
0
        goto loser;
1121
0
    }
1122
1123
4.57k
    if (alg.encode == NULL && alg.decode == NULL) {
1124
0
        goto loser;
1125
0
    }
1126
1127
    /* Checking that we have not yet registed an algorithm with the same ID. */
1128
4.57k
    for (int i = 0; i < ss->ssl3.supportedCertCompressionAlgorithmsCount; i++) {
1129
0
        if (ss->ssl3.supportedCertCompressionAlgorithms[i].id == alg.id) {
1130
0
            goto loser;
1131
0
        }
1132
0
    }
1133
1134
4.57k
    PORT_Memcpy(&ss->ssl3.supportedCertCompressionAlgorithms
1135
4.57k
                     [ss->ssl3.supportedCertCompressionAlgorithmsCount],
1136
4.57k
                &alg, sizeof(alg));
1137
4.57k
    ss->ssl3.supportedCertCompressionAlgorithmsCount += 1;
1138
4.57k
    ssl_ReleaseSSL3HandshakeLock(ss);
1139
4.57k
    return SECSuccess;
1140
1141
0
loser:
1142
0
    PORT_SetError(SEC_ERROR_INVALID_ARGS);
1143
0
    ssl_ReleaseSSL3HandshakeLock(ss);
1144
0
    return SECFailure;
1145
4.57k
}
1146
1147
/*
1148
 * enum {
1149
 *     update_not_requested(0), update_requested(1), (255)
1150
 * } KeyUpdateRequest;
1151
 *
1152
 * struct {
1153
 *     KeyUpdateRequest request_update;
1154
 * } KeyUpdate;
1155
 */
1156
1157
/* If we're handing the DTLS1.3 message, we silently fail if there is a parsing problem. */
1158
static SECStatus
1159
tls13_HandleKeyUpdate(sslSocket *ss, PRUint8 *b, unsigned int length)
1160
2
{
1161
2
    SECStatus rv;
1162
2
    PRUint32 update;
1163
1164
2
    SSL_TRC(3, ("%d: TLS13[%d]: %s handle key update",
1165
2
                SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
1166
1167
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
1168
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1169
1170
2
    if (!tls13_IsPostHandshake(ss)) {
1171
2
        FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE, unexpected_message);
1172
2
        return SECFailure;
1173
2
    }
1174
1175
0
    rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE,
1176
0
                              idle_handshake);
1177
0
    if (rv != SECSuccess) {
1178
        /* We should never be idle_handshake prior to firstHsDone. */
1179
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
1180
0
        return SECFailure;
1181
0
    }
1182
1183
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &update, 1, &b, &length);
1184
0
    if (rv != SECSuccess) {
1185
0
        return SECFailure; /* Error code set already. */
1186
0
    }
1187
0
    if (length != 0) {
1188
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_UPDATE, decode_error);
1189
0
        return SECFailure;
1190
0
    }
1191
0
    if (!(update == update_requested ||
1192
0
          update == update_not_requested)) {
1193
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_UPDATE, decode_error);
1194
0
        return SECFailure;
1195
0
    }
1196
1197
0
    if (IS_DTLS(ss)) {
1198
0
        return dtls13_HandleKeyUpdate(ss, b, length, update);
1199
0
    }
1200
1201
0
    rv = tls13_UpdateTrafficKeys(ss, ssl_secret_read);
1202
0
    if (rv != SECSuccess) {
1203
0
        return SECFailure; /* Error code set by tls13_UpdateTrafficKeys. */
1204
0
    }
1205
1206
0
    if (update == update_requested) {
1207
0
        PRBool sendUpdate;
1208
0
        if (ss->ssl3.clientCertRequested) {
1209
            /* Post-handshake auth is in progress; defer sending a key update. */
1210
0
            ss->ssl3.hs.keyUpdateDeferred = PR_TRUE;
1211
0
            ss->ssl3.hs.deferredKeyUpdateRequest = update_not_requested;
1212
0
            sendUpdate = PR_FALSE;
1213
0
        } else if (ss->ssl3.peerRequestedKeyUpdate) {
1214
            /* Only send an update if we have sent with the current spec.  This
1215
             * prevents us from being forced to crank forward pointlessly. */
1216
0
            ssl_GetSpecReadLock(ss);
1217
0
            sendUpdate = ss->ssl3.cwSpec->nextSeqNum > 0;
1218
0
            ssl_ReleaseSpecReadLock(ss);
1219
0
        } else {
1220
0
            sendUpdate = PR_TRUE;
1221
0
        }
1222
0
        if (sendUpdate) {
1223
            /* Respond immediately (don't buffer). */
1224
0
            rv = tls13_SendKeyUpdate(ss, update_not_requested, PR_FALSE);
1225
0
            if (rv != SECSuccess) {
1226
0
                return SECFailure; /* Error already set. */
1227
0
            }
1228
0
        }
1229
0
        ss->ssl3.peerRequestedKeyUpdate = PR_TRUE;
1230
0
    }
1231
1232
0
    return SECSuccess;
1233
0
}
1234
1235
SECStatus
1236
SSLExp_SendCertificateRequest(PRFileDesc *fd)
1237
0
{
1238
0
    SECStatus rv;
1239
0
    sslSocket *ss = ssl_FindSocket(fd);
1240
0
    if (!ss) {
1241
0
        return SECFailure;
1242
0
    }
1243
1244
    /* Not supported. */
1245
0
    if (IS_DTLS(ss)) {
1246
0
        PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION);
1247
0
        return SECFailure;
1248
0
    }
1249
1250
0
    if (!tls13_IsPostHandshake(ss)) {
1251
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1252
0
        return SECFailure;
1253
0
    }
1254
1255
0
    if (ss->ssl3.clientCertRequested) {
1256
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
1257
0
        return SECFailure;
1258
0
    }
1259
1260
    /* Disallow a CertificateRequest if this connection uses an external PSK. */
1261
0
    if (ss->sec.authType == ssl_auth_psk) {
1262
0
        PORT_SetError(SSL_ERROR_FEATURE_DISABLED);
1263
0
        return SECFailure;
1264
0
    }
1265
1266
0
    rv = TLS13_CHECK_HS_STATE(ss, SEC_ERROR_INVALID_ARGS,
1267
0
                              idle_handshake);
1268
0
    if (rv != SECSuccess) {
1269
0
        return SECFailure;
1270
0
    }
1271
1272
0
    if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_post_handshake_auth_xtn)) {
1273
0
        PORT_SetError(SSL_ERROR_MISSING_POST_HANDSHAKE_AUTH_EXTENSION);
1274
0
        return SECFailure;
1275
0
    }
1276
1277
0
    ssl_GetSSL3HandshakeLock(ss);
1278
1279
0
    rv = tls13_SendCertificateRequest(ss);
1280
0
    if (rv == SECSuccess) {
1281
0
        ssl_GetXmitBufLock(ss);
1282
0
        rv = ssl3_FlushHandshake(ss, 0);
1283
0
        ssl_ReleaseXmitBufLock(ss);
1284
0
        ss->ssl3.clientCertRequested = PR_TRUE;
1285
0
    }
1286
1287
0
    ssl_ReleaseSSL3HandshakeLock(ss);
1288
0
    return rv;
1289
0
}
1290
1291
SECStatus
1292
tls13_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b, PRUint32 length)
1293
17
{
1294
17
    if (ss->sec.isServer && ss->ssl3.hs.zeroRttIgnore != ssl_0rtt_ignore_none) {
1295
0
        SSL_TRC(3, ("%d: TLS13[%d]: successfully decrypted handshake after "
1296
0
                    "failed 0-RTT",
1297
0
                    SSL_GETPID(), ss->fd));
1298
0
        ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_none;
1299
0
    }
1300
1301
    /* TODO(ekr@rtfm.com): Would it be better to check all the states here? */
1302
17
    switch (ss->ssl3.hs.msg_type) {
1303
2
        case ssl_hs_certificate:
1304
2
            return tls13_HandleCertificate(ss, b, length, PR_FALSE);
1305
2
        case ssl_hs_compressed_certificate:
1306
2
            return tls13_HandleCertificateDecode(ss, b, length);
1307
2
        case ssl_hs_certificate_request:
1308
2
            return tls13_HandleCertificateRequest(ss, b, length);
1309
1310
2
        case ssl_hs_certificate_verify:
1311
2
            return tls13_HandleCertificateVerify(ss, b, length);
1312
1313
2
        case ssl_hs_encrypted_extensions:
1314
2
            return tls13_HandleEncryptedExtensions(ss, b, length);
1315
1316
1
        case ssl_hs_new_session_ticket:
1317
1
            return tls13_HandleNewSessionTicket(ss, b, length);
1318
1319
2
        case ssl_hs_finished:
1320
2
            if (ss->sec.isServer) {
1321
0
                return tls13_ServerHandleFinished(ss, b, length);
1322
2
            } else {
1323
2
                return tls13_ClientHandleFinished(ss, b, length);
1324
2
            }
1325
1326
1
        case ssl_hs_end_of_early_data:
1327
1
            return tls13_HandleEndOfEarlyData(ss, b, length);
1328
1329
2
        case ssl_hs_key_update:
1330
2
            return tls13_HandleKeyUpdate(ss, b, length);
1331
1332
1
        default:
1333
1
            FATAL_ERROR(ss, SSL_ERROR_RX_UNKNOWN_HANDSHAKE, unexpected_message);
1334
1
            return SECFailure;
1335
17
    }
1336
1337
0
    PORT_Assert(0); /* Unreached */
1338
0
    return SECFailure;
1339
17
}
1340
1341
static SECStatus
1342
tls13_RecoverWrappedSharedSecret(sslSocket *ss, sslSessionID *sid)
1343
0
{
1344
0
    PK11SymKey *wrapKey; /* wrapping key */
1345
0
    SECItem wrappedMS = { siBuffer, NULL, 0 };
1346
0
    SSLHashType hashType;
1347
1348
0
    SSL_TRC(3, ("%d: TLS13[%d]: recovering static secret (%s)",
1349
0
                SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
1350
1351
    /* Now find the hash used as the PRF for the previous handshake. */
1352
0
    hashType = tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite);
1353
1354
    /* If we are the server, we compute the wrapping key, but if we
1355
     * are the client, its coordinates are stored with the ticket. */
1356
0
    if (ss->sec.isServer) {
1357
0
        wrapKey = ssl3_GetWrappingKey(ss, NULL,
1358
0
                                      sid->u.ssl3.masterWrapMech,
1359
0
                                      ss->pkcs11PinArg);
1360
0
    } else {
1361
0
        PK11SlotInfo *slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
1362
0
                                               sid->u.ssl3.masterSlotID);
1363
0
        if (!slot)
1364
0
            return SECFailure;
1365
1366
0
        wrapKey = PK11_GetWrapKey(slot,
1367
0
                                  sid->u.ssl3.masterWrapIndex,
1368
0
                                  sid->u.ssl3.masterWrapMech,
1369
0
                                  sid->u.ssl3.masterWrapSeries,
1370
0
                                  ss->pkcs11PinArg);
1371
0
        PK11_FreeSlot(slot);
1372
0
    }
1373
0
    if (!wrapKey) {
1374
0
        return SECFailure;
1375
0
    }
1376
1377
0
    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
1378
0
    wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
1379
1380
0
    PK11SymKey *unwrappedPsk = ssl_unwrapSymKey(wrapKey, sid->u.ssl3.masterWrapMech,
1381
0
                                                NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
1382
0
                                                CKA_DERIVE, tls13_GetHashSizeForHash(hashType),
1383
0
                                                CKF_SIGN | CKF_VERIFY, ss->pkcs11PinArg);
1384
0
    PK11_FreeSymKey(wrapKey);
1385
0
    if (!unwrappedPsk) {
1386
0
        return SECFailure;
1387
0
    }
1388
0
    sslPsk *rpsk = tls13_MakePsk(unwrappedPsk, ssl_psk_resume, hashType, NULL);
1389
0
    if (!rpsk) {
1390
0
        PK11_FreeSymKey(unwrappedPsk);
1391
0
        return SECFailure;
1392
0
    }
1393
0
    if (sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data) {
1394
0
        rpsk->maxEarlyData = sid->u.ssl3.locked.sessionTicket.max_early_data_size;
1395
0
        rpsk->zeroRttSuite = sid->u.ssl3.cipherSuite;
1396
0
    }
1397
0
    PRINT_KEY(50, (ss, "Recovered RMS", rpsk->key));
1398
0
    PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) ||
1399
0
                ((sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks))->type != ssl_psk_resume);
1400
1401
0
    if (ss->sec.isServer) {
1402
        /* In server, we couldn't select the RPSK in the extension handler
1403
         * since it was not unwrapped yet. We're committed now, so select
1404
         * it and add it to the list (to ensure it is freed). */
1405
0
        ss->xtnData.selectedPsk = rpsk;
1406
0
    }
1407
0
    PR_APPEND_LINK(&rpsk->link, &ss->ssl3.hs.psks);
1408
1409
0
    return SECSuccess;
1410
0
}
1411
1412
/* Key Derivation Functions.
1413
 *
1414
 *                 0
1415
 *                 |
1416
 *                 v
1417
 *   PSK ->  HKDF-Extract = Early Secret
1418
 *                 |
1419
 *                 +-----> Derive-Secret(., "ext binder" | "res binder", "")
1420
 *                 |                     = binder_key
1421
 *                 |
1422
 *                 +-----> Derive-Secret(., "c e traffic",
1423
 *                 |                     ClientHello)
1424
 *                 |                     = client_early_traffic_secret
1425
 *                 |
1426
 *                 +-----> Derive-Secret(., "e exp master",
1427
 *                 |                     ClientHello)
1428
 *                 |                     = early_exporter_secret
1429
 *                 v
1430
 *           Derive-Secret(., "derived", "")
1431
 *                 |
1432
 *                 v
1433
 *(EC)DHE -> HKDF-Extract = Handshake Secret
1434
 *                 |
1435
 *                 +-----> Derive-Secret(., "c hs traffic",
1436
 *                 |                     ClientHello...ServerHello)
1437
 *                 |                     = client_handshake_traffic_secret
1438
 *                 |
1439
 *                 +-----> Derive-Secret(., "s hs traffic",
1440
 *                 |                     ClientHello...ServerHello)
1441
 *                 |                     = server_handshake_traffic_secret
1442
 *                 v
1443
 *           Derive-Secret(., "derived", "")
1444
 *                 |
1445
 *                 v
1446
 *      0 -> HKDF-Extract = Master Secret
1447
 *                 |
1448
 *                 +-----> Derive-Secret(., "c ap traffic",
1449
 *                 |                     ClientHello...Server Finished)
1450
 *                 |                     = client_traffic_secret_0
1451
 *                 |
1452
 *                 +-----> Derive-Secret(., "s ap traffic",
1453
 *                 |                     ClientHello...Server Finished)
1454
 *                 |                     = server_traffic_secret_0
1455
 *                 |
1456
 *                 +-----> Derive-Secret(., "exp master",
1457
 *                 |                     ClientHello...Server Finished)
1458
 *                 |                     = exporter_secret
1459
 *                 |
1460
 *                 +-----> Derive-Secret(., "res master",
1461
 *                                       ClientHello...Client Finished)
1462
 *                                       = resumption_master_secret
1463
 *
1464
 */
1465
static SECStatus
1466
tls13_ComputeEarlySecretsWithPsk(sslSocket *ss)
1467
3.99k
{
1468
3.99k
    SECStatus rv;
1469
1470
3.99k
    SSL_TRC(5, ("%d: TLS13[%d]: compute early secrets (%s)",
1471
3.99k
                SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
1472
1473
3.99k
    PORT_Assert(!ss->ssl3.hs.currentSecret);
1474
3.99k
    sslPsk *psk = NULL;
1475
1476
3.99k
    if (ss->sec.isServer) {
1477
0
        psk = ss->xtnData.selectedPsk;
1478
3.99k
    } else {
1479
        /* Client to use the first PSK for early secrets. */
1480
3.99k
        PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
1481
3.99k
        psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
1482
3.99k
    }
1483
3.99k
    PORT_Assert(psk && psk->key);
1484
3.99k
    PORT_Assert(psk->hash != ssl_hash_none);
1485
1486
3.99k
    PK11SymKey *earlySecret = NULL;
1487
3.99k
    rv = tls13_HkdfExtract(NULL, psk->key, psk->hash, &earlySecret);
1488
3.99k
    if (rv != SECSuccess) {
1489
0
        return SECFailure;
1490
0
    }
1491
1492
    /* No longer need the raw input key */
1493
3.99k
    PK11_FreeSymKey(psk->key);
1494
3.99k
    psk->key = NULL;
1495
3.99k
    const char *label = (psk->type == ssl_psk_resume) ? kHkdfLabelResPskBinderKey : kHkdfLabelExtPskBinderKey;
1496
3.99k
    rv = tls13_DeriveSecretNullHash(ss, earlySecret,
1497
3.99k
                                    label, strlen(label),
1498
3.99k
                                    &psk->binderKey, psk->hash);
1499
3.99k
    if (rv != SECSuccess) {
1500
0
        PK11_FreeSymKey(earlySecret);
1501
0
        return SECFailure;
1502
0
    }
1503
3.99k
    ss->ssl3.hs.currentSecret = earlySecret;
1504
1505
3.99k
    return SECSuccess;
1506
3.99k
}
1507
1508
/* This derives the early traffic and early exporter secrets. */
1509
static SECStatus
1510
tls13_DeriveEarlySecrets(sslSocket *ss)
1511
0
{
1512
0
    SECStatus rv;
1513
0
    PORT_Assert(ss->ssl3.hs.currentSecret);
1514
0
    rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1515
0
                                kHkdfLabelClient,
1516
0
                                kHkdfLabelEarlyTrafficSecret,
1517
0
                                keylogLabelClientEarlyTrafficSecret,
1518
0
                                &ss->ssl3.hs.clientEarlyTrafficSecret);
1519
0
    if (rv != SECSuccess) {
1520
0
        return SECFailure;
1521
0
    }
1522
1523
0
    if (ss->secretCallback) {
1524
0
        ss->secretCallback(ss->fd, (PRUint16)TrafficKeyEarlyApplicationData,
1525
0
                           ss->sec.isServer ? ssl_secret_read : ssl_secret_write,
1526
0
                           ss->ssl3.hs.clientEarlyTrafficSecret,
1527
0
                           ss->secretCallbackArg);
1528
0
    }
1529
1530
0
    rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1531
0
                                NULL, kHkdfLabelEarlyExporterSecret,
1532
0
                                keylogLabelEarlyExporterSecret,
1533
0
                                &ss->ssl3.hs.earlyExporterSecret);
1534
0
    if (rv != SECSuccess) {
1535
0
        return SECFailure;
1536
0
    }
1537
1538
0
    return SECSuccess;
1539
0
}
1540
1541
static SECStatus
1542
tls13_ComputeHandshakeSecret(sslSocket *ss)
1543
1.43k
{
1544
1.43k
    SECStatus rv;
1545
1.43k
    PK11SymKey *derivedSecret = NULL;
1546
1.43k
    PK11SymKey *newSecret = NULL;
1547
1.43k
    SSL_TRC(5, ("%d: TLS13[%d]: compute handshake secret (%s)",
1548
1.43k
                SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
1549
1550
    /* If no PSK, generate the default early secret. */
1551
1.43k
    if (!ss->ssl3.hs.currentSecret) {
1552
1.42k
        PORT_Assert(!ss->xtnData.selectedPsk);
1553
1.42k
        rv = tls13_HkdfExtract(NULL, NULL,
1554
1.42k
                               tls13_GetHash(ss), &ss->ssl3.hs.currentSecret);
1555
1.42k
        if (rv != SECSuccess) {
1556
0
            return SECFailure;
1557
0
        }
1558
1.42k
    }
1559
1.43k
    PORT_Assert(ss->ssl3.hs.currentSecret);
1560
1.43k
    PORT_Assert(ss->ssl3.hs.dheSecret);
1561
1562
    /* Derive-Secret(., "derived", "") */
1563
1.43k
    rv = tls13_DeriveSecretNullHash(ss, ss->ssl3.hs.currentSecret,
1564
1.43k
                                    kHkdfLabelDerivedSecret,
1565
1.43k
                                    strlen(kHkdfLabelDerivedSecret),
1566
1.43k
                                    &derivedSecret, tls13_GetHash(ss));
1567
1.43k
    if (rv != SECSuccess) {
1568
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
1569
0
        return rv;
1570
0
    }
1571
1572
    /* HKDF-Extract(ECDHE, .) = Handshake Secret */
1573
1.43k
    rv = tls13_HkdfExtract(derivedSecret, ss->ssl3.hs.dheSecret,
1574
1.43k
                           tls13_GetHash(ss), &newSecret);
1575
1.43k
    PK11_FreeSymKey(derivedSecret);
1576
1.43k
    if (rv != SECSuccess) {
1577
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
1578
0
        return rv;
1579
0
    }
1580
1581
1.43k
    PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
1582
1.43k
    ss->ssl3.hs.currentSecret = newSecret;
1583
1.43k
    return SECSuccess;
1584
1.43k
}
1585
1586
static SECStatus
1587
tls13_ComputeHandshakeSecrets(sslSocket *ss)
1588
1.43k
{
1589
1.43k
    SECStatus rv;
1590
1.43k
    PK11SymKey *derivedSecret = NULL;
1591
1.43k
    PK11SymKey *newSecret = NULL;
1592
1593
1.43k
    PK11_FreeSymKey(ss->ssl3.hs.dheSecret);
1594
1.43k
    ss->ssl3.hs.dheSecret = NULL;
1595
1596
1.43k
    SSL_TRC(5, ("%d: TLS13[%d]: compute handshake secrets (%s)",
1597
1.43k
                SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
1598
1599
    /* Now compute |*HsTrafficSecret| */
1600
1.43k
    rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1601
1.43k
                                kHkdfLabelClient,
1602
1.43k
                                kHkdfLabelHandshakeTrafficSecret,
1603
1.43k
                                keylogLabelClientHsTrafficSecret,
1604
1.43k
                                &ss->ssl3.hs.clientHsTrafficSecret);
1605
1.43k
    if (rv != SECSuccess) {
1606
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
1607
0
        return rv;
1608
0
    }
1609
1.43k
    rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1610
1.43k
                                kHkdfLabelServer,
1611
1.43k
                                kHkdfLabelHandshakeTrafficSecret,
1612
1.43k
                                keylogLabelServerHsTrafficSecret,
1613
1.43k
                                &ss->ssl3.hs.serverHsTrafficSecret);
1614
1.43k
    if (rv != SECSuccess) {
1615
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
1616
0
        return rv;
1617
0
    }
1618
1619
1.43k
    if (ss->secretCallback) {
1620
0
        SSLSecretDirection dir =
1621
0
            ss->sec.isServer ? ssl_secret_read : ssl_secret_write;
1622
0
        ss->secretCallback(ss->fd, (PRUint16)TrafficKeyHandshake, dir,
1623
0
                           ss->ssl3.hs.clientHsTrafficSecret,
1624
0
                           ss->secretCallbackArg);
1625
0
        dir = ss->sec.isServer ? ssl_secret_write : ssl_secret_read;
1626
0
        ss->secretCallback(ss->fd, (PRUint16)TrafficKeyHandshake, dir,
1627
0
                           ss->ssl3.hs.serverHsTrafficSecret,
1628
0
                           ss->secretCallbackArg);
1629
0
    }
1630
1631
1.43k
    SSL_TRC(5, ("%d: TLS13[%d]: compute master secret (%s)",
1632
1.43k
                SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
1633
1634
    /* Crank HKDF forward to make master secret, which we
1635
     * stuff in current secret. */
1636
1.43k
    rv = tls13_DeriveSecretNullHash(ss, ss->ssl3.hs.currentSecret,
1637
1.43k
                                    kHkdfLabelDerivedSecret,
1638
1.43k
                                    strlen(kHkdfLabelDerivedSecret),
1639
1.43k
                                    &derivedSecret, tls13_GetHash(ss));
1640
1.43k
    if (rv != SECSuccess) {
1641
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
1642
0
        return rv;
1643
0
    }
1644
1.43k
    rv = tls13_HkdfExtract(derivedSecret,
1645
1.43k
                           NULL,
1646
1.43k
                           tls13_GetHash(ss),
1647
1.43k
                           &newSecret);
1648
1.43k
    PK11_FreeSymKey(derivedSecret);
1649
1.43k
    if (rv != SECSuccess) {
1650
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
1651
0
        return SECFailure;
1652
0
    }
1653
1.43k
    PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
1654
1.43k
    ss->ssl3.hs.currentSecret = newSecret;
1655
1656
1.43k
    return SECSuccess;
1657
1.43k
}
1658
1659
static SECStatus
1660
tls13_ComputeApplicationSecrets(sslSocket *ss)
1661
0
{
1662
0
    SECStatus rv;
1663
1664
0
    rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1665
0
                                kHkdfLabelClient,
1666
0
                                kHkdfLabelApplicationTrafficSecret,
1667
0
                                keylogLabelClientTrafficSecret,
1668
0
                                &ss->ssl3.hs.clientTrafficSecret);
1669
0
    if (rv != SECSuccess) {
1670
0
        return SECFailure;
1671
0
    }
1672
0
    rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1673
0
                                kHkdfLabelServer,
1674
0
                                kHkdfLabelApplicationTrafficSecret,
1675
0
                                keylogLabelServerTrafficSecret,
1676
0
                                &ss->ssl3.hs.serverTrafficSecret);
1677
0
    if (rv != SECSuccess) {
1678
0
        return SECFailure;
1679
0
    }
1680
1681
0
    if (ss->secretCallback) {
1682
0
        SSLSecretDirection dir =
1683
0
            ss->sec.isServer ? ssl_secret_read : ssl_secret_write;
1684
0
        ss->secretCallback(ss->fd, (PRUint16)TrafficKeyApplicationData,
1685
0
                           dir, ss->ssl3.hs.clientTrafficSecret,
1686
0
                           ss->secretCallbackArg);
1687
0
        dir = ss->sec.isServer ? ssl_secret_write : ssl_secret_read;
1688
0
        ss->secretCallback(ss->fd, (PRUint16)TrafficKeyApplicationData,
1689
0
                           dir, ss->ssl3.hs.serverTrafficSecret,
1690
0
                           ss->secretCallbackArg);
1691
0
    }
1692
1693
0
    rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1694
0
                                NULL, kHkdfLabelExporterMasterSecret,
1695
0
                                keylogLabelExporterSecret,
1696
0
                                &ss->ssl3.hs.exporterSecret);
1697
0
    if (rv != SECSuccess) {
1698
0
        return SECFailure;
1699
0
    }
1700
1701
0
    return SECSuccess;
1702
0
}
1703
1704
static SECStatus
1705
tls13_ComputeFinalSecrets(sslSocket *ss)
1706
0
{
1707
0
    SECStatus rv;
1708
1709
0
    PORT_Assert(!ss->ssl3.crSpec->masterSecret);
1710
0
    PORT_Assert(!ss->ssl3.cwSpec->masterSecret);
1711
0
    PORT_Assert(ss->ssl3.hs.currentSecret);
1712
0
    rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1713
0
                                NULL, kHkdfLabelResumptionMasterSecret,
1714
0
                                NULL,
1715
0
                                &ss->ssl3.hs.resumptionMasterSecret);
1716
0
    PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
1717
0
    ss->ssl3.hs.currentSecret = NULL;
1718
0
    if (rv != SECSuccess) {
1719
0
        return SECFailure;
1720
0
    }
1721
1722
0
    return SECSuccess;
1723
0
}
1724
1725
static void
1726
tls13_RestoreCipherInfo(sslSocket *ss, sslSessionID *sid)
1727
0
{
1728
    /* Set these to match the cached value.
1729
     * TODO(ekr@rtfm.com): Make a version with the "true" values.
1730
     * Bug 1256137.
1731
     */
1732
0
    ss->sec.authType = sid->authType;
1733
0
    ss->sec.authKeyBits = sid->authKeyBits;
1734
0
    ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
1735
0
    ss->sec.signatureScheme = sid->sigScheme;
1736
0
}
1737
1738
/* Check whether resumption-PSK is allowed. */
1739
static PRBool
1740
tls13_CanResume(sslSocket *ss, const sslSessionID *sid)
1741
0
{
1742
0
    const sslServerCert *sc;
1743
1744
0
    if (!sid) {
1745
0
        return PR_FALSE;
1746
0
    }
1747
1748
0
    if (sid->version != ss->version) {
1749
0
        return PR_FALSE;
1750
0
    }
1751
1752
#ifdef UNSAFE_FUZZER_MODE
1753
    /* When fuzzing, sid could contain garbage that will crash tls13_GetHashForCipherSuite.
1754
     * Do a direct comparison of cipher suites.  This makes us refuse to resume when the
1755
     * protocol allows it, but resumption is discretionary anyway. */
1756
    if (sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
1757
#else
1758
0
    if (tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite) != tls13_GetHashForCipherSuite(ss->ssl3.hs.cipher_suite)) {
1759
0
#endif
1760
0
        return PR_FALSE;
1761
0
    }
1762
1763
    /* Server sids don't remember the server cert we previously sent, but they
1764
     * do remember the type of certificate we originally used, so we can locate
1765
     * it again, provided that the current ssl socket has had its server certs
1766
     * configured the same as the previous one. */
1767
0
    sc = ssl_FindServerCert(ss, sid->authType, sid->namedCurve);
1768
0
    if (!sc || !sc->serverCert) {
1769
0
        return PR_FALSE;
1770
0
    }
1771
1772
0
    return PR_TRUE;
1773
0
}
1774
1775
static PRBool
1776
tls13_CanNegotiateZeroRtt(sslSocket *ss, const sslSessionID *sid)
1777
0
{
1778
0
    PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_sent);
1779
0
    sslPsk *psk = ss->xtnData.selectedPsk;
1780
1781
0
    if (!ss->opt.enable0RttData) {
1782
0
        return PR_FALSE;
1783
0
    }
1784
0
    if (!psk) {
1785
0
        return PR_FALSE;
1786
0
    }
1787
0
    if (psk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL) {
1788
0
        return PR_FALSE;
1789
0
    }
1790
0
    if (!psk->maxEarlyData) {
1791
0
        return PR_FALSE;
1792
0
    }
1793
0
    if (ss->ssl3.hs.cipher_suite != psk->zeroRttSuite) {
1794
0
        return PR_FALSE;
1795
0
    }
1796
0
    if (psk->type == ssl_psk_resume) {
1797
0
        if (!sid) {
1798
0
            return PR_FALSE;
1799
0
        }
1800
0
        PORT_Assert(sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data);
1801
0
        PORT_Assert(ss->statelessResume);
1802
0
        if (!ss->statelessResume) {
1803
0
            return PR_FALSE;
1804
0
        }
1805
0
        if (SECITEM_CompareItem(&ss->xtnData.nextProto,
1806
0
                                &sid->u.ssl3.alpnSelection) != 0) {
1807
0
            return PR_FALSE;
1808
0
        }
1809
0
    } else if (psk->type != ssl_psk_external) {
1810
0
        PORT_Assert(0);
1811
0
        return PR_FALSE;
1812
0
    }
1813
1814
0
    if (tls13_IsReplay(ss, sid)) {
1815
0
        return PR_FALSE;
1816
0
    }
1817
1818
0
    return PR_TRUE;
1819
0
}
1820
1821
/* Called from tls13_HandleClientHelloPart2 to update the state of 0-RTT handling.
1822
 *
1823
 * 0-RTT is only permitted if:
1824
 * 1. The early data extension was present.
1825
 * 2. We are resuming a session.
1826
 * 3. The 0-RTT option is set.
1827
 * 4. The ticket allowed 0-RTT.
1828
 * 5. We negotiated the same ALPN value as in the ticket.
1829
 */
1830
static void
1831
tls13_NegotiateZeroRtt(sslSocket *ss, const sslSessionID *sid)
1832
0
{
1833
0
    SSL_TRC(3, ("%d: TLS13[%d]: negotiate 0-RTT %p",
1834
0
                SSL_GETPID(), ss->fd, sid));
1835
1836
    /* tls13_ServerHandleEarlyDataXtn sets this to ssl_0rtt_sent, so this will
1837
     * be ssl_0rtt_none unless early_data is present. */
1838
0
    if (ss->ssl3.hs.zeroRttState == ssl_0rtt_none) {
1839
0
        return;
1840
0
    }
1841
1842
0
    if (ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored) {
1843
        /* HelloRetryRequest causes 0-RTT to be ignored. On the second
1844
         * ClientHello, reset the ignore state so that decryption failure is
1845
         * handled normally. */
1846
0
        if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr) {
1847
0
            PORT_Assert(ss->ssl3.hs.helloRetry);
1848
0
            ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
1849
0
            ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_none;
1850
0
        } else {
1851
0
            SSL_TRC(3, ("%d: TLS13[%d]: application ignored 0-RTT",
1852
0
                        SSL_GETPID(), ss->fd));
1853
0
        }
1854
0
        return;
1855
0
    }
1856
1857
0
    if (!tls13_CanNegotiateZeroRtt(ss, sid)) {
1858
0
        SSL_TRC(3, ("%d: TLS13[%d]: ignore 0-RTT", SSL_GETPID(), ss->fd));
1859
0
        ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
1860
0
        ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
1861
0
        return;
1862
0
    }
1863
1864
0
    SSL_TRC(3, ("%d: TLS13[%d]: enable 0-RTT", SSL_GETPID(), ss->fd));
1865
0
    PORT_Assert(ss->xtnData.selectedPsk);
1866
0
    ss->ssl3.hs.zeroRttState = ssl_0rtt_accepted;
1867
0
    ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_none;
1868
0
    ss->ssl3.hs.zeroRttSuite = ss->ssl3.hs.cipher_suite;
1869
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_0rtt_cipher_suite;
1870
0
}
1871
1872
/* Check if the offered group is acceptable. */
1873
static PRBool
1874
tls13_isGroupAcceptable(const sslNamedGroupDef *offered,
1875
                        const sslNamedGroupDef *preferredGroup)
1876
0
{
1877
    /* We accept epsilon (e) bits around the offered group size. */
1878
0
    const unsigned int e = 2;
1879
1880
0
    PORT_Assert(offered);
1881
0
    PORT_Assert(preferredGroup);
1882
1883
0
    if (offered->bits >= preferredGroup->bits - e &&
1884
0
        offered->bits <= preferredGroup->bits + e) {
1885
0
        return PR_TRUE;
1886
0
    }
1887
1888
0
    return PR_FALSE;
1889
0
}
1890
1891
/* Find remote key share for given group and return it.
1892
 * Returns NULL if no key share is found. */
1893
static TLS13KeyShareEntry *
1894
tls13_FindKeyShareEntry(sslSocket *ss, const sslNamedGroupDef *group)
1895
0
{
1896
0
    PRCList *cur_p = PR_NEXT_LINK(&ss->xtnData.remoteKeyShares);
1897
0
    while (cur_p != &ss->xtnData.remoteKeyShares) {
1898
0
        TLS13KeyShareEntry *offer = (TLS13KeyShareEntry *)cur_p;
1899
0
        if (offer->group == group) {
1900
0
            return offer;
1901
0
        }
1902
0
        cur_p = PR_NEXT_LINK(cur_p);
1903
0
    }
1904
0
    return NULL;
1905
0
}
1906
1907
static SECStatus
1908
tls13_NegotiateKeyExchange(sslSocket *ss,
1909
                           const sslNamedGroupDef **requestedGroup,
1910
                           TLS13KeyShareEntry **clientShare)
1911
0
{
1912
0
    unsigned int index;
1913
0
    TLS13KeyShareEntry *entry = NULL;
1914
0
    const sslNamedGroupDef *preferredGroup = NULL;
1915
1916
    /* We insist on DHE. */
1917
0
    if (ssl3_ExtensionNegotiated(ss, ssl_tls13_pre_shared_key_xtn)) {
1918
0
        if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_psk_key_exchange_modes_xtn)) {
1919
0
            FATAL_ERROR(ss, SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES,
1920
0
                        missing_extension);
1921
0
            return SECFailure;
1922
0
        }
1923
        /* Since the server insists on DHE to provide forward secracy, for
1924
         * every other PskKem value but DHE stateless resumption is disabled,
1925
         * this includes other specified and GREASE values. */
1926
0
        if (!memchr(ss->xtnData.psk_ke_modes.data, tls13_psk_dh_ke,
1927
0
                    ss->xtnData.psk_ke_modes.len)) {
1928
0
            SSL_TRC(3, ("%d: TLS13[%d]: client offered PSK without DH",
1929
0
                        SSL_GETPID(), ss->fd));
1930
0
            ss->statelessResume = PR_FALSE;
1931
0
        }
1932
0
    }
1933
1934
    /* Now figure out which key share we like the best out of the
1935
     * mutually supported groups, regardless of what the client offered
1936
     * for key shares.
1937
     */
1938
0
    if (!ssl3_ExtensionNegotiated(ss, ssl_supported_groups_xtn)) {
1939
0
        FATAL_ERROR(ss, SSL_ERROR_MISSING_SUPPORTED_GROUPS_EXTENSION,
1940
0
                    missing_extension);
1941
0
        return SECFailure;
1942
0
    }
1943
1944
0
    SSL_TRC(3, ("%d: TLS13[%d]: selected KE = %s", SSL_GETPID(),
1945
0
                ss->fd, ss->statelessResume || ss->xtnData.selectedPsk ? "PSK + (EC)DHE" : "(EC)DHE"));
1946
1947
    /* Find the preferred group and an according client key share available. */
1948
0
    for (index = 0; index < SSL_NAMED_GROUP_COUNT; ++index) {
1949
        /* Continue to the next group if this one is not enabled. */
1950
0
        if (!ss->namedGroupPreferences[index]) {
1951
            /* There's a gap in the preferred groups list. Assume this is a group
1952
             * that's not supported by the client but preferred by the server. */
1953
0
            if (preferredGroup) {
1954
0
                entry = NULL;
1955
0
                break;
1956
0
            }
1957
0
            continue;
1958
0
        }
1959
1960
        /* Check if the client sent a key share for this group. */
1961
0
        entry = tls13_FindKeyShareEntry(ss, ss->namedGroupPreferences[index]);
1962
1963
0
        if (preferredGroup) {
1964
            /* We already found our preferred group but the group didn't have a share. */
1965
0
            if (entry) {
1966
                /* The client sent a key share with group ss->namedGroupPreferences[index] */
1967
0
                if (tls13_isGroupAcceptable(ss->namedGroupPreferences[index],
1968
0
                                            preferredGroup)) {
1969
                    /* This is not the preferred group, but it's acceptable */
1970
0
                    preferredGroup = ss->namedGroupPreferences[index];
1971
0
                } else {
1972
                    /* The proposed group is not acceptable. */
1973
0
                    entry = NULL;
1974
0
                }
1975
0
            }
1976
0
            break;
1977
0
        } else {
1978
            /* The first enabled group is the preferred group. */
1979
0
            preferredGroup = ss->namedGroupPreferences[index];
1980
0
            if (entry) {
1981
0
                break;
1982
0
            }
1983
0
        }
1984
0
    }
1985
1986
0
    if (!preferredGroup) {
1987
0
        FATAL_ERROR(ss, SSL_ERROR_NO_CYPHER_OVERLAP, handshake_failure);
1988
0
        return SECFailure;
1989
0
    }
1990
0
    SSL_TRC(3, ("%d: TLS13[%d]: group = %d", SSL_GETPID(), ss->fd,
1991
0
                preferredGroup->name));
1992
1993
    /* Either provide a share, or provide a group that should be requested in a
1994
     * HelloRetryRequest, but not both. */
1995
0
    if (entry) {
1996
0
        PORT_Assert(preferredGroup == entry->group);
1997
0
        *clientShare = entry;
1998
0
        *requestedGroup = NULL;
1999
0
    } else {
2000
0
        *clientShare = NULL;
2001
0
        *requestedGroup = preferredGroup;
2002
0
    }
2003
0
    return SECSuccess;
2004
0
}
2005
2006
SECStatus
2007
tls13_SelectServerCert(sslSocket *ss)
2008
0
{
2009
0
    PRCList *cursor;
2010
0
    SECStatus rv;
2011
2012
0
    if (!ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) {
2013
0
        FATAL_ERROR(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION,
2014
0
                    missing_extension);
2015
0
        return SECFailure;
2016
0
    }
2017
2018
    /* This picks the first certificate that has:
2019
     * a) the right authentication method, and
2020
     * b) the right named curve (EC only)
2021
     *
2022
     * We might want to do some sort of ranking here later.  For now, it's all
2023
     * based on what order they are configured in. */
2024
0
    for (cursor = PR_NEXT_LINK(&ss->serverCerts);
2025
0
         cursor != &ss->serverCerts;
2026
0
         cursor = PR_NEXT_LINK(cursor)) {
2027
0
        sslServerCert *cert = (sslServerCert *)cursor;
2028
2029
0
        if (SSL_CERT_IS_ONLY(cert, ssl_auth_rsa_decrypt)) {
2030
0
            continue;
2031
0
        }
2032
2033
0
        rv = ssl_PickSignatureScheme(ss,
2034
0
                                     cert->serverCert,
2035
0
                                     cert->serverKeyPair->pubKey,
2036
0
                                     cert->serverKeyPair->privKey,
2037
0
                                     ss->xtnData.sigSchemes,
2038
0
                                     ss->xtnData.numSigSchemes,
2039
0
                                     PR_FALSE,
2040
0
                                     &ss->ssl3.hs.signatureScheme);
2041
0
        if (rv == SECSuccess) {
2042
            /* Found one. */
2043
0
            ss->sec.serverCert = cert;
2044
2045
            /* If we can use a delegated credential (DC) for authentication in
2046
             * the current handshake, then commit to using it now. We'll send a
2047
             * DC as an extension and use the DC private key to sign the
2048
             * handshake.
2049
             *
2050
             * This sets the signature scheme to be the signature scheme
2051
             * indicated by the DC.
2052
             */
2053
0
            rv = tls13_MaybeSetDelegatedCredential(ss);
2054
0
            if (rv != SECSuccess) {
2055
0
                return SECFailure; /* Failure indicates an internal error. */
2056
0
            }
2057
2058
0
            ss->sec.authType = ss->ssl3.hs.kea_def_mutable.authKeyType =
2059
0
                ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme);
2060
0
            ss->sec.authKeyBits = cert->serverKeyBits;
2061
0
            return SECSuccess;
2062
0
        }
2063
0
    }
2064
2065
0
    FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM,
2066
0
                handshake_failure);
2067
0
    return SECFailure;
2068
0
}
2069
2070
/* Note: |requestedGroup| is non-NULL when we send a key_share extension. */
2071
static SECStatus
2072
tls13_MaybeSendHelloRetry(sslSocket *ss, const sslNamedGroupDef *requestedGroup,
2073
                          PRBool *hrrSent)
2074
0
{
2075
0
    SSLHelloRetryRequestAction action = ssl_hello_retry_accept;
2076
0
    PRUint8 token[256] = { 0 };
2077
0
    unsigned int tokenLen = 0;
2078
0
    SECStatus rv;
2079
2080
0
    if (ss->hrrCallback) {
2081
0
        action = ss->hrrCallback(!ss->ssl3.hs.helloRetry,
2082
0
                                 ss->xtnData.applicationToken.data,
2083
0
                                 ss->xtnData.applicationToken.len,
2084
0
                                 token, &tokenLen, sizeof(token),
2085
0
                                 ss->hrrCallbackArg);
2086
0
    }
2087
2088
    /* These use SSL3_SendAlert directly to avoid an assertion in
2089
     * tls13_FatalError(), which is ordinarily OK. */
2090
0
    if (action == ssl_hello_retry_request && ss->ssl3.hs.helloRetry) {
2091
0
        (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
2092
0
        PORT_SetError(SSL_ERROR_APP_CALLBACK_ERROR);
2093
0
        return SECFailure;
2094
0
    }
2095
2096
0
    if (action != ssl_hello_retry_request && tokenLen) {
2097
0
        (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
2098
0
        PORT_SetError(SSL_ERROR_APP_CALLBACK_ERROR);
2099
0
        return SECFailure;
2100
0
    }
2101
2102
0
    if (tokenLen > sizeof(token)) {
2103
0
        (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
2104
0
        PORT_SetError(SSL_ERROR_APP_CALLBACK_ERROR);
2105
0
        return SECFailure;
2106
0
    }
2107
2108
0
    if (action == ssl_hello_retry_fail) {
2109
0
        FATAL_ERROR(ss, SSL_ERROR_APPLICATION_ABORT, handshake_failure);
2110
0
        return SECFailure;
2111
0
    }
2112
2113
0
    if (action == ssl_hello_retry_reject_0rtt) {
2114
0
        ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
2115
0
        ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
2116
0
    }
2117
2118
0
    if (!requestedGroup && action != ssl_hello_retry_request) {
2119
0
        return SECSuccess;
2120
0
    }
2121
2122
0
    rv = tls13_SendHelloRetryRequest(ss, requestedGroup, token, tokenLen);
2123
0
    if (rv != SECSuccess) {
2124
0
        return SECFailure; /* Code already set. */
2125
0
    }
2126
2127
    /* We may have received ECH, but have to start over with CH2. */
2128
0
    ss->ssl3.hs.echAccepted = PR_FALSE;
2129
0
    PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE);
2130
0
    ss->ssl3.hs.echHpkeCtx = NULL;
2131
2132
0
    *hrrSent = PR_TRUE;
2133
0
    return SECSuccess;
2134
0
}
2135
2136
static SECStatus
2137
tls13_NegotiateAuthentication(sslSocket *ss)
2138
0
{
2139
0
    if (ss->statelessResume) {
2140
0
        SSL_TRC(3, ("%d: TLS13[%d]: selected resumption PSK authentication",
2141
0
                    SSL_GETPID(), ss->fd));
2142
0
        ss->ssl3.hs.signatureScheme = ssl_sig_none;
2143
0
        ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk;
2144
        /* Overwritten by tls13_RestoreCipherInfo. */
2145
0
        ss->sec.authType = ssl_auth_psk;
2146
0
        return SECSuccess;
2147
0
    } else if (ss->xtnData.selectedPsk) {
2148
        /* If the EPSK doesn't specify a suite, use what was negotiated.
2149
         * Else, only use the EPSK if we negotiated that suite. */
2150
0
        if (ss->xtnData.selectedPsk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL ||
2151
0
            ss->ssl3.hs.cipher_suite == ss->xtnData.selectedPsk->zeroRttSuite) {
2152
0
            SSL_TRC(3, ("%d: TLS13[%d]: selected external PSK authentication",
2153
0
                        SSL_GETPID(), ss->fd));
2154
0
            ss->ssl3.hs.signatureScheme = ssl_sig_none;
2155
0
            ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk;
2156
0
            ss->sec.authType = ssl_auth_psk;
2157
0
            return SECSuccess;
2158
0
        }
2159
0
    }
2160
2161
    /* If there were PSKs, they are no longer needed. */
2162
0
    if (ss->xtnData.selectedPsk) {
2163
0
        tls13_DestroyPskList(&ss->ssl3.hs.psks);
2164
0
        ss->xtnData.selectedPsk = NULL;
2165
0
    }
2166
2167
0
    SSL_TRC(3, ("%d: TLS13[%d]: selected certificate authentication",
2168
0
                SSL_GETPID(), ss->fd));
2169
0
    SECStatus rv = tls13_SelectServerCert(ss);
2170
0
    if (rv != SECSuccess) {
2171
0
        return SECFailure;
2172
0
    }
2173
0
    return SECSuccess;
2174
0
}
2175
/* Called from ssl3_HandleClientHello after we have parsed the
2176
 * ClientHello and are sure that we are going to do TLS 1.3
2177
 * or fail. */
2178
SECStatus
2179
tls13_HandleClientHelloPart2(sslSocket *ss,
2180
                             const SECItem *suites,
2181
                             sslSessionID *sid,
2182
                             const PRUint8 *msg,
2183
                             unsigned int len)
2184
0
{
2185
0
    SECStatus rv;
2186
0
    SSL3Statistics *ssl3stats = SSL_GetStatistics();
2187
0
    const sslNamedGroupDef *requestedGroup = NULL;
2188
0
    TLS13KeyShareEntry *clientShare = NULL;
2189
0
    ssl3CipherSuite previousCipherSuite = 0;
2190
0
    const sslNamedGroupDef *previousGroup = NULL;
2191
0
    PRBool hrr = PR_FALSE;
2192
0
    PRBool previousOfferedEch;
2193
2194
    /* If the legacy_version field is set to 0x300 or smaller,
2195
     * reject the connection with protocol_version alert. */
2196
0
    if (ss->clientHelloVersion <= SSL_LIBRARY_VERSION_3_0) {
2197
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, protocol_version);
2198
0
        goto loser;
2199
0
    }
2200
2201
0
    ss->ssl3.hs.endOfFlight = PR_TRUE;
2202
2203
0
    if (ssl3_ExtensionNegotiated(ss, ssl_tls13_early_data_xtn)) {
2204
0
        ss->ssl3.hs.zeroRttState = ssl_0rtt_sent;
2205
0
    }
2206
2207
    /* Negotiate cipher suite. */
2208
0
    rv = ssl3_NegotiateCipherSuite(ss, suites, PR_FALSE);
2209
0
    if (rv != SECSuccess) {
2210
0
        FATAL_ERROR(ss, PORT_GetError(), handshake_failure);
2211
0
        goto loser;
2212
0
    }
2213
2214
    /* If we are going around again, then we should make sure that the cipher
2215
     * suite selection doesn't change. That's a sign of client shennanigans. */
2216
0
    if (ss->ssl3.hs.helloRetry) {
2217
2218
        /* Update sequence numbers before checking the cookie so that any alerts
2219
         * we generate are sent with the right sequence numbers. */
2220
0
        if (IS_DTLS(ss)) {
2221
            /* Count the first ClientHello and the HelloRetryRequest. */
2222
0
            ss->ssl3.hs.sendMessageSeq = 1;
2223
0
            ss->ssl3.hs.recvMessageSeq = 1;
2224
0
            ssl_GetSpecWriteLock(ss);
2225
            /* Increase the write sequence number.  The read sequence number
2226
             * will be reset after this to early data or handshake. */
2227
0
            ss->ssl3.cwSpec->nextSeqNum = 1;
2228
0
            ssl_ReleaseSpecWriteLock(ss);
2229
0
        }
2230
2231
0
        if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_cookie_xtn) ||
2232
0
            !ss->xtnData.cookie.len) {
2233
0
            FATAL_ERROR(ss, SSL_ERROR_MISSING_COOKIE_EXTENSION,
2234
0
                        missing_extension);
2235
0
            goto loser;
2236
0
        }
2237
0
        PRINT_BUF(50, (ss, "Client sent cookie",
2238
0
                       ss->xtnData.cookie.data, ss->xtnData.cookie.len));
2239
2240
0
        rv = tls13_HandleHrrCookie(ss, ss->xtnData.cookie.data,
2241
0
                                   ss->xtnData.cookie.len,
2242
0
                                   &previousCipherSuite,
2243
0
                                   &previousGroup,
2244
0
                                   &previousOfferedEch, NULL, PR_TRUE);
2245
2246
0
        if (rv != SECSuccess) {
2247
0
            FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO, illegal_parameter);
2248
0
            goto loser;
2249
0
        }
2250
0
    }
2251
2252
    /* Now merge the ClientHello into the hash state. */
2253
0
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_client_hello, msg, len);
2254
0
    if (rv != SECSuccess) {
2255
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2256
0
        goto loser;
2257
0
    }
2258
2259
    /* Now create a synthetic kea_def that we can tweak. */
2260
0
    ss->ssl3.hs.kea_def_mutable = *ss->ssl3.hs.kea_def;
2261
0
    ss->ssl3.hs.kea_def = &ss->ssl3.hs.kea_def_mutable;
2262
2263
    /* Note: We call this quite a bit earlier than with TLS 1.2 and
2264
     * before. */
2265
0
    rv = ssl3_ServerCallSNICallback(ss);
2266
0
    if (rv != SECSuccess) {
2267
0
        goto loser; /* An alert has already been sent. */
2268
0
    }
2269
2270
    /* Check if we could in principle resume. */
2271
0
    if (ss->statelessResume) {
2272
0
        PORT_Assert(sid);
2273
0
        if (!sid) {
2274
0
            FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2275
0
            return SECFailure;
2276
0
        }
2277
0
        if (!tls13_CanResume(ss, sid)) {
2278
0
            ss->statelessResume = PR_FALSE;
2279
0
        }
2280
0
    }
2281
2282
    /* Select key exchange. */
2283
0
    rv = tls13_NegotiateKeyExchange(ss, &requestedGroup, &clientShare);
2284
0
    if (rv != SECSuccess) {
2285
0
        goto loser;
2286
0
    }
2287
    /* We should get either one of these, but not both. */
2288
0
    PORT_Assert((requestedGroup && !clientShare) ||
2289
0
                (!requestedGroup && clientShare));
2290
2291
    /* After HelloRetryRequest, check consistency of cipher and group. */
2292
0
    if (ss->ssl3.hs.helloRetry) {
2293
0
        PORT_Assert(previousCipherSuite);
2294
0
        if (ss->ssl3.hs.cipher_suite != previousCipherSuite) {
2295
0
            FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
2296
0
                        illegal_parameter);
2297
0
            goto loser;
2298
0
        }
2299
0
        if (!clientShare) {
2300
0
            FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
2301
0
                        illegal_parameter);
2302
0
            goto loser;
2303
0
        }
2304
2305
        /* CH1/CH2 must either both include ECH, or both exclude it. */
2306
0
        if (previousOfferedEch != (ss->xtnData.ech != NULL)) {
2307
0
            FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
2308
0
                        previousOfferedEch ? missing_extension : illegal_parameter);
2309
0
            goto loser;
2310
0
        }
2311
2312
        /* If we requested a new key share, check that the client provided just
2313
         * one of the right type. */
2314
0
        if (previousGroup) {
2315
0
            if (PR_PREV_LINK(&ss->xtnData.remoteKeyShares) !=
2316
0
                PR_NEXT_LINK(&ss->xtnData.remoteKeyShares)) {
2317
0
                FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
2318
0
                            illegal_parameter);
2319
0
                goto loser;
2320
0
            }
2321
0
            if (clientShare->group != previousGroup) {
2322
0
                FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
2323
0
                            illegal_parameter);
2324
0
                goto loser;
2325
0
            }
2326
0
        }
2327
0
    }
2328
2329
0
    rv = tls13_MaybeSendHelloRetry(ss, requestedGroup, &hrr);
2330
0
    if (rv != SECSuccess) {
2331
0
        goto loser;
2332
0
    }
2333
0
    if (hrr) {
2334
0
        if (sid) { /* Free the sid. */
2335
0
            ssl_UncacheSessionID(ss);
2336
0
            ssl_FreeSID(sid);
2337
0
        }
2338
0
        PORT_Assert(ss->ssl3.hs.helloRetry);
2339
0
        return SECSuccess;
2340
0
    }
2341
2342
    /* Select the authentication (this is also handshake shape). */
2343
0
    rv = tls13_NegotiateAuthentication(ss);
2344
0
    if (rv != SECSuccess) {
2345
0
        goto loser;
2346
0
    }
2347
2348
0
    if (ss->sec.authType == ssl_auth_psk) {
2349
0
        if (ss->statelessResume) {
2350
            /* We are now committed to trying to resume. */
2351
0
            PORT_Assert(sid);
2352
            /* Check that the negotiated SNI and the cached SNI match. */
2353
0
            if (SECITEM_CompareItem(&sid->u.ssl3.srvName,
2354
0
                                    &ss->ssl3.hs.srvVirtName) != SECEqual) {
2355
0
                FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO,
2356
0
                            handshake_failure);
2357
0
                goto loser;
2358
0
            }
2359
2360
0
            ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType,
2361
0
                                                    sid->namedCurve);
2362
0
            PORT_Assert(ss->sec.serverCert);
2363
2364
0
            rv = tls13_RecoverWrappedSharedSecret(ss, sid);
2365
0
            if (rv != SECSuccess) {
2366
0
                SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
2367
0
                FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2368
0
                goto loser;
2369
0
            }
2370
0
            tls13_RestoreCipherInfo(ss, sid);
2371
2372
0
            PORT_Assert(!ss->sec.localCert);
2373
0
            ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
2374
0
            if (sid->peerCert != NULL) {
2375
0
                ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
2376
0
            }
2377
0
        } else if (sid) {
2378
            /* We should never have a SID in the non-resumption case. */
2379
0
            PORT_Assert(0);
2380
0
            ssl_UncacheSessionID(ss);
2381
0
            ssl_FreeSID(sid);
2382
0
            sid = NULL;
2383
0
        }
2384
0
        ssl3_RegisterExtensionSender(
2385
0
            ss, &ss->xtnData,
2386
0
            ssl_tls13_pre_shared_key_xtn, tls13_ServerSendPreSharedKeyXtn);
2387
0
        tls13_NegotiateZeroRtt(ss, sid);
2388
2389
0
        rv = tls13_ComputeEarlySecretsWithPsk(ss);
2390
0
        if (rv != SECSuccess) {
2391
0
            FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2392
0
            return SECFailure;
2393
0
        }
2394
0
    } else {
2395
0
        if (sid) { /* we had a sid, but it's no longer valid, free it */
2396
0
            SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
2397
0
            ssl_UncacheSessionID(ss);
2398
0
            ssl_FreeSID(sid);
2399
0
            sid = NULL;
2400
0
        }
2401
0
        tls13_NegotiateZeroRtt(ss, NULL);
2402
0
    }
2403
2404
0
    if (ss->statelessResume) {
2405
0
        PORT_Assert(ss->xtnData.selectedPsk);
2406
0
        PORT_Assert(ss->ssl3.hs.kea_def_mutable.authKeyType == ssl_auth_psk);
2407
0
    }
2408
2409
    /* Now that we have the binder key, check the binder. */
2410
0
    if (ss->xtnData.selectedPsk) {
2411
0
        SSL3Hashes hashes;
2412
0
        PORT_Assert(ss->ssl3.hs.messages.len > ss->xtnData.pskBindersLen);
2413
0
        rv = tls13_ComputePskBinderHash(
2414
0
            ss,
2415
0
            ss->ssl3.hs.messages.buf,
2416
0
            ss->ssl3.hs.messages.len - ss->xtnData.pskBindersLen,
2417
0
            &hashes, tls13_GetHash(ss));
2418
0
        if (rv != SECSuccess) {
2419
0
            FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2420
0
            goto loser;
2421
0
        }
2422
2423
0
        PORT_Assert(ss->xtnData.selectedPsk->hash == tls13_GetHash(ss));
2424
0
        PORT_Assert(ss->ssl3.hs.suite_def);
2425
0
        rv = tls13_VerifyFinished(ss, ssl_hs_client_hello,
2426
0
                                  ss->xtnData.selectedPsk->binderKey,
2427
0
                                  ss->xtnData.pskBinder.data,
2428
0
                                  ss->xtnData.pskBinder.len,
2429
0
                                  &hashes);
2430
0
    }
2431
0
    if (rv != SECSuccess) {
2432
0
        goto loser;
2433
0
    }
2434
2435
    /* This needs to go after we verify the psk binder. */
2436
0
    rv = ssl3_InitHandshakeHashes(ss);
2437
0
    if (rv != SECSuccess) {
2438
0
        goto loser;
2439
0
    }
2440
2441
    /* If this is TLS 1.3 we are expecting a ClientKeyShare
2442
     * extension. Missing/absent extension cause failure
2443
     * below. */
2444
0
    rv = tls13_HandleClientKeyShare(ss, clientShare);
2445
0
    if (rv != SECSuccess) {
2446
0
        goto loser; /* An alert was sent already. */
2447
0
    }
2448
2449
    /* From this point we are either committed to resumption, or not. */
2450
0
    if (ss->statelessResume) {
2451
0
        SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_hits);
2452
0
        SSL_AtomicIncrementLong(&ssl3stats->hch_sid_stateless_resumes);
2453
0
    } else {
2454
0
        if (sid) {
2455
            /* We had a sid, but it's no longer valid, free it. */
2456
0
            SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
2457
0
            ssl_UncacheSessionID(ss);
2458
0
            ssl_FreeSID(sid);
2459
0
        } else if (!ss->xtnData.selectedPsk) {
2460
0
            SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_misses);
2461
0
        }
2462
2463
0
        sid = ssl3_NewSessionID(ss, PR_TRUE);
2464
0
        if (!sid) {
2465
0
            FATAL_ERROR(ss, PORT_GetError(), internal_error);
2466
0
            return SECFailure;
2467
0
        }
2468
0
    }
2469
    /* Take ownership of the session. */
2470
0
    ss->sec.ci.sid = sid;
2471
0
    sid = NULL;
2472
2473
0
    if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
2474
0
        rv = tls13_DeriveEarlySecrets(ss);
2475
0
        if (rv != SECSuccess) {
2476
0
            FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2477
0
            return SECFailure;
2478
0
        }
2479
0
    }
2480
2481
0
    ssl_GetXmitBufLock(ss);
2482
0
    rv = tls13_SendServerHelloSequence(ss);
2483
0
    ssl_ReleaseXmitBufLock(ss);
2484
0
    if (rv != SECSuccess) {
2485
0
        FATAL_ERROR(ss, PORT_GetError(), handshake_failure);
2486
0
        return SECFailure;
2487
0
    }
2488
2489
    /* We're done with PSKs */
2490
0
    tls13_DestroyPskList(&ss->ssl3.hs.psks);
2491
0
    ss->xtnData.selectedPsk = NULL;
2492
2493
0
    return SECSuccess;
2494
2495
0
loser:
2496
0
    if (sid) {
2497
0
        ssl_UncacheSessionID(ss);
2498
0
        ssl_FreeSID(sid);
2499
0
    }
2500
0
    return SECFailure;
2501
0
}
2502
2503
SECStatus
2504
SSLExp_HelloRetryRequestCallback(PRFileDesc *fd,
2505
                                 SSLHelloRetryRequestCallback cb, void *arg)
2506
0
{
2507
0
    sslSocket *ss = ssl_FindSocket(fd);
2508
0
    if (!ss) {
2509
0
        return SECFailure; /* Code already set. */
2510
0
    }
2511
2512
0
    ss->hrrCallback = cb;
2513
0
    ss->hrrCallbackArg = arg;
2514
0
    return SECSuccess;
2515
0
}
2516
2517
/*
2518
 * struct {
2519
 *     ProtocolVersion server_version;
2520
 *     CipherSuite cipher_suite;
2521
 *     Extension extensions<2..2^16-1>;
2522
 * } HelloRetryRequest;
2523
 *
2524
 * Note: this function takes an empty buffer and returns
2525
 * a non-empty one on success, in which case the caller must
2526
 * eventually clean up.
2527
 */
2528
SECStatus
2529
tls13_ConstructHelloRetryRequest(sslSocket *ss,
2530
                                 ssl3CipherSuite cipherSuite,
2531
                                 const sslNamedGroupDef *selectedGroup,
2532
                                 PRUint8 *cookie, unsigned int cookieLen,
2533
                                 const PRUint8 *cookieGreaseEchSignal,
2534
                                 sslBuffer *buffer)
2535
0
{
2536
0
    SECStatus rv;
2537
0
    sslBuffer extensionsBuf = SSL_BUFFER_EMPTY;
2538
0
    PORT_Assert(buffer->len == 0);
2539
2540
    /* Note: cookie is pointing to a stack variable, so is only valid
2541
     * now. */
2542
0
    ss->xtnData.selectedGroup = selectedGroup;
2543
0
    ss->xtnData.cookie.data = cookie;
2544
0
    ss->xtnData.cookie.len = cookieLen;
2545
2546
    /* Set restored ss->ssl3.hs.greaseEchBuf value for ECH HRR extension
2547
     * reconstruction. */
2548
0
    if (cookieGreaseEchSignal) {
2549
0
        PORT_Assert(!ss->ssl3.hs.greaseEchBuf.len);
2550
0
        rv = sslBuffer_Append(&ss->ssl3.hs.greaseEchBuf,
2551
0
                              cookieGreaseEchSignal,
2552
0
                              TLS13_ECH_SIGNAL_LEN);
2553
0
        if (rv != SECSuccess) {
2554
0
            goto loser;
2555
0
        }
2556
0
    }
2557
0
    rv = ssl_ConstructExtensions(ss, &extensionsBuf,
2558
0
                                 ssl_hs_hello_retry_request);
2559
    /* Reset ss->ssl3.hs.greaseEchBuf if it was changed. */
2560
0
    if (cookieGreaseEchSignal) {
2561
0
        sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
2562
0
    }
2563
0
    if (rv != SECSuccess) {
2564
0
        goto loser;
2565
0
    }
2566
    /* These extensions can't be empty. */
2567
0
    PORT_Assert(SSL_BUFFER_LEN(&extensionsBuf) > 0);
2568
2569
    /* Clean up cookie so we're not pointing at random memory. */
2570
0
    ss->xtnData.cookie.data = NULL;
2571
0
    ss->xtnData.cookie.len = 0;
2572
2573
0
    rv = ssl_ConstructServerHello(ss, PR_TRUE, &extensionsBuf, buffer);
2574
0
    if (rv != SECSuccess) {
2575
0
        goto loser;
2576
0
    }
2577
0
    sslBuffer_Clear(&extensionsBuf);
2578
0
    return SECSuccess;
2579
2580
0
loser:
2581
0
    sslBuffer_Clear(&extensionsBuf);
2582
0
    sslBuffer_Clear(buffer);
2583
0
    return SECFailure;
2584
0
}
2585
2586
static SECStatus
2587
tls13_SendHelloRetryRequest(sslSocket *ss,
2588
                            const sslNamedGroupDef *requestedGroup,
2589
                            const PRUint8 *appToken, unsigned int appTokenLen)
2590
0
{
2591
0
    SECStatus rv;
2592
0
    unsigned int cookieLen;
2593
0
    PRUint8 cookie[1024];
2594
0
    sslBuffer messageBuf = SSL_BUFFER_EMPTY;
2595
2596
0
    SSL_TRC(3, ("%d: TLS13[%d]: send hello retry request handshake",
2597
0
                SSL_GETPID(), ss->fd));
2598
2599
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2600
2601
    /* If an ECH backend or shared-mode server accepted ECH when offered,
2602
     * the HRR extension's payload must be set to 8 zero bytes, these are
2603
     * overwritten with the accept_confirmation value after the handshake
2604
     * transcript calculation.
2605
     * If a client-facing or shared-mode server did not accept ECH when offered
2606
     * OR if ECH GREASE is enabled on the server and a ECH extension was
2607
     * received, a 8 byte random value is set as the extension's payload
2608
     * [draft-ietf-tls-esni-14, Section 7].
2609
     *
2610
     * The (temporary) payload is written to the extension in tls13exthandle.c/
2611
     * tls13_ServerSendHrrEchXtn(). */
2612
0
    if (ss->xtnData.ech) {
2613
0
        PRUint8 echGreaseRaw[TLS13_ECH_SIGNAL_LEN] = { 0 };
2614
0
        if (!(ss->ssl3.hs.echAccepted ||
2615
0
              (ss->opt.enableTls13BackendEch &&
2616
0
               ss->xtnData.ech &&
2617
0
               ss->xtnData.ech->receivedInnerXtn))) {
2618
0
            rv = PK11_GenerateRandom(echGreaseRaw, TLS13_ECH_SIGNAL_LEN);
2619
0
            if (rv != SECSuccess) {
2620
0
                return SECFailure;
2621
0
            }
2622
0
            SSL_TRC(100, ("Generated random value for ECH HRR GREASE."));
2623
0
        }
2624
0
        sslBuffer echGreaseBuffer = SSL_BUFFER_EMPTY;
2625
0
        rv = sslBuffer_Append(&echGreaseBuffer, echGreaseRaw, sizeof(echGreaseRaw));
2626
0
        if (rv != SECSuccess) {
2627
0
            return SECFailure;
2628
0
        }
2629
        /* HRR GREASE/accept_confirmation zero bytes placeholder buffer. */
2630
0
        ss->ssl3.hs.greaseEchBuf = echGreaseBuffer;
2631
0
    }
2632
2633
    /* Compute the cookie we are going to need. */
2634
0
    rv = tls13_MakeHrrCookie(ss, requestedGroup,
2635
0
                             appToken, appTokenLen,
2636
0
                             cookie, &cookieLen, sizeof(cookie));
2637
0
    if (rv != SECSuccess) {
2638
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2639
0
        return SECFailure;
2640
0
    }
2641
2642
    /* Now build the body of the message. */
2643
0
    rv = tls13_ConstructHelloRetryRequest(ss, ss->ssl3.hs.cipher_suite,
2644
0
                                          requestedGroup,
2645
0
                                          cookie, cookieLen,
2646
0
                                          NULL, &messageBuf);
2647
0
    if (rv != SECSuccess) {
2648
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2649
0
        return SECFailure;
2650
0
    }
2651
2652
    /* And send it. */
2653
0
    ssl_GetXmitBufLock(ss);
2654
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello,
2655
0
                                    SSL_BUFFER_LEN(&messageBuf));
2656
0
    if (rv != SECSuccess) {
2657
0
        goto loser;
2658
0
    }
2659
0
    rv = ssl3_AppendBufferToHandshake(ss, &messageBuf);
2660
0
    if (rv != SECSuccess) {
2661
0
        goto loser;
2662
0
    }
2663
0
    sslBuffer_Clear(&messageBuf); /* Done with messageBuf */
2664
2665
0
    if (ss->ssl3.hs.fakeSid.len) {
2666
0
        PRInt32 sent;
2667
2668
0
        PORT_Assert(!IS_DTLS(ss));
2669
0
        rv = ssl3_SendChangeCipherSpecsInt(ss);
2670
0
        if (rv != SECSuccess) {
2671
0
            goto loser;
2672
0
        }
2673
        /* ssl3_SendChangeCipherSpecsInt() only flushes to the output buffer, so we
2674
         * have to force a send. */
2675
0
        sent = ssl_SendSavedWriteData(ss);
2676
0
        if (sent < 0 && PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
2677
0
            PORT_SetError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2678
0
            goto loser;
2679
0
        }
2680
0
    } else {
2681
0
        rv = ssl3_FlushHandshake(ss, 0);
2682
0
        if (rv != SECSuccess) {
2683
0
            goto loser; /* error code set by ssl3_FlushHandshake */
2684
0
        }
2685
0
    }
2686
2687
    /* We depend on this being exactly one record and one message. */
2688
0
    PORT_Assert(!IS_DTLS(ss) || (ss->ssl3.hs.sendMessageSeq == 1 &&
2689
0
                                 ss->ssl3.cwSpec->nextSeqNum == 1));
2690
0
    ssl_ReleaseXmitBufLock(ss);
2691
2692
0
    ss->ssl3.hs.helloRetry = PR_TRUE;
2693
2694
    /* We received early data but have to ignore it because we sent a retry. */
2695
0
    if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
2696
0
        ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
2697
0
        ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_hrr;
2698
0
    }
2699
2700
0
    return SECSuccess;
2701
2702
0
loser:
2703
0
    sslBuffer_Clear(&messageBuf);
2704
0
    ssl_ReleaseXmitBufLock(ss);
2705
0
    return SECFailure;
2706
0
}
2707
2708
/* Called from tls13_HandleClientHello.
2709
 *
2710
 * Caller must hold Handshake and RecvBuf locks.
2711
 */
2712
2713
static SECStatus
2714
tls13_HandleClientKeyShare(sslSocket *ss, TLS13KeyShareEntry *peerShare)
2715
0
{
2716
0
    SECStatus rv;
2717
0
    sslEphemeralKeyPair *keyPair; /* ours */
2718
0
    SECItem *ciphertext = NULL;
2719
0
    PK11SymKey *dheSecret = NULL;
2720
0
    PK11SymKey *kemSecret = NULL;
2721
2722
0
    SSL_TRC(3, ("%d: TLS13[%d]: handle client_key_share handshake",
2723
0
                SSL_GETPID(), ss->fd));
2724
2725
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
2726
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2727
0
    PORT_Assert(peerShare);
2728
2729
0
    tls13_SetKeyExchangeType(ss, peerShare->group);
2730
2731
    /* Generate our key */
2732
0
    rv = tls13_AddKeyShare(ss, peerShare->group);
2733
0
    if (rv != SECSuccess) {
2734
0
        return rv;
2735
0
    }
2736
2737
    /* We should have exactly one key share. */
2738
0
    PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
2739
0
    PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==
2740
0
                PR_NEXT_LINK(&ss->ephemeralKeyPairs));
2741
2742
0
    keyPair = ((sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs));
2743
0
    ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->keys->pubKey);
2744
2745
    /* Register the sender */
2746
0
    rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_tls13_key_share_xtn,
2747
0
                                      tls13_ServerSendKeyShareXtn);
2748
0
    if (rv != SECSuccess) {
2749
0
        return SECFailure; /* Error code set already. */
2750
0
    }
2751
2752
0
    rv = tls13_HandleKeyShare(ss, peerShare, keyPair->keys,
2753
0
                              tls13_GetHash(ss),
2754
0
                              &dheSecret);
2755
0
    if (rv != SECSuccess) {
2756
0
        goto loser; /* Error code already set. */
2757
0
    }
2758
2759
0
    if (peerShare->group->keaType == ssl_kea_ecdh_hybrid) {
2760
0
        rv = tls13_HandleKEMKey(ss, peerShare, &kemSecret, &ciphertext);
2761
0
        if (rv != SECSuccess) {
2762
0
            goto loser; /* Error set by tls13_HandleKEMKey */
2763
0
        }
2764
0
        switch (peerShare->group->name) {
2765
0
            case ssl_grp_kem_xyber768d00:
2766
0
                ss->ssl3.hs.dheSecret = PK11_ConcatSymKeys(dheSecret, kemSecret, CKM_HKDF_DERIVE, CKA_DERIVE);
2767
0
                break;
2768
0
            case ssl_grp_kem_mlkem768x25519:
2769
0
                ss->ssl3.hs.dheSecret = PK11_ConcatSymKeys(kemSecret, dheSecret, CKM_HKDF_DERIVE, CKA_DERIVE);
2770
0
                break;
2771
0
            default:
2772
0
                PORT_Assert(0);
2773
0
                PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2774
0
                ss->ssl3.hs.dheSecret = NULL;
2775
0
                break;
2776
0
        }
2777
0
        if (!ss->ssl3.hs.dheSecret) {
2778
0
            goto loser; /* Error set by PK11_ConcatSymKeys */
2779
0
        }
2780
0
        keyPair->kemCt = ciphertext;
2781
0
        PK11_FreeSymKey(dheSecret);
2782
0
        PK11_FreeSymKey(kemSecret);
2783
0
    } else {
2784
0
        ss->ssl3.hs.dheSecret = dheSecret;
2785
0
    }
2786
2787
0
    return SECSuccess;
2788
2789
0
loser:
2790
0
    SECITEM_FreeItem(ciphertext, PR_TRUE);
2791
0
    PK11_FreeSymKey(dheSecret);
2792
0
    PK11_FreeSymKey(kemSecret);
2793
0
    FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
2794
0
    return SECFailure;
2795
0
}
2796
2797
/*
2798
 *     [draft-ietf-tls-tls13-11] Section 6.3.3.2
2799
 *
2800
 *     opaque DistinguishedName<1..2^16-1>;
2801
 *
2802
 *     struct {
2803
 *         opaque certificate_extension_oid<1..2^8-1>;
2804
 *         opaque certificate_extension_values<0..2^16-1>;
2805
 *     } CertificateExtension;
2806
 *
2807
 *     struct {
2808
 *         opaque certificate_request_context<0..2^8-1>;
2809
 *         SignatureAndHashAlgorithm
2810
 *           supported_signature_algorithms<2..2^16-2>;
2811
 *         DistinguishedName certificate_authorities<0..2^16-1>;
2812
 *         CertificateExtension certificate_extensions<0..2^16-1>;
2813
 *     } CertificateRequest;
2814
 */
2815
static SECStatus
2816
tls13_SendCertificateRequest(sslSocket *ss)
2817
0
{
2818
0
    SECStatus rv;
2819
0
    sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
2820
0
    unsigned int offset = 0;
2821
2822
0
    SSL_TRC(3, ("%d: TLS13[%d]: begin send certificate_request",
2823
0
                SSL_GETPID(), ss->fd));
2824
2825
0
    if (ss->firstHsDone) {
2826
0
        PORT_Assert(ss->ssl3.hs.shaPostHandshake == NULL);
2827
0
        ss->ssl3.hs.shaPostHandshake = PK11_CloneContext(ss->ssl3.hs.sha);
2828
0
        if (ss->ssl3.hs.shaPostHandshake == NULL) {
2829
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
2830
0
            return SECFailure;
2831
0
        }
2832
0
    }
2833
2834
0
    rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_certificate_request);
2835
0
    if (rv != SECSuccess) {
2836
0
        return SECFailure; /* Code already set. */
2837
0
    }
2838
    /* We should always have at least one of these. */
2839
0
    PORT_Assert(SSL_BUFFER_LEN(&extensionBuf) > 0);
2840
2841
    /* Create a new request context for post-handshake authentication */
2842
0
    if (ss->firstHsDone) {
2843
0
        PRUint8 context[16];
2844
0
        SECItem contextItem = { siBuffer, context, sizeof(context) };
2845
2846
0
        rv = PK11_GenerateRandom(context, sizeof(context));
2847
0
        if (rv != SECSuccess) {
2848
0
            goto loser;
2849
0
        }
2850
2851
0
        SECITEM_FreeItem(&ss->xtnData.certReqContext, PR_FALSE);
2852
0
        rv = SECITEM_CopyItem(NULL, &ss->xtnData.certReqContext, &contextItem);
2853
0
        if (rv != SECSuccess) {
2854
0
            FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
2855
0
            goto loser;
2856
0
        }
2857
2858
0
        offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf);
2859
0
    }
2860
2861
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request,
2862
0
                                    1 + /* request context length */
2863
0
                                        ss->xtnData.certReqContext.len +
2864
0
                                        2 + /* extension length */
2865
0
                                        SSL_BUFFER_LEN(&extensionBuf));
2866
0
    if (rv != SECSuccess) {
2867
0
        goto loser; /* err set by AppendHandshake. */
2868
0
    }
2869
2870
    /* Context. */
2871
0
    rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.certReqContext.data,
2872
0
                                      ss->xtnData.certReqContext.len, 1);
2873
0
    if (rv != SECSuccess) {
2874
0
        goto loser; /* err set by AppendHandshake. */
2875
0
    }
2876
    /* Extensions. */
2877
0
    rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensionBuf, 2);
2878
0
    if (rv != SECSuccess) {
2879
0
        goto loser; /* err set by AppendHandshake. */
2880
0
    }
2881
2882
0
    if (ss->firstHsDone) {
2883
0
        rv = ssl3_UpdatePostHandshakeHashes(ss,
2884
0
                                            SSL_BUFFER_BASE(&ss->sec.ci.sendBuf) + offset,
2885
0
                                            SSL_BUFFER_LEN(&ss->sec.ci.sendBuf) - offset);
2886
0
        if (rv != SECSuccess) {
2887
0
            goto loser;
2888
0
        }
2889
0
    }
2890
2891
0
    sslBuffer_Clear(&extensionBuf);
2892
0
    return SECSuccess;
2893
2894
0
loser:
2895
0
    sslBuffer_Clear(&extensionBuf);
2896
0
    return SECFailure;
2897
0
}
2898
2899
/* [draft-ietf-tls-tls13; S 4.4.1] says:
2900
 *
2901
 *     Transcript-Hash(ClientHello1, HelloRetryRequest, ... MN) =
2902
 *      Hash(message_hash ||        // Handshake type
2903
 *           00 00 Hash.length ||   // Handshake message length
2904
 *           Hash(ClientHello1) ||  // Hash of ClientHello1
2905
 *           HelloRetryRequest ... MN)
2906
 *
2907
 *  For an ECH handshake, the process occurs for the outer
2908
 *  transcript in |ss->ssl3.hs.messages| and the inner
2909
 *  transcript in |ss->ssl3.hs.echInnerMessages|.
2910
 */
2911
static SECStatus
2912
tls13_ReinjectHandshakeTranscript(sslSocket *ss)
2913
1.27k
{
2914
1.27k
    SSL3Hashes hashes = { 0 };
2915
1.27k
    SSL3Hashes echInnerHashes = { 0 };
2916
1.27k
    SECStatus rv;
2917
2918
    /* First compute the hash. */
2919
1.27k
    rv = tls13_ComputeHash(ss, &hashes,
2920
1.27k
                           ss->ssl3.hs.messages.buf,
2921
1.27k
                           ss->ssl3.hs.messages.len,
2922
1.27k
                           tls13_GetHash(ss));
2923
1.27k
    if (rv != SECSuccess) {
2924
0
        return SECFailure;
2925
0
    }
2926
2927
1.27k
    if (ss->ssl3.hs.echHpkeCtx) {
2928
0
        rv = tls13_ComputeHash(ss, &echInnerHashes,
2929
0
                               ss->ssl3.hs.echInnerMessages.buf,
2930
0
                               ss->ssl3.hs.echInnerMessages.len,
2931
0
                               tls13_GetHash(ss));
2932
0
        if (rv != SECSuccess) {
2933
0
            return SECFailure;
2934
0
        }
2935
0
    }
2936
2937
1.27k
    ssl3_RestartHandshakeHashes(ss);
2938
2939
    /* Reinject the message. The Default context variant updates
2940
     * the default hash state. Use it for both non-ECH and ECH Outer. */
2941
1.27k
    rv = ssl_HashHandshakeMessageDefault(ss, ssl_hs_message_hash,
2942
1.27k
                                         hashes.u.raw, hashes.len);
2943
1.27k
    if (rv != SECSuccess) {
2944
0
        return SECFailure;
2945
0
    }
2946
2947
1.27k
    if (ss->ssl3.hs.echHpkeCtx) {
2948
0
        rv = ssl_HashHandshakeMessageEchInner(ss, ssl_hs_message_hash,
2949
0
                                              echInnerHashes.u.raw,
2950
0
                                              echInnerHashes.len);
2951
0
        if (rv != SECSuccess) {
2952
0
            return SECFailure;
2953
0
        }
2954
0
    }
2955
2956
1.27k
    return SECSuccess;
2957
1.27k
}
2958
static unsigned int
2959
ssl_ListCount(PRCList *list)
2960
1.29k
{
2961
1.29k
    unsigned int c = 0;
2962
1.29k
    PRCList *cur;
2963
4.01k
    for (cur = PR_NEXT_LINK(list); cur != list; cur = PR_NEXT_LINK(cur)) {
2964
2.72k
        ++c;
2965
2.72k
    }
2966
1.29k
    return c;
2967
1.29k
}
2968
2969
/*
2970
 * savedMsg contains the HelloRetryRequest message. When its extensions are parsed
2971
 * in ssl3_HandleParsedExtensions, the handler for ECH HRR extensions (tls13_ClientHandleHrrEchXtn)
2972
 * will take a reference into the message buffer.
2973
 *
2974
 * This reference is then used in tls13_MaybeHandleEchSignal in order to compute
2975
 * the transcript for the ECH signal calculation. This was felt to be preferable
2976
 * to re-parsing the HelloRetryRequest message in order to create the transcript.
2977
 *
2978
 * Consequently, savedMsg should not be moved or mutated between these
2979
 * function calls.
2980
 */
2981
SECStatus
2982
tls13_HandleHelloRetryRequest(sslSocket *ss, const PRUint8 *savedMsg,
2983
                              PRUint32 savedLength)
2984
1.29k
{
2985
1.29k
    SECStatus rv;
2986
2987
1.29k
    SSL_TRC(3, ("%d: TLS13[%d]: handle hello retry request",
2988
1.29k
                SSL_GETPID(), ss->fd));
2989
2990
1.29k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
2991
1.29k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2992
2993
1.29k
    if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
2994
0
        FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST,
2995
0
                    unexpected_message);
2996
0
        return SECFailure;
2997
0
    }
2998
1.29k
    PORT_Assert(ss->ssl3.hs.ws == wait_server_hello);
2999
3000
1.29k
    if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
3001
0
        ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
3002
        /* Restore the null cipher spec for writing. */
3003
0
        ssl_GetSpecWriteLock(ss);
3004
0
        ssl_CipherSpecRelease(ss->ssl3.cwSpec);
3005
0
        ss->ssl3.cwSpec = ssl_FindCipherSpecByEpoch(ss, ssl_secret_write,
3006
0
                                                    TrafficKeyClearText);
3007
0
        PORT_Assert(ss->ssl3.cwSpec);
3008
0
        ssl_ReleaseSpecWriteLock(ss);
3009
1.29k
    } else {
3010
1.29k
        PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none);
3011
1.29k
    }
3012
    /* Set the spec version, because we want to send CH now with 0303 */
3013
1.29k
    tls13_SetSpecRecordVersion(ss, ss->ssl3.cwSpec);
3014
3015
    /* Extensions must contain more than just supported_versions.  This will
3016
     * ensure that a HelloRetryRequest isn't a no-op: we must have at least two
3017
     * extensions, supported_versions plus one other.  That other must be one
3018
     * that we understand and recognize as being valid for HelloRetryRequest,
3019
     * and should alter our next Client Hello. */
3020
1.29k
    unsigned int requiredExtensions = 1;
3021
    /* The ECH HRR extension is a no-op from the client's perspective. */
3022
1.29k
    if (ss->xtnData.ech) {
3023
0
        requiredExtensions++;
3024
0
    }
3025
1.29k
    if (ssl_ListCount(&ss->ssl3.hs.remoteExtensions) <= requiredExtensions) {
3026
1
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST,
3027
1
                    decode_error);
3028
1
        return SECFailure;
3029
1
    }
3030
3031
1.29k
    rv = ssl3_HandleParsedExtensions(ss, ssl_hs_hello_retry_request);
3032
1.29k
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
3033
1.29k
    if (rv != SECSuccess) {
3034
20
        return SECFailure; /* Error code set below */
3035
20
    }
3036
1.27k
    rv = tls13_MaybeHandleEchSignal(ss, savedMsg, savedLength, PR_TRUE);
3037
1.27k
    if (rv != SECSuccess) {
3038
0
        return SECFailure;
3039
0
    }
3040
1.27k
    ss->ssl3.hs.helloRetry = PR_TRUE;
3041
1.27k
    rv = tls13_ReinjectHandshakeTranscript(ss);
3042
1.27k
    if (rv != SECSuccess) {
3043
0
        return rv;
3044
0
    }
3045
3046
1.27k
    rv = ssl_HashHandshakeMessage(ss, ssl_hs_server_hello,
3047
1.27k
                                  savedMsg, savedLength);
3048
1.27k
    if (rv != SECSuccess) {
3049
0
        return SECFailure;
3050
0
    }
3051
3052
1.27k
    ssl_GetXmitBufLock(ss);
3053
1.27k
    if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss) &&
3054
1.27k
        ss->ssl3.hs.zeroRttState == ssl_0rtt_none) {
3055
0
        rv = ssl3_SendChangeCipherSpecsInt(ss);
3056
0
        if (rv != SECSuccess) {
3057
0
            goto loser;
3058
0
        }
3059
0
    }
3060
3061
1.27k
    rv = ssl3_SendClientHello(ss, client_hello_retry);
3062
1.27k
    if (rv != SECSuccess) {
3063
0
        goto loser;
3064
0
    }
3065
3066
1.27k
    ssl_ReleaseXmitBufLock(ss);
3067
1.27k
    return SECSuccess;
3068
3069
0
loser:
3070
0
    ssl_ReleaseXmitBufLock(ss);
3071
0
    return SECFailure;
3072
1.27k
}
3073
3074
static SECStatus
3075
tls13_SendPostHandshakeCertificate(sslSocket *ss)
3076
0
{
3077
0
    SECStatus rv;
3078
0
    if (ss->ssl3.hs.restartTarget) {
3079
0
        PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
3080
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3081
0
        return SECFailure;
3082
0
    }
3083
3084
0
    if (ss->ssl3.hs.clientCertificatePending) {
3085
0
        SSL_TRC(3, ("%d: TLS13[%d]: deferring tls13_SendClientSecondFlight because"
3086
0
                    " certificate authentication is still pending.",
3087
0
                    SSL_GETPID(), ss->fd));
3088
0
        ss->ssl3.hs.restartTarget = tls13_SendPostHandshakeCertificate;
3089
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
3090
0
        return SECFailure;
3091
0
    }
3092
3093
0
    ssl_GetXmitBufLock(ss);
3094
0
    rv = tls13_SendClientSecondFlight(ss);
3095
0
    ssl_ReleaseXmitBufLock(ss);
3096
0
    PORT_Assert(ss->ssl3.hs.ws == idle_handshake);
3097
0
    PORT_Assert(ss->ssl3.hs.shaPostHandshake != NULL);
3098
0
    PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
3099
0
    ss->ssl3.hs.shaPostHandshake = NULL;
3100
0
    if (rv != SECSuccess) {
3101
0
        return SECFailure;
3102
0
    }
3103
0
    return rv;
3104
0
}
3105
3106
static SECStatus
3107
tls13_HandleCertificateRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
3108
2
{
3109
2
    SECStatus rv;
3110
2
    SECItem context = { siBuffer, NULL, 0 };
3111
2
    SECItem extensionsData = { siBuffer, NULL, 0 };
3112
3113
2
    SSL_TRC(3, ("%d: TLS13[%d]: handle certificate_request sequence",
3114
2
                SSL_GETPID(), ss->fd));
3115
3116
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3117
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3118
3119
    /* Client */
3120
2
    if (ss->opt.enablePostHandshakeAuth) {
3121
1
        rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST,
3122
1
                                  wait_cert_request, idle_handshake);
3123
1
    } else {
3124
1
        rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST,
3125
1
                                  wait_cert_request);
3126
1
    }
3127
2
    if (rv != SECSuccess) {
3128
2
        return SECFailure;
3129
2
    }
3130
3131
    /*  MUST NOT combine external PSKs with certificate authentication. */
3132
0
    if (ss->sec.authType == ssl_auth_psk) {
3133
0
        FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST, unexpected_message);
3134
0
        return SECFailure;
3135
0
    }
3136
3137
0
    if (tls13_IsPostHandshake(ss)) {
3138
0
        PORT_Assert(ss->ssl3.hs.shaPostHandshake == NULL);
3139
0
        ss->ssl3.hs.shaPostHandshake = PK11_CloneContext(ss->ssl3.hs.sha);
3140
0
        if (ss->ssl3.hs.shaPostHandshake == NULL) {
3141
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3142
0
            return SECFailure;
3143
0
        }
3144
0
        rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate_request, b, length);
3145
0
        if (rv != SECSuccess) {
3146
0
            FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
3147
0
            return SECFailure;
3148
0
        }
3149
3150
        /* clean up anything left from previous handshake. */
3151
0
        if (ss->ssl3.clientCertChain != NULL) {
3152
0
            CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
3153
0
            ss->ssl3.clientCertChain = NULL;
3154
0
        }
3155
0
        if (ss->ssl3.clientCertificate != NULL) {
3156
0
            CERT_DestroyCertificate(ss->ssl3.clientCertificate);
3157
0
            ss->ssl3.clientCertificate = NULL;
3158
0
        }
3159
0
        if (ss->ssl3.clientPrivateKey != NULL) {
3160
0
            SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
3161
0
            ss->ssl3.clientPrivateKey = NULL;
3162
0
        }
3163
0
        if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL) {
3164
0
            PORT_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
3165
0
            ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
3166
0
            ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
3167
0
        }
3168
0
        SECITEM_FreeItem(&ss->xtnData.certReqContext, PR_FALSE);
3169
0
        ss->xtnData.certReqContext.data = NULL;
3170
0
    } else {
3171
0
        PORT_Assert(ss->ssl3.clientCertChain == NULL);
3172
0
        PORT_Assert(ss->ssl3.clientCertificate == NULL);
3173
0
        PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
3174
0
        PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemes == NULL);
3175
0
        PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemesLen == 0);
3176
0
        PORT_Assert(!ss->ssl3.hs.clientCertRequested);
3177
0
        PORT_Assert(ss->xtnData.certReqContext.data == NULL);
3178
0
    }
3179
3180
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &context, 1, &b, &length);
3181
0
    if (rv != SECSuccess) {
3182
0
        return SECFailure;
3183
0
    }
3184
3185
    /* Unless it is a post-handshake client auth, the certificate
3186
     * request context must be empty. */
3187
0
    if (!tls13_IsPostHandshake(ss) && context.len > 0) {
3188
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST, illegal_parameter);
3189
0
        return SECFailure;
3190
0
    }
3191
3192
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &extensionsData, 2, &b, &length);
3193
0
    if (rv != SECSuccess) {
3194
0
        return SECFailure;
3195
0
    }
3196
3197
0
    if (length) {
3198
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST, decode_error);
3199
0
        return SECFailure;
3200
0
    }
3201
3202
    /* Process all the extensions. */
3203
0
    rv = ssl3_HandleExtensions(ss, &extensionsData.data, &extensionsData.len,
3204
0
                               ssl_hs_certificate_request);
3205
0
    if (rv != SECSuccess) {
3206
0
        return SECFailure;
3207
0
    }
3208
3209
0
    if (!ss->xtnData.numSigSchemes) {
3210
0
        FATAL_ERROR(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION,
3211
0
                    missing_extension);
3212
0
        return SECFailure;
3213
0
    }
3214
3215
0
    rv = SECITEM_CopyItem(NULL, &ss->xtnData.certReqContext, &context);
3216
0
    if (rv != SECSuccess) {
3217
0
        return SECFailure;
3218
0
    }
3219
3220
0
    ss->ssl3.hs.clientCertRequested = PR_TRUE;
3221
3222
0
    if (ss->firstHsDone) {
3223
3224
        /* Request a client certificate. */
3225
0
        rv = ssl3_BeginHandleCertificateRequest(
3226
0
            ss, ss->xtnData.sigSchemes, ss->xtnData.numSigSchemes,
3227
0
            &ss->xtnData.certReqAuthorities);
3228
0
        if (rv != SECSuccess) {
3229
0
            FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
3230
0
            return rv;
3231
0
        }
3232
0
        rv = tls13_SendPostHandshakeCertificate(ss);
3233
0
        if (rv != SECSuccess) {
3234
0
            return rv; /* error code is set. */
3235
0
        }
3236
0
    } else {
3237
0
        TLS13_SET_HS_STATE(ss, wait_server_cert);
3238
0
    }
3239
0
    return SECSuccess;
3240
0
}
3241
3242
PRBool
3243
tls13_ShouldRequestClientAuth(sslSocket *ss)
3244
0
{
3245
    /* Even if we are configured to request a certificate, we can't
3246
     * if this handshake used a PSK, even when we are resuming. */
3247
0
    return ss->opt.requestCertificate &&
3248
0
           ss->ssl3.hs.kea_def->authKeyType != ssl_auth_psk;
3249
0
}
3250
3251
static SECStatus
3252
tls13_SendEncryptedServerSequence(sslSocket *ss)
3253
0
{
3254
0
    SECStatus rv;
3255
3256
0
    rv = tls13_ComputeHandshakeSecrets(ss);
3257
0
    if (rv != SECSuccess) {
3258
0
        return SECFailure; /* error code is set. */
3259
0
    }
3260
3261
0
    rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
3262
0
                             ssl_secret_write, PR_FALSE);
3263
0
    if (rv != SECSuccess) {
3264
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
3265
0
        return SECFailure;
3266
0
    }
3267
3268
0
    if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
3269
0
        rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData,
3270
0
                                          ssl_tls13_early_data_xtn,
3271
0
                                          ssl_SendEmptyExtension);
3272
0
        if (rv != SECSuccess) {
3273
0
            return SECFailure; /* Error code set already. */
3274
0
        }
3275
0
    }
3276
3277
0
    rv = tls13_SendEncryptedExtensions(ss);
3278
0
    if (rv != SECSuccess) {
3279
0
        return SECFailure; /* error code is set. */
3280
0
    }
3281
3282
0
    if (tls13_ShouldRequestClientAuth(ss)) {
3283
0
        rv = tls13_SendCertificateRequest(ss);
3284
0
        if (rv != SECSuccess) {
3285
0
            return SECFailure; /* error code is set. */
3286
0
        }
3287
0
    }
3288
0
    if (ss->ssl3.hs.signatureScheme != ssl_sig_none) {
3289
0
        SECKEYPrivateKey *svrPrivKey;
3290
3291
0
        rv = tls13_SendCertificate(ss);
3292
0
        if (rv != SECSuccess) {
3293
0
            return SECFailure; /* error code is set. */
3294
0
        }
3295
3296
0
        if (tls13_IsSigningWithDelegatedCredential(ss)) {
3297
0
            SSL_TRC(3, ("%d: TLS13[%d]: Signing with delegated credential",
3298
0
                        SSL_GETPID(), ss->fd));
3299
0
            svrPrivKey = ss->sec.serverCert->delegCredKeyPair->privKey;
3300
0
        } else {
3301
0
            svrPrivKey = ss->sec.serverCert->serverKeyPair->privKey;
3302
0
        }
3303
3304
0
        rv = tls13_SendCertificateVerify(ss, svrPrivKey);
3305
0
        if (rv != SECSuccess) {
3306
0
            return SECFailure; /* err code is set. */
3307
0
        }
3308
0
    }
3309
3310
0
    rv = tls13_SendFinished(ss, ss->ssl3.hs.serverHsTrafficSecret);
3311
0
    if (rv != SECSuccess) {
3312
0
        return SECFailure; /* error code is set. */
3313
0
    }
3314
3315
0
    return SECSuccess;
3316
0
}
3317
3318
/* Called from:  ssl3_HandleClientHello */
3319
static SECStatus
3320
tls13_SendServerHelloSequence(sslSocket *ss)
3321
0
{
3322
0
    SECStatus rv;
3323
0
    PRErrorCode err = 0;
3324
3325
0
    SSL_TRC(3, ("%d: TLS13[%d]: begin send server_hello sequence",
3326
0
                SSL_GETPID(), ss->fd));
3327
3328
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3329
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3330
3331
0
    rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData,
3332
0
                                      ssl_tls13_supported_versions_xtn,
3333
0
                                      tls13_ServerSendSupportedVersionsXtn);
3334
0
    if (rv != SECSuccess) {
3335
0
        return SECFailure;
3336
0
    }
3337
3338
0
    rv = tls13_ComputeHandshakeSecret(ss);
3339
0
    if (rv != SECSuccess) {
3340
0
        return SECFailure; /* error code is set. */
3341
0
    }
3342
3343
0
    rv = ssl3_SendServerHello(ss);
3344
0
    if (rv != SECSuccess) {
3345
0
        return rv; /* err code is set. */
3346
0
    }
3347
3348
0
    if (ss->ssl3.hs.fakeSid.len) {
3349
0
        PORT_Assert(!IS_DTLS(ss));
3350
0
        SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
3351
0
        if (!ss->ssl3.hs.helloRetry) {
3352
0
            rv = ssl3_SendChangeCipherSpecsInt(ss);
3353
0
            if (rv != SECSuccess) {
3354
0
                return rv;
3355
0
            }
3356
0
        }
3357
0
    }
3358
3359
0
    rv = tls13_SendEncryptedServerSequence(ss);
3360
0
    if (rv != SECSuccess) {
3361
0
        err = PORT_GetError();
3362
0
    }
3363
    /* Even if we get an error, since the ServerHello was successfully
3364
     * serialized, we should give it a chance to reach the network.  This gives
3365
     * the client a chance to perform the key exchange and decrypt the alert
3366
     * we're about to send. */
3367
0
    rv |= ssl3_FlushHandshake(ss, 0);
3368
0
    if (rv != SECSuccess) {
3369
0
        if (err) {
3370
0
            PORT_SetError(err);
3371
0
        }
3372
0
        return SECFailure;
3373
0
    }
3374
3375
    /* Compute the rest of the secrets except for the resumption
3376
     * and exporter secret. */
3377
0
    rv = tls13_ComputeApplicationSecrets(ss);
3378
0
    if (rv != SECSuccess) {
3379
0
        LOG_ERROR(ss, PORT_GetError());
3380
0
        return SECFailure;
3381
0
    }
3382
3383
0
    rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
3384
0
                             ssl_secret_write, PR_FALSE);
3385
0
    if (rv != SECSuccess) {
3386
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
3387
0
        return SECFailure;
3388
0
    }
3389
3390
0
    if (IS_DTLS(ss)) {
3391
        /* We need this for reading ACKs. */
3392
0
        ssl_CipherSpecAddRef(ss->ssl3.crSpec);
3393
0
    }
3394
0
    if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
3395
0
        rv = tls13_SetCipherSpec(ss, TrafficKeyEarlyApplicationData,
3396
0
                                 ssl_secret_read, PR_TRUE);
3397
0
        if (rv != SECSuccess) {
3398
0
            LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
3399
0
            return SECFailure;
3400
0
        }
3401
0
        TLS13_SET_HS_STATE(ss, wait_end_of_early_data);
3402
0
    } else {
3403
0
        PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none ||
3404
0
                    ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored);
3405
3406
0
        rv = tls13_SetCipherSpec(ss,
3407
0
                                 TrafficKeyHandshake,
3408
0
                                 ssl_secret_read, PR_FALSE);
3409
0
        if (rv != SECSuccess) {
3410
0
            LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
3411
0
            return SECFailure;
3412
0
        }
3413
0
        if (tls13_ShouldRequestClientAuth(ss)) {
3414
0
            TLS13_SET_HS_STATE(ss, wait_client_cert);
3415
0
        } else {
3416
0
            TLS13_SET_HS_STATE(ss, wait_finished);
3417
0
        }
3418
0
    }
3419
3420
    /* Here we set a baseline value for our RTT estimation.
3421
     * This value is updated when we get a response from the client. */
3422
0
    ss->ssl3.hs.rttEstimate = ssl_Time(ss);
3423
0
    return SECSuccess;
3424
0
}
3425
3426
SECStatus
3427
tls13_HandleServerHelloPart2(sslSocket *ss, const PRUint8 *savedMsg, PRUint32 savedLength)
3428
1.51k
{
3429
1.51k
    SECStatus rv;
3430
1.51k
    sslSessionID *sid = ss->sec.ci.sid;
3431
1.51k
    SSL3Statistics *ssl3stats = SSL_GetStatistics();
3432
3433
1.51k
    if (ssl3_ExtensionNegotiated(ss, ssl_tls13_pre_shared_key_xtn)) {
3434
9
        PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
3435
9
        PORT_Assert(ss->xtnData.selectedPsk);
3436
3437
9
        if (ss->xtnData.selectedPsk->type != ssl_psk_resume) {
3438
9
            ss->statelessResume = PR_FALSE;
3439
9
        }
3440
1.50k
    } else {
3441
        /* We may have offered a PSK. If the server didn't negotiate
3442
         * it, clear this state to re-extract the Early Secret. */
3443
1.50k
        if (ss->ssl3.hs.currentSecret) {
3444
            /* We might have dropped incompatible PSKs on HRR
3445
             * (see RFC8466, Section 4.1.4). */
3446
753
            PORT_Assert(ss->ssl3.hs.helloRetry ||
3447
753
                        ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn));
3448
753
            PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
3449
753
            ss->ssl3.hs.currentSecret = NULL;
3450
753
        }
3451
1.50k
        ss->statelessResume = PR_FALSE;
3452
1.50k
        ss->xtnData.selectedPsk = NULL;
3453
1.50k
    }
3454
3455
1.51k
    if (ss->statelessResume) {
3456
0
        PORT_Assert(sid->version >= SSL_LIBRARY_VERSION_TLS_1_3);
3457
0
        if (tls13_GetHash(ss) !=
3458
0
            tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite)) {
3459
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO,
3460
0
                        illegal_parameter);
3461
0
            return SECFailure;
3462
0
        }
3463
0
    }
3464
3465
    /* Now create a synthetic kea_def that we can tweak. */
3466
1.51k
    ss->ssl3.hs.kea_def_mutable = *ss->ssl3.hs.kea_def;
3467
1.51k
    ss->ssl3.hs.kea_def = &ss->ssl3.hs.kea_def_mutable;
3468
3469
1.51k
    if (ss->xtnData.selectedPsk) {
3470
9
        ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk;
3471
9
        if (ss->statelessResume) {
3472
0
            tls13_RestoreCipherInfo(ss, sid);
3473
0
            if (sid->peerCert) {
3474
0
                ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
3475
0
            }
3476
3477
0
            SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_cache_hits);
3478
0
            SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_stateless_resumes);
3479
9
        } else {
3480
9
            ss->sec.authType = ssl_auth_psk;
3481
9
        }
3482
1.50k
    } else {
3483
1.50k
        if (ss->statelessResume &&
3484
1.50k
            ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)) {
3485
0
            SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_cache_misses);
3486
0
        }
3487
1.50k
        if (sid->cached == in_client_cache) {
3488
            /* If we tried to resume and failed, let's not try again. */
3489
0
            ssl_UncacheSessionID(ss);
3490
0
        }
3491
1.50k
    }
3492
3493
    /* Discard current SID and make a new one, though it may eventually
3494
     * end up looking a lot like the old one.
3495
     */
3496
1.51k
    ssl_FreeSID(sid);
3497
1.51k
    ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
3498
1.51k
    if (sid == NULL) {
3499
0
        FATAL_ERROR(ss, PORT_GetError(), internal_error);
3500
0
        return SECFailure;
3501
0
    }
3502
1.51k
    if (ss->statelessResume) {
3503
0
        PORT_Assert(ss->sec.peerCert);
3504
0
        sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
3505
0
    }
3506
1.51k
    sid->version = ss->version;
3507
3508
1.51k
    rv = tls13_HandleServerKeyShare(ss);
3509
1.51k
    if (rv != SECSuccess) {
3510
77
        return SECFailure;
3511
77
    }
3512
3513
1.43k
    rv = tls13_ComputeHandshakeSecret(ss);
3514
1.43k
    if (rv != SECSuccess) {
3515
0
        return SECFailure; /* error code is set. */
3516
0
    }
3517
3518
1.43k
    rv = tls13_MaybeHandleEchSignal(ss, savedMsg, savedLength, PR_FALSE);
3519
1.43k
    if (rv != SECSuccess) {
3520
0
        return SECFailure; /* error code is set. */
3521
0
    }
3522
3523
1.43k
    rv = tls13_ComputeHandshakeSecrets(ss);
3524
1.43k
    if (rv != SECSuccess) {
3525
0
        return SECFailure; /* error code is set. */
3526
0
    }
3527
3528
1.43k
    if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
3529
        /* When we send 0-RTT, we saved the null spec in case we needed it to
3530
         * send another ClientHello in response to a HelloRetryRequest.  Now
3531
         * that we won't be receiving a HelloRetryRequest, release the spec. */
3532
0
        ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_write, TrafficKeyClearText);
3533
0
    }
3534
3535
1.43k
    rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
3536
1.43k
                             ssl_secret_read, PR_FALSE);
3537
1.43k
    if (rv != SECSuccess) {
3538
0
        FATAL_ERROR(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, internal_error);
3539
0
        return SECFailure;
3540
0
    }
3541
1.43k
    TLS13_SET_HS_STATE(ss, wait_encrypted_extensions);
3542
3543
1.43k
    return SECSuccess;
3544
1.43k
}
3545
3546
static void
3547
tls13_SetKeyExchangeType(sslSocket *ss, const sslNamedGroupDef *group)
3548
1.43k
{
3549
1.43k
    ss->sec.keaGroup = group;
3550
1.43k
    switch (group->keaType) {
3551
        /* Note: These overwrite on resumption.... so if you start with ECDH
3552
         * and resume with DH, we report DH. That's fine, since no answer
3553
         * is really right. */
3554
494
        case ssl_kea_ecdh:
3555
494
            ss->ssl3.hs.kea_def_mutable.exchKeyType =
3556
494
                ss->statelessResume ? ssl_kea_ecdh_psk : ssl_kea_ecdh;
3557
494
            ss->sec.keaType = ssl_kea_ecdh;
3558
494
            break;
3559
0
        case ssl_kea_ecdh_hybrid:
3560
0
            ss->ssl3.hs.kea_def_mutable.exchKeyType =
3561
0
                ss->statelessResume ? ssl_kea_ecdh_hybrid_psk : ssl_kea_ecdh_hybrid;
3562
0
            ss->sec.keaType = ssl_kea_ecdh_hybrid;
3563
0
            break;
3564
940
        case ssl_kea_dh:
3565
940
            ss->ssl3.hs.kea_def_mutable.exchKeyType =
3566
940
                ss->statelessResume ? ssl_kea_dh_psk : ssl_kea_dh;
3567
940
            ss->sec.keaType = ssl_kea_dh;
3568
940
            break;
3569
0
        default:
3570
0
            PORT_Assert(0);
3571
1.43k
    }
3572
1.43k
}
3573
3574
/*
3575
 * Called from ssl3_HandleServerHello.
3576
 *
3577
 * Caller must hold Handshake and RecvBuf locks.
3578
 */
3579
static SECStatus
3580
tls13_HandleServerKeyShare(sslSocket *ss)
3581
1.51k
{
3582
1.51k
    SECStatus rv;
3583
1.51k
    TLS13KeyShareEntry *entry;
3584
1.51k
    sslEphemeralKeyPair *keyPair;
3585
1.51k
    PK11SymKey *dheSecret = NULL;
3586
1.51k
    PK11SymKey *kemSecret = NULL;
3587
3588
1.51k
    SSL_TRC(3, ("%d: TLS13[%d]: handle server_key_share handshake",
3589
1.51k
                SSL_GETPID(), ss->fd));
3590
1.51k
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3591
1.51k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3592
3593
    /* This list should have one entry. */
3594
1.51k
    if (PR_CLIST_IS_EMPTY(&ss->xtnData.remoteKeyShares)) {
3595
8
        FATAL_ERROR(ss, SSL_ERROR_MISSING_KEY_SHARE, missing_extension);
3596
8
        return SECFailure;
3597
8
    }
3598
3599
1.50k
    entry = (TLS13KeyShareEntry *)PR_NEXT_LINK(&ss->xtnData.remoteKeyShares);
3600
1.50k
    PORT_Assert(PR_NEXT_LINK(&entry->link) == &ss->xtnData.remoteKeyShares);
3601
3602
    /* Now get our matching key. */
3603
1.50k
    keyPair = ssl_LookupEphemeralKeyPair(ss, entry->group);
3604
1.50k
    if (!keyPair) {
3605
13
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_SHARE, illegal_parameter);
3606
13
        return SECFailure;
3607
13
    }
3608
3609
1.49k
    PORT_Assert(ssl_NamedGroupEnabled(ss, entry->group));
3610
3611
1.49k
    rv = tls13_HandleKeyShare(ss, entry, keyPair->keys,
3612
1.49k
                              tls13_GetHash(ss),
3613
1.49k
                              &dheSecret);
3614
1.49k
    if (rv != SECSuccess) {
3615
56
        goto loser; /* Error code already set. */
3616
56
    }
3617
3618
1.43k
    if (entry->group->keaType == ssl_kea_ecdh_hybrid) {
3619
0
        rv = tls13_HandleKEMCiphertext(ss, entry, keyPair->kemKeys, &kemSecret);
3620
0
        if (rv != SECSuccess) {
3621
0
            goto loser; /* Error set by tls13_HandleKEMCiphertext */
3622
0
        }
3623
0
        switch (entry->group->name) {
3624
0
            case ssl_grp_kem_xyber768d00:
3625
0
                ss->ssl3.hs.dheSecret = PK11_ConcatSymKeys(dheSecret, kemSecret, CKM_HKDF_DERIVE, CKA_DERIVE);
3626
0
                break;
3627
0
            case ssl_grp_kem_mlkem768x25519:
3628
0
                ss->ssl3.hs.dheSecret = PK11_ConcatSymKeys(kemSecret, dheSecret, CKM_HKDF_DERIVE, CKA_DERIVE);
3629
0
                break;
3630
0
            default:
3631
0
                PORT_Assert(0);
3632
0
                PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3633
0
                ss->ssl3.hs.dheSecret = NULL;
3634
0
                break;
3635
0
        }
3636
0
        if (!ss->ssl3.hs.dheSecret) {
3637
0
            goto loser; /* Error set by PK11_ConcatSymKeys */
3638
0
        }
3639
0
        PK11_FreeSymKey(dheSecret);
3640
0
        PK11_FreeSymKey(kemSecret);
3641
1.43k
    } else {
3642
1.43k
        ss->ssl3.hs.dheSecret = dheSecret;
3643
1.43k
    }
3644
3645
1.43k
    tls13_SetKeyExchangeType(ss, entry->group);
3646
1.43k
    ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->keys->pubKey);
3647
3648
1.43k
    return SECSuccess;
3649
3650
56
loser:
3651
56
    PK11_FreeSymKey(dheSecret);
3652
56
    PK11_FreeSymKey(kemSecret);
3653
56
    FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
3654
56
    return SECFailure;
3655
1.43k
}
3656
3657
static PRBool
3658
tls13_FindCompressionAlgAndCheckIfSupportsEncoding(sslSocket *ss)
3659
0
{
3660
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3661
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3662
3663
0
    for (int j = 0; j < ss->ssl3.supportedCertCompressionAlgorithmsCount; j++) {
3664
0
        if (ss->ssl3.supportedCertCompressionAlgorithms[j].id == ss->xtnData.compressionAlg) {
3665
0
            if (ss->ssl3.supportedCertCompressionAlgorithms[j].encode != NULL) {
3666
0
                return PR_TRUE;
3667
0
            }
3668
0
            return PR_FALSE;
3669
0
        }
3670
0
    }
3671
3672
0
    return PR_FALSE;
3673
0
}
3674
3675
static SECStatus
3676
tls13_FindCompressionAlgAndEncodeCertificate(
3677
    sslSocket *ss, SECItem *certificateToEncode, SECItem *encodedCertificate)
3678
0
{
3679
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3680
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3681
3682
0
    SECStatus rv = SECFailure;
3683
0
    for (int j = 0; j < ss->ssl3.supportedCertCompressionAlgorithmsCount; j++) {
3684
0
        if (ss->ssl3.supportedCertCompressionAlgorithms[j].id == ss->xtnData.compressionAlg &&
3685
0
            ss->ssl3.supportedCertCompressionAlgorithms[j].encode != NULL) {
3686
0
            rv = ss->ssl3.supportedCertCompressionAlgorithms[j].encode(
3687
0
                certificateToEncode, encodedCertificate);
3688
0
            return rv;
3689
0
        }
3690
0
    }
3691
3692
0
    PORT_SetError(SEC_ERROR_CERTIFICATE_COMPRESSION_ALGORITHM_NOT_SUPPORTED);
3693
0
    return SECFailure;
3694
0
}
3695
3696
static SECStatus
3697
tls13_SendCompressedCertificate(sslSocket *ss, sslBuffer *bufferCertificate)
3698
0
{
3699
    /* TLS Certificate Compression. RFC 8879 */
3700
    /* As the encoding function takes as input a SECItem,
3701
     * we convert bufferCertificate to certificateToEncode.
3702
     *
3703
     * encodedCertificate is used to store the certificate
3704
     * after encoding.
3705
     */
3706
0
    SECItem encodedCertificate = { siBuffer, NULL, 0 };
3707
0
    SECItem certificateToEncode = { siBuffer, NULL, 0 };
3708
0
    SECStatus rv = SECFailure;
3709
3710
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3711
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3712
3713
0
    SSL_TRC(30, ("%d: TLS13[%d]: %s is encoding the certificate using the %s compression algorithm",
3714
0
                 SSL_GETPID(), ss->fd, SSL_ROLE(ss),
3715
0
                 ssl3_mapCertificateCompressionAlgorithmToName(ss, ss->xtnData.compressionAlg)));
3716
3717
0
    PRINT_BUF(50, (NULL, "The certificate before encoding:",
3718
0
                   bufferCertificate->buf, bufferCertificate->len));
3719
3720
0
    PRUint32 lengthUnencodedMessage = bufferCertificate->len;
3721
0
    rv = ssl3_CopyToSECItem(bufferCertificate, &certificateToEncode);
3722
0
    if (rv != SECSuccess) {
3723
0
        SSL_TRC(50, ("%d: TLS13[%d]: %s has failed encoding the certificate.",
3724
0
                     SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
3725
0
        goto loser; /* Code already set. */
3726
0
    }
3727
3728
0
    rv = tls13_FindCompressionAlgAndEncodeCertificate(ss, &certificateToEncode,
3729
0
                                                      &encodedCertificate);
3730
0
    if (rv != SECSuccess) {
3731
0
        SSL_TRC(50, ("%d: TLS13[%d]: %s has failed encoding the certificate.",
3732
0
                     SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
3733
0
        PORT_SetError(SEC_ERROR_NO_MEMORY);
3734
0
        goto loser; /* Code already set. */
3735
0
    }
3736
3737
    /* The CompressedCertificate message is formed as follows:
3738
     * struct {
3739
     *   CertificateCompressionAlgorithm algorithm;
3740
     *         uint24 uncompressed_length;
3741
     *         opaque compressed_certificate_message<1..2^24-1>;
3742
     *    } CompressedCertificate;
3743
     */
3744
3745
0
    if (encodedCertificate.len < 1) {
3746
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3747
0
        goto loser;
3748
0
    }
3749
3750
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_compressed_certificate,
3751
0
                                    encodedCertificate.len + 2 + 3 + 3);
3752
0
    if (rv != SECSuccess) {
3753
0
        goto loser; /* err set by AppendHandshake. */
3754
0
    }
3755
3756
0
    rv = ssl3_AppendHandshakeNumber(ss, ss->xtnData.compressionAlg, 2);
3757
0
    if (rv != SECSuccess) {
3758
0
        goto loser; /* err set by AppendHandshake. */
3759
0
    }
3760
3761
0
    rv = ssl3_AppendHandshakeNumber(ss, lengthUnencodedMessage, 3);
3762
0
    if (rv != SECSuccess) {
3763
0
        goto loser; /* err set by AppendHandshake. */
3764
0
    }
3765
3766
0
    PRINT_BUF(30, (NULL, "The encoded certificate: ",
3767
0
                   encodedCertificate.data, encodedCertificate.len));
3768
3769
0
    rv = ssl3_AppendHandshakeVariable(ss, encodedCertificate.data, encodedCertificate.len, 3);
3770
0
    if (rv != SECSuccess) {
3771
0
        goto loser; /* err set by AppendHandshake. */
3772
0
    }
3773
3774
0
    SECITEM_FreeItem(&certificateToEncode, PR_FALSE);
3775
0
    SECITEM_FreeItem(&encodedCertificate, PR_FALSE);
3776
0
    return SECSuccess;
3777
3778
0
loser:
3779
0
    SECITEM_FreeItem(&certificateToEncode, PR_FALSE);
3780
0
    SECITEM_FreeItem(&encodedCertificate, PR_FALSE);
3781
0
    return SECFailure;
3782
0
}
3783
3784
/*
3785
 *    opaque ASN1Cert<1..2^24-1>;
3786
 *
3787
 *    struct {
3788
 *        ASN1Cert cert_data;
3789
 *        Extension extensions<0..2^16-1>;
3790
 *    } CertificateEntry;
3791
 *
3792
 *    struct {
3793
 *        opaque certificate_request_context<0..2^8-1>;
3794
 *        CertificateEntry certificate_list<0..2^24-1>;
3795
 *    } Certificate;
3796
 */
3797
static SECStatus
3798
tls13_SendCertificate(sslSocket *ss)
3799
0
{
3800
0
    SECStatus rv;
3801
0
    CERTCertificateList *certChain;
3802
0
    int certChainLen = 0;
3803
0
    int i;
3804
0
    SECItem context = { siBuffer, NULL, 0 };
3805
0
    sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
3806
0
    sslBuffer bufferCertificate = SSL_BUFFER_EMPTY;
3807
3808
0
    SSL_TRC(3, ("%d: TLS1.3[%d]: send certificate handshake",
3809
0
                SSL_GETPID(), ss->fd));
3810
3811
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3812
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3813
3814
0
    if (ss->sec.isServer) {
3815
0
        PORT_Assert(!ss->sec.localCert);
3816
        /* A server certificate is selected in tls13_SelectServerCert(). */
3817
0
        PORT_Assert(ss->sec.serverCert);
3818
3819
0
        certChain = ss->sec.serverCert->serverCertChain;
3820
0
        ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
3821
0
    } else {
3822
0
        if (ss->sec.localCert)
3823
0
            CERT_DestroyCertificate(ss->sec.localCert);
3824
3825
0
        certChain = ss->ssl3.clientCertChain;
3826
0
        ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
3827
0
    }
3828
3829
0
    if (!ss->sec.isServer) {
3830
0
        PORT_Assert(ss->ssl3.hs.clientCertRequested);
3831
0
        context = ss->xtnData.certReqContext;
3832
0
    }
3833
3834
0
    if (certChain) {
3835
0
        for (i = 0; i < certChain->len; i++) {
3836
            /* Each cert is 3 octet length, cert, and extensions */
3837
0
            certChainLen += 3 + certChain->certs[i].len + 2;
3838
0
        }
3839
3840
        /* Build the extensions. This only applies to the leaf cert, because we
3841
         * don't yet send extensions for non-leaf certs. */
3842
0
        rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_certificate);
3843
0
        if (rv != SECSuccess) {
3844
0
            return SECFailure; /* code already set */
3845
0
        }
3846
        /* extensionBuf.len is only added once, for the leaf cert. */
3847
0
        certChainLen += SSL_BUFFER_LEN(&extensionBuf);
3848
0
    }
3849
3850
0
    rv = sslBuffer_AppendVariable(&bufferCertificate, context.data, context.len, 1);
3851
0
    if (rv != SECSuccess) {
3852
0
        goto loser; /* Code already set. */
3853
0
    }
3854
3855
0
    rv = sslBuffer_AppendNumber(&bufferCertificate, certChainLen, 3);
3856
0
    if (rv != SECSuccess) {
3857
0
        goto loser; /* Code already set. */
3858
0
    }
3859
3860
0
    if (certChain) {
3861
0
        for (i = 0; i < certChain->len; i++) {
3862
0
            rv = sslBuffer_AppendVariable(&bufferCertificate, certChain->certs[i].data,
3863
0
                                          certChain->certs[i].len, 3);
3864
0
            if (rv != SECSuccess) {
3865
0
                goto loser; /* Code already set. */
3866
0
            }
3867
3868
0
            if (i) {
3869
                /* Not end-entity. */
3870
0
                rv = sslBuffer_AppendNumber(&bufferCertificate, 0, 2);
3871
0
                if (rv != SECSuccess) {
3872
0
                    goto loser; /* Code already set. */
3873
0
                }
3874
0
                continue;
3875
0
            }
3876
3877
0
            rv = sslBuffer_AppendBufferVariable(&bufferCertificate, &extensionBuf, 2);
3878
0
            if (rv != SECSuccess) {
3879
0
                goto loser; /* Code already set. */
3880
0
            }
3881
0
        }
3882
0
    }
3883
3884
    /* If no compression mechanism was established or
3885
     * the compression mechanism supports only decoding,
3886
     * we continue as before. */
3887
0
    if (ss->xtnData.compressionAlg == 0 || !tls13_FindCompressionAlgAndCheckIfSupportsEncoding(ss)) {
3888
0
        rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate,
3889
0
                                        1 + context.len + 3 + certChainLen);
3890
0
        if (rv != SECSuccess) {
3891
0
            goto loser; /* err set by AppendHandshake. */
3892
0
        }
3893
0
        rv = ssl3_AppendBufferToHandshake(ss, &bufferCertificate);
3894
0
        if (rv != SECSuccess) {
3895
0
            goto loser; /* err set by AppendHandshake. */
3896
0
        }
3897
0
    } else {
3898
0
        rv = tls13_SendCompressedCertificate(ss, &bufferCertificate);
3899
0
        if (rv != SECSuccess) {
3900
0
            goto loser; /* err set by tls13_SendCompressedCertificate. */
3901
0
        }
3902
0
    }
3903
3904
0
    sslBuffer_Clear(&bufferCertificate);
3905
0
    sslBuffer_Clear(&extensionBuf);
3906
0
    return SECSuccess;
3907
3908
0
loser:
3909
0
    sslBuffer_Clear(&bufferCertificate);
3910
0
    sslBuffer_Clear(&extensionBuf);
3911
0
    return SECFailure;
3912
0
}
3913
3914
static SECStatus
3915
tls13_HandleCertificateEntry(sslSocket *ss, SECItem *data, PRBool first,
3916
                             SECItem *certData)
3917
0
{
3918
0
    SECStatus rv;
3919
0
    SECItem extensionsData;
3920
3921
0
    rv = ssl3_ConsumeHandshakeVariable(ss, certData,
3922
0
                                       3, &data->data, &data->len);
3923
0
    if (rv != SECSuccess) {
3924
0
        return SECFailure;
3925
0
    }
3926
3927
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &extensionsData,
3928
0
                                       2, &data->data, &data->len);
3929
0
    if (rv != SECSuccess) {
3930
0
        return SECFailure;
3931
0
    }
3932
3933
    /* Parse all the extensions. */
3934
0
    if (first && !ss->sec.isServer) {
3935
0
        rv = ssl3_HandleExtensions(ss, &extensionsData.data,
3936
0
                                   &extensionsData.len,
3937
0
                                   ssl_hs_certificate);
3938
0
        if (rv != SECSuccess) {
3939
0
            return SECFailure;
3940
0
        }
3941
        /* TODO(ekr@rtfm.com): Copy out SCTs. Bug 1315727. */
3942
0
    }
3943
3944
0
    return SECSuccess;
3945
0
}
3946
3947
static SECStatus
3948
tls13_EnsureCerticateExpected(sslSocket *ss)
3949
3
{
3950
3
    SECStatus rv = SECFailure;
3951
3
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3952
3
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3953
3954
3
    if (ss->sec.isServer) {
3955
        /* Receiving this message might be the first sign we have that
3956
         * early data is over, so pretend we received EOED. */
3957
0
        rv = tls13_MaybeHandleSuppressedEndOfEarlyData(ss);
3958
0
        if (rv != SECSuccess) {
3959
0
            return SECFailure; /* Code already set. */
3960
0
        }
3961
3962
0
        if (ss->ssl3.clientCertRequested) {
3963
0
            rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,
3964
0
                                      idle_handshake);
3965
0
        } else {
3966
0
            rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,
3967
0
                                      wait_client_cert);
3968
0
        }
3969
3
    } else {
3970
3
        rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,
3971
3
                                  wait_cert_request, wait_server_cert);
3972
3
    }
3973
3
    return rv;
3974
3
}
3975
3976
/* RFC 8879 TLS Certificate Compression
3977
 * struct {
3978
 *  CertificateCompressionAlgorithm algorithm;
3979
 *  uint24 uncompressed_length;
3980
 *  opaque compressed_certificate_message<1..2^24-1>;
3981
 * } CompressedCertificate;
3982
 */
3983
static SECStatus
3984
tls13_HandleCertificateDecode(sslSocket *ss, PRUint8 *b, PRUint32 length)
3985
2
{
3986
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3987
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3988
3989
2
    SECStatus rv = SECFailure;
3990
3991
2
    if (!ss->xtnData.certificateCompressionAdvertised) {
3992
1
        FATAL_ERROR(ss, SEC_ERROR_UNEXPECTED_COMPRESSED_CERTIFICATE, decode_error);
3993
1
        return SECFailure;
3994
1
    }
3995
3996
1
    rv = tls13_EnsureCerticateExpected(ss);
3997
1
    if (rv != SECSuccess) {
3998
1
        return SECFailure; /* Code already set. */
3999
1
    }
4000
4001
0
    if (ss->firstHsDone) {
4002
0
        rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_compressed_certificate, b, length);
4003
0
        if (rv != SECSuccess) {
4004
0
            return rv;
4005
0
        }
4006
0
    }
4007
4008
0
    SSL_TRC(30, ("%d: TLS1.3[%d]: %s handles certificate compression handshake",
4009
0
                 SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
4010
4011
0
    PRINT_BUF(50, (NULL, "The certificate before decoding:", b, length));
4012
    /* Reading CertificateCompressionAlgorithm. */
4013
0
    PRUint32 compressionAlg = 0;
4014
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &compressionAlg, 2, &b, &length);
4015
0
    if (rv != SECSuccess) {
4016
0
        return SECFailure; /* Alert already sent. */
4017
0
    }
4018
4019
0
    PRBool compressionAlgorithmIsSupported = PR_FALSE;
4020
0
    SECStatus (*certificateDecodingFunc)(const SECItem *,
4021
0
                                         unsigned char *output, size_t outputLen, size_t *usedLen) = NULL;
4022
0
    for (int i = 0; i < ss->ssl3.supportedCertCompressionAlgorithmsCount; i++) {
4023
0
        if (ss->ssl3.supportedCertCompressionAlgorithms[i].id == compressionAlg) {
4024
0
            compressionAlgorithmIsSupported = PR_TRUE;
4025
0
            certificateDecodingFunc = ss->ssl3.supportedCertCompressionAlgorithms[i].decode;
4026
0
        }
4027
0
    }
4028
4029
    /* Peer selected a compression algorithm we do not support (and did not advertise). */
4030
0
    if (!compressionAlgorithmIsSupported) {
4031
0
        PORT_SetError(SEC_ERROR_CERTIFICATE_COMPRESSION_ALGORITHM_NOT_SUPPORTED);
4032
0
        FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
4033
0
        return SECFailure;
4034
0
    }
4035
4036
    /* The algorithm does not support decoding. */
4037
0
    if (certificateDecodingFunc == NULL) {
4038
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4039
0
        FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
4040
0
        return SECFailure;
4041
0
    }
4042
4043
0
    SSL_TRC(30, ("%d: TLS13[%d]: %s is decoding the certificate using the %s compression algorithm",
4044
0
                 SSL_GETPID(), ss->fd, SSL_ROLE(ss),
4045
0
                 ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg)));
4046
0
    PRUint32 decodedCertLen = 0;
4047
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &decodedCertLen, 3, &b, &length);
4048
0
    if (rv != SECSuccess) {
4049
0
        return SECFailure; /* alert has been sent */
4050
0
    }
4051
4052
    /*  If the received CompressedCertificate message cannot be decompressed,
4053
     *  he connection MUST be terminated with the "bad_certificate" alert.
4054
     */
4055
0
    if (decodedCertLen == 0) {
4056
0
        SSL_TRC(50, ("%d: TLS13[%d]: %s decoded certificate length is incorrect",
4057
0
                     SSL_GETPID(), ss->fd, SSL_ROLE(ss),
4058
0
                     ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg)));
4059
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate);
4060
0
        return SECFailure;
4061
0
    }
4062
4063
    /* opaque compressed_certificate_message<1..2^24-1>; */
4064
0
    PRUint32 compressedCertLen = 0;
4065
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &compressedCertLen, 3, &b, &length);
4066
0
    if (rv != SECSuccess) {
4067
0
        return SECFailure; /* alert has been sent */
4068
0
    }
4069
4070
0
    if (compressedCertLen == 0 || compressedCertLen != length) {
4071
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate);
4072
0
        return SECFailure;
4073
0
    }
4074
4075
    /* Decoding received certificate. */
4076
0
    PRUint8 *decodedCert = PORT_ZAlloc(decodedCertLen);
4077
0
    if (!decodedCert) {
4078
0
        return SECFailure;
4079
0
    }
4080
4081
0
    size_t actualCertLen = 0;
4082
4083
0
    SECItem encodedCertAsSecItem = { siBuffer, b, compressedCertLen };
4084
0
    rv = certificateDecodingFunc(&encodedCertAsSecItem,
4085
0
                                 decodedCert, decodedCertLen, &actualCertLen);
4086
4087
0
    if (rv != SECSuccess) {
4088
0
        SSL_TRC(50, ("%d: TLS13[%d]: %s decoding of the certificate has failed",
4089
0
                     SSL_GETPID(), ss->fd, SSL_ROLE(ss),
4090
0
                     ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg)));
4091
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate);
4092
0
        goto loser;
4093
0
    }
4094
0
    PRINT_BUF(60, (ss, "consume bytes:", b, compressedCertLen));
4095
0
    *b += compressedCertLen;
4096
0
    length -= compressedCertLen;
4097
4098
    /*  If, after decompression, the specified length does not match the actual length,
4099
     *  the party receiving the invalid message MUST abort the connection
4100
     *  with the "bad_certificate" alert.
4101
     */
4102
0
    if (actualCertLen != decodedCertLen) {
4103
0
        SSL_TRC(50, ("%d: TLS13[%d]: %s certificate length does not correspond to extension length",
4104
0
                     SSL_GETPID(), ss->fd, SSL_ROLE(ss),
4105
0
                     ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg)));
4106
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate);
4107
0
        goto loser;
4108
0
    }
4109
4110
0
    PRINT_BUF(50, (NULL, "Decoded certificate",
4111
0
                   decodedCert, decodedCertLen));
4112
4113
    /* compressed_certificate_message:  The result of applying the indicated
4114
     * compression algorithm to the encoded Certificate message that
4115
     *  would have been sent if certificate compression was not in use.
4116
     *
4117
     * After decompression, the Certificate message MUST be processed as if
4118
     * it were encoded without being compressed.  This way, the parsing and
4119
     * the verification have the same security properties as they would have
4120
     * in TLS normally.
4121
     */
4122
0
    rv = tls13_HandleCertificate(ss, decodedCert, decodedCertLen, PR_TRUE);
4123
0
    if (rv != SECSuccess) {
4124
0
        goto loser;
4125
0
    }
4126
    /* We allow only one compressed certificate to be handled after each
4127
       certificate compression advertisement.
4128
       See test CertificateCompression_TwoEncodedCertificateRequests. */
4129
0
    ss->xtnData.certificateCompressionAdvertised = PR_FALSE;
4130
0
    PORT_Free(decodedCert);
4131
0
    return SECSuccess;
4132
4133
0
loser:
4134
0
    PORT_Free(decodedCert);
4135
0
    return SECFailure;
4136
0
}
4137
4138
/* Called from tls13_CompleteHandleHandshakeMessage() when it has deciphered a complete
4139
 * tls13 Certificate message.
4140
 * Caller must hold Handshake and RecvBuf locks.
4141
 */
4142
static SECStatus
4143
tls13_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length, PRBool alreadyHashed)
4144
2
{
4145
2
    SECStatus rv;
4146
2
    SECItem context = { siBuffer, NULL, 0 };
4147
2
    SECItem certList;
4148
2
    PRBool first = PR_TRUE;
4149
2
    ssl3CertNode *lastCert = NULL;
4150
4151
2
    SSL_TRC(3, ("%d: TLS13[%d]: handle certificate handshake",
4152
2
                SSL_GETPID(), ss->fd));
4153
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4154
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4155
4156
2
    rv = tls13_EnsureCerticateExpected(ss);
4157
2
    if (rv != SECSuccess) {
4158
2
        return SECFailure; /* Code already set. */
4159
2
    }
4160
4161
    /* We can ignore any other cleartext from the client. */
4162
0
    if (ss->sec.isServer && IS_DTLS(ss)) {
4163
0
        ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read, TrafficKeyClearText);
4164
0
        dtls_ReceivedFirstMessageInFlight(ss);
4165
0
    }
4166
4167
    /* AlreadyHashed is true only when Certificate Compression is used. */
4168
0
    if (ss->firstHsDone && !alreadyHashed) {
4169
0
        rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate, b, length);
4170
0
        if (rv != SECSuccess) {
4171
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4172
0
            return SECFailure;
4173
0
        }
4174
0
    }
4175
4176
0
    if (!ss->firstHsDone && ss->sec.isServer) {
4177
        /* Our first shot an getting an RTT estimate.  If the client took extra
4178
         * time to fetch a certificate, this will be bad, but we can't do much
4179
         * about that. */
4180
0
        ss->ssl3.hs.rttEstimate = ssl_Time(ss) - ss->ssl3.hs.rttEstimate;
4181
0
    }
4182
4183
    /* Process the context string */
4184
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &context, 1, &b, &length);
4185
0
    if (rv != SECSuccess)
4186
0
        return SECFailure;
4187
4188
0
    if (ss->ssl3.clientCertRequested) {
4189
0
        PORT_Assert(ss->sec.isServer);
4190
0
        if (SECITEM_CompareItem(&context, &ss->xtnData.certReqContext) != 0) {
4191
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, illegal_parameter);
4192
0
            return SECFailure;
4193
0
        }
4194
0
    }
4195
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &certList, 3, &b, &length);
4196
0
    if (rv != SECSuccess) {
4197
0
        return SECFailure;
4198
0
    }
4199
0
    if (length) {
4200
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, illegal_parameter);
4201
0
        return SECFailure;
4202
0
    }
4203
4204
0
    if (!certList.len) {
4205
0
        if (!ss->sec.isServer) {
4206
            /* Servers always need to send some cert. */
4207
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate);
4208
0
            return SECFailure;
4209
0
        } else {
4210
            /* This is TLS's version of a no_certificate alert. */
4211
            /* I'm a server. I've requested a client cert. He hasn't got one. */
4212
0
            rv = ssl3_HandleNoCertificate(ss);
4213
0
            if (rv != SECSuccess) {
4214
0
                return SECFailure;
4215
0
            }
4216
4217
0
            TLS13_SET_HS_STATE(ss, wait_finished);
4218
0
            return SECSuccess;
4219
0
        }
4220
0
    }
4221
4222
    /* Now clean up. */
4223
0
    ssl3_CleanupPeerCerts(ss);
4224
0
    ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
4225
0
    if (ss->ssl3.peerCertArena == NULL) {
4226
0
        FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
4227
0
        return SECFailure;
4228
0
    }
4229
4230
0
    while (certList.len) {
4231
0
        SECItem derCert; // will hold a weak reference into certList
4232
0
        rv = tls13_HandleCertificateEntry(ss, &certList, first,
4233
0
                                          &derCert);
4234
0
        if (rv != SECSuccess) {
4235
0
            ss->xtnData.signedCertTimestamps.len = 0;
4236
0
            return SECFailure;
4237
0
        }
4238
4239
0
        if (first) {
4240
0
            ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &derCert,
4241
0
                                                       NULL, PR_FALSE, PR_TRUE);
4242
0
            if (!ss->sec.peerCert) {
4243
0
                PRErrorCode errCode = PORT_GetError();
4244
0
                switch (errCode) {
4245
0
                    case PR_OUT_OF_MEMORY_ERROR:
4246
0
                    case SEC_ERROR_BAD_DATABASE:
4247
0
                    case SEC_ERROR_NO_MEMORY:
4248
0
                        FATAL_ERROR(ss, errCode, internal_error);
4249
0
                        return SECFailure;
4250
0
                    default:
4251
0
                        ssl3_SendAlertForCertError(ss, errCode);
4252
0
                        return SECFailure;
4253
0
                }
4254
0
            }
4255
4256
0
            if (ss->xtnData.signedCertTimestamps.len) {
4257
0
                sslSessionID *sid = ss->sec.ci.sid;
4258
0
                rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps,
4259
0
                                      &ss->xtnData.signedCertTimestamps);
4260
0
                ss->xtnData.signedCertTimestamps.len = 0;
4261
0
                if (rv != SECSuccess) {
4262
0
                    FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
4263
0
                    return SECFailure;
4264
0
                }
4265
0
            }
4266
0
        } else {
4267
0
            ssl3CertNode *c = PORT_ArenaNew(ss->ssl3.peerCertArena,
4268
0
                                            ssl3CertNode);
4269
0
            if (!c) {
4270
0
                FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
4271
0
                return SECFailure;
4272
0
            }
4273
0
            c->derCert = SECITEM_ArenaDupItem(ss->ssl3.peerCertArena,
4274
0
                                              &derCert);
4275
0
            c->next = NULL;
4276
4277
0
            if (lastCert) {
4278
0
                lastCert->next = c;
4279
0
            } else {
4280
0
                ss->ssl3.peerCertChain = c;
4281
0
            }
4282
0
            lastCert = c;
4283
0
        }
4284
4285
0
        first = PR_FALSE;
4286
0
    }
4287
0
    SECKEY_UpdateCertPQG(ss->sec.peerCert);
4288
4289
0
    return ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
4290
0
}
4291
4292
/* Add context to the hash functions as described in
4293
   [draft-ietf-tls-tls13; Section 4.9.1] */
4294
SECStatus
4295
tls13_AddContextToHashes(sslSocket *ss, const SSL3Hashes *hashes,
4296
                         SSLHashType algorithm, PRBool sending,
4297
                         SSL3Hashes *tbsHash)
4298
0
{
4299
0
    SECStatus rv = SECSuccess;
4300
0
    PK11Context *ctx;
4301
0
    const unsigned char context_padding[] = {
4302
0
        0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4303
0
        0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4304
0
        0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4305
0
        0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4306
0
        0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4307
0
        0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4308
0
        0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4309
0
        0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20
4310
0
    };
4311
4312
0
    const char *client_cert_verify_string = "TLS 1.3, client CertificateVerify";
4313
0
    const char *server_cert_verify_string = "TLS 1.3, server CertificateVerify";
4314
0
    const char *context_string = (sending ^ ss->sec.isServer) ? client_cert_verify_string
4315
0
                                                              : server_cert_verify_string;
4316
0
    unsigned int hashlength;
4317
4318
    /* Double check that we are doing the same hash.*/
4319
0
    PORT_Assert(hashes->len == tls13_GetHashSize(ss));
4320
4321
0
    ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(algorithm));
4322
0
    if (!ctx) {
4323
0
        PORT_SetError(SEC_ERROR_NO_MEMORY);
4324
0
        goto loser;
4325
0
    }
4326
4327
0
    PORT_Assert(SECFailure);
4328
0
    PORT_Assert(!SECSuccess);
4329
4330
0
    PRINT_BUF(50, (ss, "TLS 1.3 hash without context", hashes->u.raw, hashes->len));
4331
0
    PRINT_BUF(50, (ss, "Context string", context_string, strlen(context_string)));
4332
0
    rv |= PK11_DigestBegin(ctx);
4333
0
    rv |= PK11_DigestOp(ctx, context_padding, sizeof(context_padding));
4334
0
    rv |= PK11_DigestOp(ctx, (unsigned char *)context_string,
4335
0
                        strlen(context_string) + 1); /* +1 includes the terminating 0 */
4336
0
    rv |= PK11_DigestOp(ctx, hashes->u.raw, hashes->len);
4337
    /* Update the hash in-place */
4338
0
    rv |= PK11_DigestFinal(ctx, tbsHash->u.raw, &hashlength, sizeof(tbsHash->u.raw));
4339
0
    PK11_DestroyContext(ctx, PR_TRUE);
4340
0
    PRINT_BUF(50, (ss, "TLS 1.3 hash with context", tbsHash->u.raw, hashlength));
4341
4342
0
    tbsHash->len = hashlength;
4343
0
    tbsHash->hashAlg = algorithm;
4344
4345
0
    if (rv) {
4346
0
        ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4347
0
        goto loser;
4348
0
    }
4349
0
    return SECSuccess;
4350
4351
0
loser:
4352
0
    return SECFailure;
4353
0
}
4354
4355
/*
4356
 *    Derive-Secret(Secret, Label, Messages) =
4357
 *       HKDF-Expand-Label(Secret, Label,
4358
 *                         Hash(Messages) + Hash(resumption_context), L))
4359
 */
4360
SECStatus
4361
tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key,
4362
                   const char *label,
4363
                   unsigned int labelLen,
4364
                   const SSL3Hashes *hashes,
4365
                   PK11SymKey **dest,
4366
                   SSLHashType hash)
4367
9.73k
{
4368
9.73k
    SECStatus rv;
4369
4370
9.73k
    rv = tls13_HkdfExpandLabel(key, hash, hashes->u.raw, hashes->len,
4371
9.73k
                               label, labelLen, CKM_HKDF_DERIVE,
4372
9.73k
                               tls13_GetHashSizeForHash(hash),
4373
9.73k
                               ss->protocolVariant, dest);
4374
9.73k
    if (rv != SECSuccess) {
4375
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
4376
0
        return SECFailure;
4377
0
    }
4378
9.73k
    return SECSuccess;
4379
9.73k
}
4380
4381
/* Convenience wrapper for the empty hash. */
4382
SECStatus
4383
tls13_DeriveSecretNullHash(sslSocket *ss, PK11SymKey *key,
4384
                           const char *label,
4385
                           unsigned int labelLen,
4386
                           PK11SymKey **dest,
4387
                           SSLHashType hash)
4388
6.86k
{
4389
6.86k
    SSL3Hashes hashes;
4390
6.86k
    SECStatus rv;
4391
6.86k
    PRUint8 buf[] = { 0 };
4392
4393
6.86k
    rv = tls13_ComputeHash(ss, &hashes, buf, 0, hash);
4394
6.86k
    if (rv != SECSuccess) {
4395
0
        return SECFailure;
4396
0
    }
4397
4398
6.86k
    return tls13_DeriveSecret(ss, key, label, labelLen, &hashes, dest, hash);
4399
6.86k
}
4400
4401
/* Convenience wrapper that lets us supply a separate prefix and suffix. */
4402
static SECStatus
4403
tls13_DeriveSecretWrap(sslSocket *ss, PK11SymKey *key,
4404
                       const char *prefix,
4405
                       const char *suffix,
4406
                       const char *keylogLabel,
4407
                       PK11SymKey **dest)
4408
2.86k
{
4409
2.86k
    SECStatus rv;
4410
2.86k
    SSL3Hashes hashes;
4411
2.86k
    char buf[100];
4412
2.86k
    const char *label;
4413
4414
2.86k
    if (prefix) {
4415
2.86k
        if ((strlen(prefix) + strlen(suffix) + 2) > sizeof(buf)) {
4416
0
            PORT_Assert(0);
4417
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4418
0
            return SECFailure;
4419
0
        }
4420
2.86k
        (void)PR_snprintf(buf, sizeof(buf), "%s %s",
4421
2.86k
                          prefix, suffix);
4422
2.86k
        label = buf;
4423
2.86k
    } else {
4424
0
        label = suffix;
4425
0
    }
4426
4427
2.86k
    SSL_TRC(3, ("%d: TLS13[%d]: deriving secret '%s'",
4428
2.86k
                SSL_GETPID(), ss->fd, label));
4429
2.86k
    rv = tls13_ComputeHandshakeHashes(ss, &hashes);
4430
2.86k
    if (rv != SECSuccess) {
4431
0
        PORT_Assert(0); /* Should never fail */
4432
0
        ssl_MapLowLevelError(SEC_ERROR_LIBRARY_FAILURE);
4433
0
        return SECFailure;
4434
0
    }
4435
4436
2.86k
    rv = tls13_DeriveSecret(ss, key, label, strlen(label),
4437
2.86k
                            &hashes, dest, tls13_GetHash(ss));
4438
2.86k
    if (rv != SECSuccess) {
4439
0
        return SECFailure;
4440
0
    }
4441
4442
2.86k
    if (keylogLabel) {
4443
2.86k
        ssl3_RecordKeyLog(ss, keylogLabel, *dest);
4444
2.86k
    }
4445
2.86k
    return SECSuccess;
4446
2.86k
}
4447
4448
SECStatus
4449
SSLExp_SecretCallback(PRFileDesc *fd, SSLSecretCallback cb, void *arg)
4450
0
{
4451
0
    sslSocket *ss = ssl_FindSocket(fd);
4452
0
    if (!ss) {
4453
0
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SecretCallback",
4454
0
                 SSL_GETPID(), fd));
4455
0
        return SECFailure;
4456
0
    }
4457
4458
0
    ssl_Get1stHandshakeLock(ss);
4459
0
    ssl_GetSSL3HandshakeLock(ss);
4460
0
    ss->secretCallback = cb;
4461
0
    ss->secretCallbackArg = arg;
4462
0
    ssl_ReleaseSSL3HandshakeLock(ss);
4463
0
    ssl_Release1stHandshakeLock(ss);
4464
0
    return SECSuccess;
4465
0
}
4466
4467
/* Derive traffic keys for the next cipher spec in the queue. */
4468
static SECStatus
4469
tls13_DeriveTrafficKeys(sslSocket *ss, ssl3CipherSpec *spec,
4470
                        TrafficKeyType type,
4471
                        PRBool deleteSecret)
4472
1.60k
{
4473
1.60k
    size_t keySize = spec->cipherDef->key_size;
4474
1.60k
    size_t ivSize = spec->cipherDef->iv_size +
4475
1.60k
                    spec->cipherDef->explicit_nonce_size; /* This isn't always going to
4476
                                                           * work, but it does for
4477
                                                           * AES-GCM */
4478
1.60k
    CK_MECHANISM_TYPE bulkAlgorithm = ssl3_Alg2Mech(spec->cipherDef->calg);
4479
1.60k
    PK11SymKey **prkp = NULL;
4480
1.60k
    PK11SymKey *prk = NULL;
4481
1.60k
    PRBool clientSecret;
4482
1.60k
    SECStatus rv;
4483
    /* These labels are just used for debugging. */
4484
1.60k
    static const char kHkdfPhaseEarlyApplicationDataKeys[] = "early application data";
4485
1.60k
    static const char kHkdfPhaseHandshakeKeys[] = "handshake data";
4486
1.60k
    static const char kHkdfPhaseApplicationDataKeys[] = "application data";
4487
4488
1.60k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4489
4490
1.60k
    clientSecret = !tls13_UseServerSecret(ss, spec->direction);
4491
1.60k
    switch (type) {
4492
0
        case TrafficKeyEarlyApplicationData:
4493
0
            PORT_Assert(clientSecret);
4494
0
            prkp = &ss->ssl3.hs.clientEarlyTrafficSecret;
4495
0
            spec->phase = kHkdfPhaseEarlyApplicationDataKeys;
4496
0
            break;
4497
1.60k
        case TrafficKeyHandshake:
4498
1.60k
            prkp = clientSecret ? &ss->ssl3.hs.clientHsTrafficSecret
4499
1.60k
                                : &ss->ssl3.hs.serverHsTrafficSecret;
4500
1.60k
            spec->phase = kHkdfPhaseHandshakeKeys;
4501
1.60k
            break;
4502
0
        case TrafficKeyApplicationData:
4503
0
            prkp = clientSecret ? &ss->ssl3.hs.clientTrafficSecret
4504
0
                                : &ss->ssl3.hs.serverTrafficSecret;
4505
0
            spec->phase = kHkdfPhaseApplicationDataKeys;
4506
0
            break;
4507
0
        default:
4508
0
            LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
4509
0
            PORT_Assert(0);
4510
0
            return SECFailure;
4511
1.60k
    }
4512
1.60k
    PORT_Assert(prkp != NULL);
4513
1.60k
    prk = *prkp;
4514
4515
1.60k
    SSL_TRC(3, ("%d: TLS13[%d]: deriving %s traffic keys epoch=%d (%s)",
4516
1.60k
                SSL_GETPID(), ss->fd, SPEC_DIR(spec),
4517
1.60k
                spec->epoch, spec->phase));
4518
4519
1.60k
    rv = tls13_HkdfExpandLabel(prk, tls13_GetHash(ss),
4520
1.60k
                               NULL, 0,
4521
1.60k
                               kHkdfPurposeKey, strlen(kHkdfPurposeKey),
4522
1.60k
                               bulkAlgorithm, keySize,
4523
1.60k
                               ss->protocolVariant,
4524
1.60k
                               &spec->keyMaterial.key);
4525
1.60k
    if (rv != SECSuccess) {
4526
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
4527
0
        PORT_Assert(0);
4528
0
        goto loser;
4529
0
    }
4530
4531
1.60k
    if (IS_DTLS(ss) && spec->epoch > 0) {
4532
1.60k
        rv = ssl_CreateMaskingContextInner(spec->version, ss->ssl3.hs.cipher_suite,
4533
1.60k
                                           ss->protocolVariant, prk, kHkdfPurposeSn,
4534
1.60k
                                           strlen(kHkdfPurposeSn), &spec->maskContext);
4535
1.60k
        if (rv != SECSuccess) {
4536
0
            LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
4537
0
            PORT_Assert(0);
4538
0
            goto loser;
4539
0
        }
4540
1.60k
    }
4541
4542
1.60k
    rv = tls13_HkdfExpandLabelRaw(prk, tls13_GetHash(ss),
4543
1.60k
                                  NULL, 0,
4544
1.60k
                                  kHkdfPurposeIv, strlen(kHkdfPurposeIv),
4545
1.60k
                                  ss->protocolVariant,
4546
1.60k
                                  spec->keyMaterial.iv, ivSize);
4547
1.60k
    if (rv != SECSuccess) {
4548
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
4549
0
        PORT_Assert(0);
4550
0
        goto loser;
4551
0
    }
4552
4553
1.60k
    if (deleteSecret) {
4554
0
        PK11_FreeSymKey(prk);
4555
0
        *prkp = NULL;
4556
0
    }
4557
1.60k
    return SECSuccess;
4558
4559
0
loser:
4560
0
    return SECFailure;
4561
1.60k
}
4562
4563
void
4564
tls13_SetSpecRecordVersion(sslSocket *ss, ssl3CipherSpec *spec)
4565
4.48k
{
4566
    /* Set the record version to pretend to be (D)TLS 1.2. */
4567
4.48k
    if (IS_DTLS(ss)) {
4568
4.48k
        spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_2_WIRE;
4569
4.48k
    } else {
4570
0
        spec->recordVersion = SSL_LIBRARY_VERSION_TLS_1_2;
4571
0
    }
4572
4.48k
    SSL_TRC(10, ("%d: TLS13[%d]: set spec=%d record version to 0x%04x",
4573
4.48k
                 SSL_GETPID(), ss->fd, spec, spec->recordVersion));
4574
4.48k
}
4575
4576
static SECStatus
4577
tls13_SetupPendingCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
4578
1.60k
{
4579
1.60k
    ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
4580
4581
1.60k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4582
1.60k
    PORT_Assert(spec->epoch);
4583
4584
    /* Version isn't set when we send 0-RTT data. */
4585
1.60k
    spec->version = PR_MAX(SSL_LIBRARY_VERSION_TLS_1_3, ss->version);
4586
4587
1.60k
    ssl_SaveCipherSpec(ss, spec);
4588
    /* We want to keep read cipher specs around longer because
4589
     * there are cases where we might get either epoch N or
4590
     * epoch N+1. */
4591
1.60k
    if (IS_DTLS(ss) && spec->direction == ssl_secret_read) {
4592
1.43k
        ssl_CipherSpecAddRef(spec);
4593
1.43k
    }
4594
4595
1.60k
    SSL_TRC(3, ("%d: TLS13[%d]: Set Pending Cipher Suite to 0x%04x",
4596
1.60k
                SSL_GETPID(), ss->fd, suite));
4597
4598
1.60k
    spec->cipherDef = ssl_GetBulkCipherDef(ssl_LookupCipherSuiteDef(suite));
4599
4600
1.60k
    if (spec->epoch == TrafficKeyEarlyApplicationData) {
4601
0
        if (ss->xtnData.selectedPsk &&
4602
0
            ss->xtnData.selectedPsk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL) {
4603
0
            spec->earlyDataRemaining = ss->xtnData.selectedPsk->maxEarlyData;
4604
0
        }
4605
0
    }
4606
4607
1.60k
    tls13_SetSpecRecordVersion(ss, spec);
4608
4609
    /* The record size limit is reduced by one so that the remainder of the
4610
     * record handling code can use the same checks for all versions. */
4611
1.60k
    if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) {
4612
0
        spec->recordSizeLimit = ((spec->direction == ssl_secret_read)
4613
0
                                     ? ss->opt.recordSizeLimit
4614
0
                                     : ss->xtnData.recordSizeLimit) -
4615
0
                                1;
4616
1.60k
    } else {
4617
1.60k
        spec->recordSizeLimit = MAX_FRAGMENT_LENGTH;
4618
1.60k
    }
4619
1.60k
    return SECSuccess;
4620
1.60k
}
4621
4622
/*
4623
 * Initialize the cipher context. All TLS 1.3 operations are AEAD,
4624
 * so they are all message contexts.
4625
 */
4626
static SECStatus
4627
tls13_InitPendingContext(sslSocket *ss, ssl3CipherSpec *spec)
4628
1.60k
{
4629
1.60k
    CK_MECHANISM_TYPE encMechanism;
4630
1.60k
    CK_ATTRIBUTE_TYPE encMode;
4631
1.60k
    SECItem iv;
4632
1.60k
    SSLCipherAlgorithm calg;
4633
4634
1.60k
    calg = spec->cipherDef->calg;
4635
4636
1.60k
    encMechanism = ssl3_Alg2Mech(calg);
4637
1.60k
    encMode = CKA_NSS_MESSAGE | ((spec->direction == ssl_secret_write) ? CKA_ENCRYPT : CKA_DECRYPT);
4638
1.60k
    iv.data = NULL;
4639
1.60k
    iv.len = 0;
4640
4641
    /*
4642
     * build the context
4643
     */
4644
1.60k
    spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode,
4645
1.60k
                                                     spec->keyMaterial.key,
4646
1.60k
                                                     &iv);
4647
1.60k
    if (!spec->cipherContext) {
4648
0
        ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
4649
0
        return SECFailure;
4650
0
    }
4651
1.60k
    return SECSuccess;
4652
1.60k
}
4653
4654
/*
4655
 * Called before sending alerts to set up the right key on the client.
4656
 * We might encounter errors during the handshake where the current
4657
 * key is ClearText or EarlyApplicationData. This
4658
 * function switches to the Handshake key if possible.
4659
 */
4660
SECStatus
4661
tls13_SetAlertCipherSpec(sslSocket *ss)
4662
4.64k
{
4663
4.64k
    SECStatus rv;
4664
4665
4.64k
    if (ss->sec.isServer) {
4666
0
        return SECSuccess;
4667
0
    }
4668
4.64k
    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
4669
4.20k
        return SECSuccess;
4670
4.20k
    }
4671
439
    if (TLS13_IN_HS_STATE(ss, wait_server_hello)) {
4672
266
        return SECSuccess;
4673
266
    }
4674
173
    if ((ss->ssl3.cwSpec->epoch != TrafficKeyClearText) &&
4675
173
        (ss->ssl3.cwSpec->epoch != TrafficKeyEarlyApplicationData)) {
4676
0
        return SECSuccess;
4677
0
    }
4678
4679
173
    rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
4680
173
                             ssl_secret_write, PR_FALSE);
4681
173
    if (rv != SECSuccess) {
4682
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4683
0
        return SECFailure;
4684
0
    }
4685
173
    return SECSuccess;
4686
173
}
4687
4688
/* Install a new cipher spec for this direction.
4689
 *
4690
 * During the handshake, the values for |epoch| take values from the
4691
 * TrafficKeyType enum.  Afterwards, key update increments them.
4692
 */
4693
static SECStatus
4694
tls13_SetCipherSpec(sslSocket *ss, PRUint16 epoch,
4695
                    SSLSecretDirection direction, PRBool deleteSecret)
4696
1.60k
{
4697
1.60k
    TrafficKeyType type;
4698
1.60k
    SECStatus rv;
4699
1.60k
    ssl3CipherSpec *spec = NULL;
4700
1.60k
    ssl3CipherSpec **specp;
4701
4702
    /* Flush out old handshake data. */
4703
1.60k
    ssl_GetXmitBufLock(ss);
4704
1.60k
    rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
4705
1.60k
    ssl_ReleaseXmitBufLock(ss);
4706
1.60k
    if (rv != SECSuccess) {
4707
0
        return SECFailure;
4708
0
    }
4709
4710
    /* Create the new spec. */
4711
1.60k
    spec = ssl_CreateCipherSpec(ss, direction);
4712
1.60k
    if (!spec) {
4713
0
        return SECFailure;
4714
0
    }
4715
1.60k
    spec->epoch = epoch;
4716
1.60k
    spec->nextSeqNum = 0;
4717
1.60k
    if (IS_DTLS(ss)) {
4718
1.60k
        dtls_InitRecvdRecords(&spec->recvdRecords);
4719
1.60k
    }
4720
4721
    /* This depends on spec having a valid direction and epoch. */
4722
1.60k
    rv = tls13_SetupPendingCipherSpec(ss, spec);
4723
1.60k
    if (rv != SECSuccess) {
4724
0
        goto loser;
4725
0
    }
4726
4727
1.60k
    type = (TrafficKeyType)PR_MIN(TrafficKeyApplicationData, epoch);
4728
1.60k
    rv = tls13_DeriveTrafficKeys(ss, spec, type, deleteSecret);
4729
1.60k
    if (rv != SECSuccess) {
4730
0
        goto loser;
4731
0
    }
4732
4733
1.60k
    rv = tls13_InitPendingContext(ss, spec);
4734
1.60k
    if (rv != SECSuccess) {
4735
0
        goto loser;
4736
0
    }
4737
4738
    /* Now that we've set almost everything up, finally cut over. */
4739
1.60k
    specp = (direction == ssl_secret_read) ? &ss->ssl3.crSpec : &ss->ssl3.cwSpec;
4740
1.60k
    ssl_GetSpecWriteLock(ss);
4741
1.60k
    ssl_CipherSpecRelease(*specp); /* May delete old cipher. */
4742
1.60k
    *specp = spec;                 /* Overwrite. */
4743
1.60k
    ssl_ReleaseSpecWriteLock(ss);
4744
4745
1.60k
    SSL_TRC(3, ("%d: TLS13[%d]: %s installed key for epoch=%d (%s) dir=%s",
4746
1.60k
                SSL_GETPID(), ss->fd, SSL_ROLE(ss), spec->epoch,
4747
1.60k
                spec->phase, SPEC_DIR(spec)));
4748
1.60k
    return SECSuccess;
4749
4750
0
loser:
4751
0
    ssl_CipherSpecRelease(spec);
4752
0
    return SECFailure;
4753
1.60k
}
4754
4755
SECStatus
4756
tls13_ComputeHandshakeHashes(sslSocket *ss, SSL3Hashes *hashes)
4757
2.86k
{
4758
2.86k
    SECStatus rv;
4759
2.86k
    PK11Context *ctx = NULL;
4760
2.86k
    PRBool useEchInner;
4761
2.86k
    sslBuffer *transcript;
4762
4763
2.86k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4764
2.86k
    if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
4765
        /* Backup: if we haven't done any hashing, then hash now.
4766
         * This happens when we are doing 0-RTT on the client. */
4767
0
        ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(tls13_GetHash(ss)));
4768
0
        if (!ctx) {
4769
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4770
0
            return SECFailure;
4771
0
        }
4772
4773
0
        if (PK11_DigestBegin(ctx) != SECSuccess) {
4774
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4775
0
            goto loser;
4776
0
        }
4777
4778
        /* One might expect this to use ss->ssl3.hs.echAccepted,
4779
         * but with 0-RTT we don't know that yet. */
4780
0
        useEchInner = ss->sec.isServer ? PR_FALSE : !!ss->ssl3.hs.echHpkeCtx;
4781
0
        transcript = useEchInner ? &ss->ssl3.hs.echInnerMessages : &ss->ssl3.hs.messages;
4782
4783
0
        PRINT_BUF(10, (ss, "Handshake hash computed over saved messages",
4784
0
                       transcript->buf,
4785
0
                       transcript->len));
4786
4787
0
        if (PK11_DigestOp(ctx,
4788
0
                          transcript->buf,
4789
0
                          transcript->len) != SECSuccess) {
4790
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4791
0
            goto loser;
4792
0
        }
4793
2.86k
    } else {
4794
2.86k
        if (ss->firstHsDone) {
4795
0
            ctx = PK11_CloneContext(ss->ssl3.hs.shaPostHandshake);
4796
2.86k
        } else {
4797
2.86k
            ctx = PK11_CloneContext(ss->ssl3.hs.sha);
4798
2.86k
        }
4799
2.86k
        if (!ctx) {
4800
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4801
0
            return SECFailure;
4802
0
        }
4803
2.86k
    }
4804
4805
2.86k
    rv = PK11_DigestFinal(ctx, hashes->u.raw,
4806
2.86k
                          &hashes->len,
4807
2.86k
                          sizeof(hashes->u.raw));
4808
2.86k
    if (rv != SECSuccess) {
4809
0
        ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4810
0
        goto loser;
4811
0
    }
4812
4813
2.86k
    PRINT_BUF(10, (ss, "Handshake hash", hashes->u.raw, hashes->len));
4814
2.86k
    PORT_Assert(hashes->len == tls13_GetHashSize(ss));
4815
2.86k
    PK11_DestroyContext(ctx, PR_TRUE);
4816
4817
2.86k
    return SECSuccess;
4818
4819
0
loser:
4820
0
    PK11_DestroyContext(ctx, PR_TRUE);
4821
0
    return SECFailure;
4822
2.86k
}
4823
4824
TLS13KeyShareEntry *
4825
tls13_CopyKeyShareEntry(TLS13KeyShareEntry *o)
4826
0
{
4827
0
    TLS13KeyShareEntry *n;
4828
4829
0
    PORT_Assert(o);
4830
0
    n = PORT_ZNew(TLS13KeyShareEntry);
4831
0
    if (!n) {
4832
0
        return NULL;
4833
0
    }
4834
4835
0
    if (SECSuccess != SECITEM_CopyItem(NULL, &n->key_exchange, &o->key_exchange)) {
4836
0
        PORT_Free(n);
4837
0
        return NULL;
4838
0
    }
4839
0
    n->group = o->group;
4840
0
    return n;
4841
0
}
4842
4843
void
4844
tls13_DestroyKeyShareEntry(TLS13KeyShareEntry *offer)
4845
1.54k
{
4846
1.54k
    if (!offer) {
4847
28
        return;
4848
28
    }
4849
1.51k
    SECITEM_ZfreeItem(&offer->key_exchange, PR_FALSE);
4850
1.51k
    PORT_ZFree(offer, sizeof(*offer));
4851
1.51k
}
4852
4853
void
4854
tls13_DestroyKeyShares(PRCList *list)
4855
39.0k
{
4856
39.0k
    PRCList *cur_p;
4857
4858
    /* The list must be initialized. */
4859
39.0k
    PORT_Assert(PR_LIST_HEAD(list));
4860
4861
40.5k
    while (!PR_CLIST_IS_EMPTY(list)) {
4862
1.50k
        cur_p = PR_LIST_TAIL(list);
4863
1.50k
        PR_REMOVE_LINK(cur_p);
4864
1.50k
        tls13_DestroyKeyShareEntry((TLS13KeyShareEntry *)cur_p);
4865
1.50k
    }
4866
39.0k
}
4867
4868
void
4869
tls13_DestroyEarlyData(PRCList *list)
4870
9.36k
{
4871
9.36k
    PRCList *cur_p;
4872
4873
9.36k
    while (!PR_CLIST_IS_EMPTY(list)) {
4874
0
        TLS13EarlyData *msg;
4875
4876
0
        cur_p = PR_LIST_TAIL(list);
4877
0
        msg = (TLS13EarlyData *)cur_p;
4878
4879
0
        PR_REMOVE_LINK(cur_p);
4880
0
        SECITEM_ZfreeItem(&msg->data, PR_FALSE);
4881
0
        PORT_ZFree(msg, sizeof(*msg));
4882
0
    }
4883
9.36k
}
4884
4885
/* draft-ietf-tls-tls13 Section 5.2.2 specifies the following
4886
 * nonce algorithm:
4887
 *
4888
 * The length of the per-record nonce (iv_length) is set to max(8 bytes,
4889
 * N_MIN) for the AEAD algorithm (see [RFC5116] Section 4).  An AEAD
4890
 * algorithm where N_MAX is less than 8 bytes MUST NOT be used with TLS.
4891
 * The per-record nonce for the AEAD construction is formed as follows:
4892
 *
4893
 * 1.  The 64-bit record sequence number is padded to the left with
4894
 *     zeroes to iv_length.
4895
 *
4896
 * 2.  The padded sequence number is XORed with the static
4897
 *     client_write_iv or server_write_iv, depending on the role.
4898
 *
4899
 * The resulting quantity (of length iv_length) is used as the per-
4900
 * record nonce.
4901
 *
4902
 * Existing suites have the same nonce size: N_MIN = N_MAX = 12 bytes
4903
 *
4904
 * See RFC 5288 and https://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305-04#section-2
4905
 */
4906
static void
4907
tls13_WriteNonce(const unsigned char *ivIn, unsigned int ivInLen,
4908
                 const unsigned char *nonce, unsigned int nonceLen,
4909
                 unsigned char *ivOut, unsigned int ivOutLen)
4910
10.9k
{
4911
10.9k
    size_t i;
4912
10.9k
    unsigned int offset = ivOutLen - nonceLen;
4913
4914
10.9k
    PORT_Assert(ivInLen <= ivOutLen);
4915
10.9k
    PORT_Assert(nonceLen <= ivOutLen);
4916
10.9k
    PORT_Memset(ivOut, 0, ivOutLen);
4917
10.9k
    PORT_Memcpy(ivOut, ivIn, ivInLen);
4918
4919
    /* XOR the last n bytes of the IV with the nonce (should be a counter). */
4920
98.3k
    for (i = 0; i < nonceLen; ++i) {
4921
87.4k
        ivOut[offset + i] ^= nonce[i];
4922
87.4k
    }
4923
10.9k
    PRINT_BUF(50, (NULL, "Nonce", ivOut, ivOutLen));
4924
10.9k
}
4925
4926
/* Setup the IV for AEAD encrypt. The PKCS #11 module will add the
4927
 * counter, but it doesn't know about the DTLS epic, so we add it here.
4928
 */
4929
unsigned int
4930
tls13_SetupAeadIv(PRBool isDTLS, SSL3ProtocolVersion v, unsigned char *ivOut, unsigned char *ivIn,
4931
                  unsigned int offset, unsigned int ivLen, DTLSEpoch epoch)
4932
303
{
4933
303
    PORT_Memcpy(ivOut, ivIn, ivLen);
4934
303
    if (isDTLS && v < SSL_LIBRARY_VERSION_TLS_1_3) {
4935
        /* handle the tls 1.2 counter mode case, the epoc is copied
4936
         * instead of xored. We accomplish this by clearing ivOut
4937
         * before running xor. */
4938
130
        if (offset >= ivLen) {
4939
130
            ivOut[offset] = ivOut[offset + 1] = 0;
4940
130
        }
4941
130
        ivOut[offset] ^= (unsigned char)(epoch >> BPB) & 0xff;
4942
130
        ivOut[offset + 1] ^= (unsigned char)(epoch)&0xff;
4943
130
        offset += 2;
4944
130
    }
4945
4946
303
    return offset;
4947
303
}
4948
4949
/*
4950
 * Do a single AEAD for TLS. This differs from PK11_AEADOp in the following
4951
 * ways.
4952
 *   1) If context is not supplied, it treats the operation as a single shot
4953
 *   and creates a context from symKey and mech.
4954
 *   2) It always assumes the tag will be at the end of the buffer
4955
 *   (in on decrypt, out on encrypt) just like the old single shot.
4956
 *   3) If we aren't generating an IV, it uses tls13_WriteNonce to create the
4957
 *   nonce.
4958
 * NOTE is context is supplied, symKey and mech are ignored
4959
 */
4960
SECStatus
4961
tls13_AEAD(PK11Context *context, PRBool decrypt,
4962
           CK_GENERATOR_FUNCTION ivGen, unsigned int fixedbits,
4963
           const unsigned char *ivIn, unsigned char *ivOut, unsigned int ivLen,
4964
           const unsigned char *nonceIn, unsigned int nonceLen,
4965
           const unsigned char *aad, unsigned int aadLen,
4966
           unsigned char *out, unsigned int *outLen, unsigned int maxout,
4967
           unsigned int tagLen, const unsigned char *in, unsigned int inLen)
4968
11.2k
{
4969
11.2k
    unsigned char *tag;
4970
11.2k
    unsigned char iv[MAX_IV_LENGTH];
4971
11.2k
    unsigned char tagbuf[HASH_LENGTH_MAX];
4972
11.2k
    SECStatus rv;
4973
4974
    /* must have either context or the symKey set */
4975
11.2k
    if (!context) {
4976
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
4977
0
        return SECFailure;
4978
0
    }
4979
4980
11.2k
    PORT_Assert(ivLen <= MAX_IV_LENGTH);
4981
11.2k
    PORT_Assert(tagLen <= HASH_LENGTH_MAX);
4982
11.2k
    if (!ivOut) {
4983
10.9k
        ivOut = iv; /* caller doesn't need a returned, iv */
4984
10.9k
    }
4985
4986
11.2k
    if (ivGen == CKG_NO_GENERATE) {
4987
10.9k
        tls13_WriteNonce(ivIn, ivLen, nonceIn, nonceLen, ivOut, ivLen);
4988
10.9k
    } else if (ivIn != ivOut) {
4989
0
        PORT_Memcpy(ivOut, ivIn, ivLen);
4990
0
    }
4991
11.2k
    if (decrypt) {
4992
10.9k
        inLen = inLen - tagLen;
4993
10.9k
        tag = (unsigned char *)in + inLen;
4994
        /* tag is const on decrypt, but returned on encrypt */
4995
10.9k
    } else {
4996
        /* tag is written to a separate buffer, then added to the end
4997
         * of the actual output buffer. This allows output buffer to be larger
4998
         * than the input buffer and everything still work */
4999
303
        tag = tagbuf;
5000
303
    }
5001
11.2k
    rv = PK11_AEADOp(context, ivGen, fixedbits, ivOut, ivLen, aad, aadLen,
5002
11.2k
                     out, (int *)outLen, maxout, tag, tagLen, in, inLen);
5003
    /* on encrypt SSL always puts the tag at the end of the buffer */
5004
11.2k
    if ((rv == SECSuccess) && !(decrypt)) {
5005
303
        unsigned int len = *outLen;
5006
        /* make sure there is still space */
5007
303
        if (len + tagLen > maxout) {
5008
0
            PORT_SetError(SEC_ERROR_OUTPUT_LEN);
5009
0
            return SECFailure;
5010
0
        }
5011
303
        PORT_Memcpy(out + len, tag, tagLen);
5012
303
        *outLen += tagLen;
5013
303
    }
5014
11.2k
    return rv;
5015
11.2k
}
5016
5017
static SECStatus
5018
tls13_HandleEncryptedExtensions(sslSocket *ss, PRUint8 *b, PRUint32 length)
5019
2
{
5020
2
    SECStatus rv;
5021
2
    PRUint32 innerLength;
5022
2
    SECItem oldAlpn = { siBuffer, NULL, 0 };
5023
5024
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
5025
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5026
5027
2
    SSL_TRC(3, ("%d: TLS13[%d]: handle encrypted extensions",
5028
2
                SSL_GETPID(), ss->fd));
5029
5030
2
    rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS,
5031
2
                              wait_encrypted_extensions);
5032
2
    if (rv != SECSuccess) {
5033
2
        return SECFailure;
5034
2
    }
5035
5036
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &innerLength, 2, &b, &length);
5037
0
    if (rv != SECSuccess) {
5038
0
        return SECFailure; /* Alert already sent. */
5039
0
    }
5040
0
    if (innerLength != length) {
5041
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
5042
0
                    illegal_parameter);
5043
0
        return SECFailure;
5044
0
    }
5045
5046
    /* If we are doing 0-RTT, then we already have an ALPN value. Stash
5047
     * it for comparison. */
5048
0
    if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent &&
5049
0
        ss->xtnData.nextProtoState == SSL_NEXT_PROTO_EARLY_VALUE) {
5050
0
        oldAlpn = ss->xtnData.nextProto;
5051
0
        ss->xtnData.nextProto.data = NULL;
5052
0
        ss->xtnData.nextProtoState = SSL_NEXT_PROTO_NO_SUPPORT;
5053
0
    }
5054
5055
0
    rv = ssl3_ParseExtensions(ss, &b, &length);
5056
0
    if (rv != SECSuccess) {
5057
0
        return SECFailure; /* Error code set below */
5058
0
    }
5059
5060
    /* Handle the rest of the extensions. */
5061
0
    rv = ssl3_HandleParsedExtensions(ss, ssl_hs_encrypted_extensions);
5062
0
    if (rv != SECSuccess) {
5063
0
        return SECFailure; /* Error code set below */
5064
0
    }
5065
5066
    /* We can only get here if we offered 0-RTT. */
5067
0
    if (ssl3_ExtensionNegotiated(ss, ssl_tls13_early_data_xtn)) {
5068
0
        PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_sent);
5069
0
        if (!ss->xtnData.selectedPsk) {
5070
            /* Illegal to accept 0-RTT without also accepting PSK. */
5071
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
5072
0
                        illegal_parameter);
5073
0
        }
5074
0
        ss->ssl3.hs.zeroRttState = ssl_0rtt_accepted;
5075
5076
        /* Check that the server negotiated the same ALPN (if any). */
5077
0
        if (SECITEM_CompareItem(&oldAlpn, &ss->xtnData.nextProto)) {
5078
0
            SECITEM_FreeItem(&oldAlpn, PR_FALSE);
5079
0
            FATAL_ERROR(ss, SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID,
5080
0
                        illegal_parameter);
5081
0
            return SECFailure;
5082
0
        }
5083
        /* Check that the server negotiated the same cipher suite. */
5084
0
        if (ss->ssl3.hs.cipher_suite != ss->ssl3.hs.zeroRttSuite) {
5085
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
5086
0
                        illegal_parameter);
5087
0
            return SECFailure;
5088
0
        }
5089
0
    } else if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
5090
        /* Though we sent 0-RTT, the early_data extension wasn't present so the
5091
         * state is unmodified; the server must have rejected 0-RTT. */
5092
0
        ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
5093
0
        ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
5094
0
    } else {
5095
0
        PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none ||
5096
0
                    (ss->ssl3.hs.helloRetry &&
5097
0
                     ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored));
5098
0
    }
5099
5100
0
    SECITEM_FreeItem(&oldAlpn, PR_FALSE);
5101
0
    if (ss->ssl3.hs.kea_def->authKeyType == ssl_auth_psk) {
5102
0
        TLS13_SET_HS_STATE(ss, wait_finished);
5103
0
    } else {
5104
0
        TLS13_SET_HS_STATE(ss, wait_cert_request);
5105
0
    }
5106
5107
    /* Client is done with any PSKs */
5108
0
    tls13_DestroyPskList(&ss->ssl3.hs.psks);
5109
0
    ss->xtnData.selectedPsk = NULL;
5110
5111
0
    return SECSuccess;
5112
0
}
5113
5114
static SECStatus
5115
tls13_SendEncryptedExtensions(sslSocket *ss)
5116
0
{
5117
0
    sslBuffer extensions = SSL_BUFFER_EMPTY;
5118
0
    SECStatus rv;
5119
5120
0
    SSL_TRC(3, ("%d: TLS13[%d]: send encrypted extensions handshake",
5121
0
                SSL_GETPID(), ss->fd));
5122
5123
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5124
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5125
5126
0
    rv = ssl_ConstructExtensions(ss, &extensions, ssl_hs_encrypted_extensions);
5127
0
    if (rv != SECSuccess) {
5128
0
        return SECFailure;
5129
0
    }
5130
5131
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_encrypted_extensions,
5132
0
                                    SSL_BUFFER_LEN(&extensions) + 2);
5133
0
    if (rv != SECSuccess) {
5134
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
5135
0
        goto loser;
5136
0
    }
5137
0
    rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensions, 2);
5138
0
    if (rv != SECSuccess) {
5139
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
5140
0
        goto loser;
5141
0
    }
5142
0
    sslBuffer_Clear(&extensions);
5143
0
    return SECSuccess;
5144
5145
0
loser:
5146
0
    sslBuffer_Clear(&extensions);
5147
0
    return SECFailure;
5148
0
}
5149
5150
SECStatus
5151
tls13_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
5152
0
{
5153
0
    SECStatus rv = SECFailure;
5154
0
    SECItem buf = { siBuffer, NULL, 0 };
5155
0
    unsigned int len;
5156
0
    SSLHashType hashAlg;
5157
0
    SSL3Hashes hash;
5158
0
    SSL3Hashes tbsHash; /* The hash "to be signed". */
5159
5160
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5161
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5162
5163
0
    SSL_TRC(3, ("%d: TLS13[%d]: send certificate_verify handshake",
5164
0
                SSL_GETPID(), ss->fd));
5165
5166
0
    PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single);
5167
0
    rv = tls13_ComputeHandshakeHashes(ss, &hash);
5168
0
    if (rv != SECSuccess) {
5169
0
        return SECFailure;
5170
0
    }
5171
5172
    /* We should have picked a signature scheme when we received a
5173
     * CertificateRequest, or when we picked a server certificate. */
5174
0
    PORT_Assert(ss->ssl3.hs.signatureScheme != ssl_sig_none);
5175
0
    if (ss->ssl3.hs.signatureScheme == ssl_sig_none) {
5176
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5177
0
        return SECFailure;
5178
0
    }
5179
0
    hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
5180
0
    rv = tls13_AddContextToHashes(ss, &hash, hashAlg,
5181
0
                                  PR_TRUE, &tbsHash);
5182
0
    if (rv != SECSuccess) {
5183
0
        return SECFailure;
5184
0
    }
5185
5186
0
    rv = ssl3_SignHashes(ss, &tbsHash, privKey, &buf);
5187
0
    if (rv == SECSuccess && !ss->sec.isServer) {
5188
        /* Remember the info about the slot that did the signing.
5189
         * Later, when doing an SSL restart handshake, verify this.
5190
         * These calls are mere accessors, and can't fail.
5191
         */
5192
0
        PK11SlotInfo *slot;
5193
0
        sslSessionID *sid = ss->sec.ci.sid;
5194
5195
0
        slot = PK11_GetSlotFromPrivateKey(privKey);
5196
0
        sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
5197
0
        sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
5198
0
        sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
5199
0
        sid->u.ssl3.clAuthValid = PR_TRUE;
5200
0
        PK11_FreeSlot(slot);
5201
0
    }
5202
0
    if (rv != SECSuccess) {
5203
0
        goto done; /* err code was set by ssl3_SignHashes */
5204
0
    }
5205
5206
0
    len = buf.len + 2 + 2;
5207
5208
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len);
5209
0
    if (rv != SECSuccess) {
5210
0
        goto done; /* error code set by AppendHandshake */
5211
0
    }
5212
5213
0
    rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
5214
0
    if (rv != SECSuccess) {
5215
0
        goto done; /* err set by AppendHandshakeNumber */
5216
0
    }
5217
5218
0
    rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
5219
0
    if (rv != SECSuccess) {
5220
0
        goto done; /* error code set by AppendHandshake */
5221
0
    }
5222
5223
0
done:
5224
    /* For parity with the allocation functions, which don't use
5225
     * SECITEM_AllocItem(). */
5226
0
    if (buf.data)
5227
0
        PORT_Free(buf.data);
5228
0
    return rv;
5229
0
}
5230
5231
/* Called from tls13_CompleteHandleHandshakeMessage() when it has deciphered a complete
5232
 * tls13 CertificateVerify message
5233
 * Caller must hold Handshake and RecvBuf locks.
5234
 */
5235
SECStatus
5236
tls13_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
5237
2
{
5238
2
    sslDelegatedCredential *dc = ss->xtnData.peerDelegCred;
5239
2
    CERTSubjectPublicKeyInfo *spki;
5240
2
    SECKEYPublicKey *pubKey = NULL;
5241
2
    SECItem signed_hash = { siBuffer, NULL, 0 };
5242
2
    SECStatus rv;
5243
2
    SSLSignatureScheme sigScheme;
5244
2
    SSLHashType hashAlg;
5245
2
    SSL3Hashes tbsHash;
5246
2
    SSL3Hashes hashes;
5247
5248
2
    SSL_TRC(3, ("%d: TLS13[%d]: handle certificate_verify handshake",
5249
2
                SSL_GETPID(), ss->fd));
5250
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
5251
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5252
5253
2
    rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY,
5254
2
                              wait_cert_verify);
5255
2
    if (rv != SECSuccess) {
5256
2
        return SECFailure;
5257
2
    }
5258
5259
0
    rv = tls13_ComputeHandshakeHashes(ss, &hashes);
5260
0
    if (rv != SECSuccess) {
5261
0
        return SECFailure;
5262
0
    }
5263
5264
0
    if (ss->firstHsDone) {
5265
0
        rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate_verify, b, length);
5266
0
    } else {
5267
0
        rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify, b, length);
5268
0
    }
5269
0
    if (rv != SECSuccess) {
5270
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5271
0
        return SECFailure;
5272
0
    }
5273
5274
0
    rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
5275
0
    if (rv != SECSuccess) {
5276
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY, illegal_parameter);
5277
0
        return SECFailure;
5278
0
    }
5279
5280
    /* Set the |spki| used to verify the handshake. When verifying with a
5281
     * delegated credential (DC), this corresponds to the DC public key;
5282
     * otherwise it correspond to the public key of the peer's end-entity
5283
     * certificate.
5284
     */
5285
0
    if (tls13_IsVerifyingWithDelegatedCredential(ss)) {
5286
        /* DelegatedCredential.cred.expected_cert_verify_algorithm is expected
5287
         * to match CertificateVerify.scheme.
5288
         * DelegatedCredential.cred.expected_cert_verify_algorithm must also be
5289
         * the same as was reported in ssl3_AuthCertificate.
5290
         */
5291
0
        if (sigScheme != dc->expectedCertVerifyAlg || sigScheme != ss->sec.signatureScheme) {
5292
0
            FATAL_ERROR(ss, SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH, illegal_parameter);
5293
0
            return SECFailure;
5294
0
        }
5295
5296
        /* Verify the DC has three steps: (1) use the peer's end-entity
5297
         * certificate to verify DelegatedCredential.signature, (2) check that
5298
         * the certificate has the correct key usage, and (3) check that the DC
5299
         * hasn't expired.
5300
         */
5301
0
        rv = tls13_VerifyDelegatedCredential(ss, dc);
5302
0
        if (rv != SECSuccess) { /* Calls FATAL_ERROR() */
5303
0
            return SECFailure;
5304
0
        }
5305
5306
0
        SSL_TRC(3, ("%d: TLS13[%d]: Verifying with delegated credential",
5307
0
                    SSL_GETPID(), ss->fd));
5308
0
        spki = dc->spki;
5309
0
    } else {
5310
0
        spki = &ss->sec.peerCert->subjectPublicKeyInfo;
5311
0
    }
5312
5313
0
    rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme, spki);
5314
0
    if (rv != SECSuccess) {
5315
        /* Error set already */
5316
0
        FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
5317
0
        return SECFailure;
5318
0
    }
5319
0
    hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
5320
5321
0
    rv = tls13_AddContextToHashes(ss, &hashes, hashAlg, PR_FALSE, &tbsHash);
5322
0
    if (rv != SECSuccess) {
5323
0
        FATAL_ERROR(ss, SSL_ERROR_DIGEST_FAILURE, internal_error);
5324
0
        return SECFailure;
5325
0
    }
5326
5327
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
5328
0
    if (rv != SECSuccess) {
5329
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_VERIFY);
5330
0
        return SECFailure;
5331
0
    }
5332
5333
0
    if (length != 0) {
5334
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY, decode_error);
5335
0
        return SECFailure;
5336
0
    }
5337
5338
0
    pubKey = SECKEY_ExtractPublicKey(spki);
5339
0
    if (pubKey == NULL) {
5340
0
        ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
5341
0
        return SECFailure;
5342
0
    }
5343
5344
0
    rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, sigScheme,
5345
0
                                          &tbsHash, &signed_hash);
5346
0
    if (rv != SECSuccess) {
5347
0
        FATAL_ERROR(ss, PORT_GetError(), decrypt_error);
5348
0
        goto loser;
5349
0
    }
5350
5351
    /* Set the auth type and verify it is what we captured in ssl3_AuthCertificate */
5352
0
    if (!ss->sec.isServer) {
5353
0
        ss->sec.authType = ssl_SignatureSchemeToAuthType(sigScheme);
5354
5355
0
        uint32_t prelimAuthKeyBits = ss->sec.authKeyBits;
5356
0
        rv = ssl_SetAuthKeyBits(ss, pubKey);
5357
0
        if (rv != SECSuccess) {
5358
0
            goto loser; /* Alert sent and code set. */
5359
0
        }
5360
5361
0
        if (prelimAuthKeyBits != ss->sec.authKeyBits) {
5362
0
            FATAL_ERROR(ss, SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH, illegal_parameter);
5363
0
            goto loser;
5364
0
        }
5365
0
    }
5366
5367
    /* Request a client certificate now if one was requested. */
5368
0
    if (ss->ssl3.hs.clientCertRequested) {
5369
0
        PORT_Assert(!ss->sec.isServer);
5370
0
        rv = ssl3_BeginHandleCertificateRequest(
5371
0
            ss, ss->xtnData.sigSchemes, ss->xtnData.numSigSchemes,
5372
0
            &ss->xtnData.certReqAuthorities);
5373
0
        if (rv != SECSuccess) {
5374
0
            FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
5375
0
            goto loser;
5376
0
        }
5377
0
    }
5378
5379
0
    SECKEY_DestroyPublicKey(pubKey);
5380
0
    TLS13_SET_HS_STATE(ss, wait_finished);
5381
0
    return SECSuccess;
5382
5383
0
loser:
5384
0
    SECKEY_DestroyPublicKey(pubKey);
5385
0
    return SECFailure;
5386
0
}
5387
5388
/* Compute the PSK binder hash over:
5389
 * Client HRR prefix, if present in ss->ssl3.hs.messages or ss->ssl3.hs.echInnerMessages,
5390
 * |len| bytes of |buf| */
5391
static SECStatus
5392
tls13_ComputePskBinderHash(sslSocket *ss, PRUint8 *b, size_t length,
5393
                           SSL3Hashes *hashes, SSLHashType hashType)
5394
4.51k
{
5395
4.51k
    SECStatus rv;
5396
4.51k
    PK11Context *ctx = NULL;
5397
4.51k
    sslBuffer *clientResidual = NULL;
5398
4.51k
    if (!ss->sec.isServer) {
5399
        /* On the server, HRR residual is already buffered. */
5400
4.51k
        clientResidual = ss->ssl3.hs.echHpkeCtx ? &ss->ssl3.hs.echInnerMessages : &ss->ssl3.hs.messages;
5401
4.51k
    }
5402
4.51k
    PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
5403
4.51k
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5404
5405
4.51k
    PRINT_BUF(10, (NULL, "Binder computed over ClientHello",
5406
4.51k
                   b, length));
5407
5408
4.51k
    ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(hashType));
5409
4.51k
    if (!ctx) {
5410
0
        goto loser;
5411
0
    }
5412
4.51k
    rv = PK11_DigestBegin(ctx);
5413
4.51k
    if (rv != SECSuccess) {
5414
0
        ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5415
0
        goto loser;
5416
0
    }
5417
5418
4.51k
    if (clientResidual && clientResidual->len) {
5419
316
        PRINT_BUF(10, (NULL, " with HRR prefix", clientResidual->buf,
5420
316
                       clientResidual->len));
5421
316
        rv = PK11_DigestOp(ctx, clientResidual->buf, clientResidual->len);
5422
316
        if (rv != SECSuccess) {
5423
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5424
0
            goto loser;
5425
0
        }
5426
316
    }
5427
5428
4.51k
    if (IS_DTLS(ss) && !ss->sec.isServer) {
5429
        /* Removing the unnecessary header fields.
5430
         * See ssl3_AppendHandshakeHeader.*/
5431
4.51k
        PORT_Assert(length >= 12);
5432
4.51k
        rv = PK11_DigestOp(ctx, b, 4);
5433
4.51k
        if (rv != SECSuccess) {
5434
0
            ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5435
0
            goto loser;
5436
0
        }
5437
4.51k
        rv = PK11_DigestOp(ctx, b + 12, length - 12);
5438
4.51k
    } else {
5439
0
        rv = PK11_DigestOp(ctx, b, length);
5440
0
    }
5441
4.51k
    if (rv != SECSuccess) {
5442
0
        ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5443
0
        goto loser;
5444
0
    }
5445
4.51k
    rv = PK11_DigestFinal(ctx, hashes->u.raw, &hashes->len, sizeof(hashes->u.raw));
5446
4.51k
    if (rv != SECSuccess) {
5447
0
        ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5448
0
        goto loser;
5449
0
    }
5450
5451
4.51k
    PK11_DestroyContext(ctx, PR_TRUE);
5452
4.51k
    PRINT_BUF(10, (NULL, "PSK Binder hash", hashes->u.raw, hashes->len));
5453
4.51k
    return SECSuccess;
5454
5455
0
loser:
5456
0
    if (ctx) {
5457
0
        PK11_DestroyContext(ctx, PR_TRUE);
5458
0
    }
5459
0
    return SECFailure;
5460
4.51k
}
5461
5462
/* Compute and inject the PSK Binder for sending.
5463
 *
5464
 * When sending a ClientHello, we construct all the extensions with a dummy
5465
 * value for the binder.  To construct the binder, we commit the entire message
5466
 * up to the point where the binders start.  Then we calculate the hash using
5467
 * the saved message (in ss->ssl3.hs.messages).  This is written over the dummy
5468
 * binder, after which we write the remainder of the binder extension. */
5469
SECStatus
5470
tls13_WriteExtensionsWithBinder(sslSocket *ss, sslBuffer *extensions, sslBuffer *chBuf)
5471
4.51k
{
5472
4.51k
    SSL3Hashes hashes;
5473
4.51k
    SECStatus rv;
5474
5475
4.51k
    PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
5476
4.51k
    sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
5477
4.51k
    unsigned int size = tls13_GetHashSizeForHash(psk->hash);
5478
4.51k
    unsigned int prefixLen = extensions->len - size - 3;
5479
4.51k
    unsigned int finishedLen;
5480
5481
4.51k
    PORT_Assert(extensions->len >= size + 3);
5482
5483
4.51k
    rv = sslBuffer_AppendNumber(chBuf, extensions->len, 2);
5484
4.51k
    if (rv != SECSuccess) {
5485
0
        return SECFailure;
5486
0
    }
5487
5488
    /* Only write the extension up to the point before the binders.  Assume that
5489
     * the pre_shared_key extension is at the end of the buffer.  Don't write
5490
     * the binder, or the lengths that precede it (a 2 octet length for the list
5491
     * of all binders, plus a 1 octet length for the binder length). */
5492
4.51k
    rv = sslBuffer_Append(chBuf, extensions->buf, prefixLen);
5493
4.51k
    if (rv != SECSuccess) {
5494
0
        return SECFailure;
5495
0
    }
5496
5497
    /* Calculate the binder based on what has been written out. */
5498
4.51k
    rv = tls13_ComputePskBinderHash(ss, chBuf->buf, chBuf->len, &hashes, psk->hash);
5499
4.51k
    if (rv != SECSuccess) {
5500
0
        return SECFailure;
5501
0
    }
5502
5503
    /* Write the binder into the extensions buffer, over the zeros we reserved
5504
     * previously. This avoids an allocation and means that we don't need a
5505
     * separate write for the extra bits that precede the binder. */
5506
4.51k
    PORT_Assert(psk->binderKey);
5507
4.51k
    rv = tls13_ComputeFinished(ss, psk->binderKey,
5508
4.51k
                               psk->hash, &hashes, PR_TRUE,
5509
4.51k
                               extensions->buf + extensions->len - size,
5510
4.51k
                               &finishedLen, size);
5511
4.51k
    if (rv != SECSuccess) {
5512
0
        return SECFailure;
5513
0
    }
5514
4.51k
    PORT_Assert(finishedLen == size);
5515
5516
    /* Write out the remainder of the extension. */
5517
4.51k
    rv = sslBuffer_Append(chBuf, extensions->buf + prefixLen,
5518
4.51k
                          extensions->len - prefixLen);
5519
4.51k
    if (rv != SECSuccess) {
5520
0
        return SECFailure;
5521
0
    }
5522
5523
4.51k
    return SECSuccess;
5524
4.51k
}
5525
5526
static SECStatus
5527
tls13_ComputeFinished(sslSocket *ss, PK11SymKey *baseKey,
5528
                      SSLHashType hashType, const SSL3Hashes *hashes,
5529
                      PRBool sending, PRUint8 *output, unsigned int *outputLen,
5530
                      unsigned int maxOutputLen)
5531
4.51k
{
5532
4.51k
    SECStatus rv;
5533
4.51k
    PK11Context *hmacCtx = NULL;
5534
4.51k
    CK_MECHANISM_TYPE macAlg = tls13_GetHmacMechanismFromHash(hashType);
5535
4.51k
    SECItem param = { siBuffer, NULL, 0 };
5536
4.51k
    unsigned int outputLenUint;
5537
4.51k
    const char *label = kHkdfLabelFinishedSecret;
5538
4.51k
    PK11SymKey *secret = NULL;
5539
5540
4.51k
    PORT_Assert(baseKey);
5541
4.51k
    SSL_TRC(3, ("%d: TLS13[%d]: %s calculate finished",
5542
4.51k
                SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
5543
4.51k
    PRINT_BUF(50, (ss, "Handshake hash", hashes->u.raw, hashes->len));
5544
5545
    /* Now derive the appropriate finished secret from the base secret. */
5546
4.51k
    rv = tls13_HkdfExpandLabel(baseKey, hashType,
5547
4.51k
                               NULL, 0, label, strlen(label),
5548
4.51k
                               tls13_GetHmacMechanismFromHash(hashType),
5549
4.51k
                               tls13_GetHashSizeForHash(hashType),
5550
4.51k
                               ss->protocolVariant, &secret);
5551
4.51k
    if (rv != SECSuccess) {
5552
0
        goto abort;
5553
0
    }
5554
5555
4.51k
    PORT_Assert(hashes->len == tls13_GetHashSizeForHash(hashType));
5556
4.51k
    hmacCtx = PK11_CreateContextBySymKey(macAlg, CKA_SIGN,
5557
4.51k
                                         secret, &param);
5558
4.51k
    if (!hmacCtx) {
5559
0
        goto abort;
5560
0
    }
5561
5562
4.51k
    rv = PK11_DigestBegin(hmacCtx);
5563
4.51k
    if (rv != SECSuccess)
5564
0
        goto abort;
5565
5566
4.51k
    rv = PK11_DigestOp(hmacCtx, hashes->u.raw, hashes->len);
5567
4.51k
    if (rv != SECSuccess)
5568
0
        goto abort;
5569
5570
4.51k
    PORT_Assert(maxOutputLen >= tls13_GetHashSizeForHash(hashType));
5571
4.51k
    rv = PK11_DigestFinal(hmacCtx, output, &outputLenUint, maxOutputLen);
5572
4.51k
    if (rv != SECSuccess)
5573
0
        goto abort;
5574
4.51k
    *outputLen = outputLenUint;
5575
5576
4.51k
    PK11_FreeSymKey(secret);
5577
4.51k
    PK11_DestroyContext(hmacCtx, PR_TRUE);
5578
4.51k
    PRINT_BUF(50, (ss, "finished value", output, outputLenUint));
5579
4.51k
    return SECSuccess;
5580
5581
0
abort:
5582
0
    if (secret) {
5583
0
        PK11_FreeSymKey(secret);
5584
0
    }
5585
5586
0
    if (hmacCtx) {
5587
0
        PK11_DestroyContext(hmacCtx, PR_TRUE);
5588
0
    }
5589
5590
0
    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5591
0
    return SECFailure;
5592
4.51k
}
5593
5594
static SECStatus
5595
tls13_SendFinished(sslSocket *ss, PK11SymKey *baseKey)
5596
0
{
5597
0
    SECStatus rv;
5598
0
    PRUint8 finishedBuf[TLS13_MAX_FINISHED_SIZE];
5599
0
    unsigned int finishedLen;
5600
0
    SSL3Hashes hashes;
5601
5602
0
    SSL_TRC(3, ("%d: TLS13[%d]: send finished handshake", SSL_GETPID(), ss->fd));
5603
5604
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5605
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5606
5607
0
    rv = tls13_ComputeHandshakeHashes(ss, &hashes);
5608
0
    if (rv != SECSuccess) {
5609
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
5610
0
        return SECFailure;
5611
0
    }
5612
5613
0
    ssl_GetSpecReadLock(ss);
5614
0
    rv = tls13_ComputeFinished(ss, baseKey, tls13_GetHash(ss), &hashes, PR_TRUE,
5615
0
                               finishedBuf, &finishedLen, sizeof(finishedBuf));
5616
0
    ssl_ReleaseSpecReadLock(ss);
5617
0
    if (rv != SECSuccess) {
5618
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
5619
0
        return SECFailure;
5620
0
    }
5621
5622
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, finishedLen);
5623
0
    if (rv != SECSuccess) {
5624
0
        return SECFailure; /* Error code already set. */
5625
0
    }
5626
5627
0
    rv = ssl3_AppendHandshake(ss, finishedBuf, finishedLen);
5628
0
    if (rv != SECSuccess) {
5629
0
        return SECFailure; /* Error code already set. */
5630
0
    }
5631
5632
    /* TODO(ekr@rtfm.com): Record key log */
5633
0
    return SECSuccess;
5634
0
}
5635
5636
static SECStatus
5637
tls13_VerifyFinished(sslSocket *ss, SSLHandshakeType message,
5638
                     PK11SymKey *secret,
5639
                     PRUint8 *b, PRUint32 length,
5640
                     const SSL3Hashes *hashes)
5641
0
{
5642
0
    SECStatus rv;
5643
0
    PRUint8 finishedBuf[TLS13_MAX_FINISHED_SIZE];
5644
0
    unsigned int finishedLen;
5645
5646
0
    if (!hashes) {
5647
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
5648
0
        return SECFailure;
5649
0
    }
5650
5651
0
    rv = tls13_ComputeFinished(ss, secret, tls13_GetHash(ss), hashes, PR_FALSE,
5652
0
                               finishedBuf, &finishedLen, sizeof(finishedBuf));
5653
0
    if (rv != SECSuccess) {
5654
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
5655
0
        return SECFailure;
5656
0
    }
5657
5658
0
    if (length != finishedLen) {
5659
0
#ifndef UNSAFE_FUZZER_MODE
5660
0
        FATAL_ERROR(ss, message == ssl_hs_finished ? SSL_ERROR_RX_MALFORMED_FINISHED : SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
5661
0
        return SECFailure;
5662
0
#endif
5663
0
    }
5664
5665
0
    if (NSS_SecureMemcmp(b, finishedBuf, finishedLen) != 0) {
5666
0
#ifndef UNSAFE_FUZZER_MODE
5667
0
        FATAL_ERROR(ss, SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE,
5668
0
                    decrypt_error);
5669
0
        return SECFailure;
5670
0
#endif
5671
0
    }
5672
5673
0
    return SECSuccess;
5674
0
}
5675
5676
static SECStatus
5677
tls13_CommonHandleFinished(sslSocket *ss, PK11SymKey *key,
5678
                           PRUint8 *b, PRUint32 length)
5679
2
{
5680
2
    SECStatus rv;
5681
2
    SSL3Hashes hashes;
5682
5683
2
    rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_FINISHED,
5684
2
                              wait_finished);
5685
2
    if (rv != SECSuccess) {
5686
2
        return SECFailure;
5687
2
    }
5688
0
    ss->ssl3.hs.endOfFlight = PR_TRUE;
5689
5690
0
    rv = tls13_ComputeHandshakeHashes(ss, &hashes);
5691
0
    if (rv != SECSuccess) {
5692
0
        LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
5693
0
        return SECFailure;
5694
0
    }
5695
5696
0
    if (ss->firstHsDone) {
5697
0
        rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_finished, b, length);
5698
0
    } else {
5699
0
        rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
5700
0
    }
5701
0
    if (rv != SECSuccess) {
5702
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5703
0
        return SECFailure;
5704
0
    }
5705
5706
0
    return tls13_VerifyFinished(ss, ssl_hs_finished,
5707
0
                                key, b, length, &hashes);
5708
0
}
5709
5710
static SECStatus
5711
tls13_ClientHandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
5712
2
{
5713
2
    SECStatus rv;
5714
5715
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
5716
2
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5717
5718
2
    SSL_TRC(3, ("%d: TLS13[%d]: client handle finished handshake",
5719
2
                SSL_GETPID(), ss->fd));
5720
5721
2
    rv = tls13_CommonHandleFinished(ss, ss->ssl3.hs.serverHsTrafficSecret,
5722
2
                                    b, length);
5723
2
    if (rv != SECSuccess) {
5724
2
        return SECFailure;
5725
2
    }
5726
5727
0
    return tls13_SendClientSecondRound(ss);
5728
2
}
5729
5730
static SECStatus
5731
tls13_ServerHandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
5732
0
{
5733
0
    SECStatus rv;
5734
5735
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
5736
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5737
5738
0
    SSL_TRC(3, ("%d: TLS13[%d]: server handle finished handshake",
5739
0
                SSL_GETPID(), ss->fd));
5740
5741
0
    if (!tls13_ShouldRequestClientAuth(ss)) {
5742
        /* Receiving this message might be the first sign we have that
5743
         * early data is over, so pretend we received EOED. */
5744
0
        rv = tls13_MaybeHandleSuppressedEndOfEarlyData(ss);
5745
0
        if (rv != SECSuccess) {
5746
0
            return SECFailure; /* Code already set. */
5747
0
        }
5748
5749
0
        if (!tls13_IsPostHandshake(ss)) {
5750
            /* Finalize the RTT estimate. */
5751
0
            ss->ssl3.hs.rttEstimate = ssl_Time(ss) - ss->ssl3.hs.rttEstimate;
5752
0
        }
5753
0
    }
5754
5755
0
    rv = tls13_CommonHandleFinished(ss,
5756
0
                                    ss->firstHsDone ? ss->ssl3.hs.clientTrafficSecret : ss->ssl3.hs.clientHsTrafficSecret,
5757
0
                                    b, length);
5758
0
    if (rv != SECSuccess) {
5759
0
        return SECFailure;
5760
0
    }
5761
5762
0
    if (ss->firstHsDone) {
5763
0
        TLS13_SET_HS_STATE(ss, idle_handshake);
5764
5765
0
        PORT_Assert(ss->ssl3.hs.shaPostHandshake != NULL);
5766
0
        PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
5767
0
        ss->ssl3.hs.shaPostHandshake = NULL;
5768
5769
0
        ss->ssl3.clientCertRequested = PR_FALSE;
5770
5771
0
        if (ss->ssl3.hs.keyUpdateDeferred) {
5772
0
            rv = tls13_SendKeyUpdate(ss, ss->ssl3.hs.deferredKeyUpdateRequest,
5773
0
                                     PR_FALSE);
5774
0
            if (rv != SECSuccess) {
5775
0
                return SECFailure; /* error is set. */
5776
0
            }
5777
0
            ss->ssl3.hs.keyUpdateDeferred = PR_FALSE;
5778
0
        }
5779
5780
0
        return SECSuccess;
5781
0
    }
5782
5783
0
    if (!tls13_ShouldRequestClientAuth(ss) &&
5784
0
        (ss->ssl3.hs.zeroRttState != ssl_0rtt_done)) {
5785
0
        dtls_ReceivedFirstMessageInFlight(ss);
5786
0
    }
5787
5788
0
    rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
5789
0
                             ssl_secret_read, PR_FALSE);
5790
0
    if (rv != SECSuccess) {
5791
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
5792
0
        return SECFailure;
5793
0
    }
5794
5795
0
    if (IS_DTLS(ss)) {
5796
0
        ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read, TrafficKeyClearText);
5797
        /* We need to keep the handshake cipher spec so we can
5798
         * read re-transmitted client Finished. */
5799
0
        rv = dtls_StartTimer(ss, ss->ssl3.hs.hdTimer,
5800
0
                             DTLS_RETRANSMIT_FINISHED_MS,
5801
0
                             dtls13_HolddownTimerCb);
5802
0
        if (rv != SECSuccess) {
5803
0
            return SECFailure;
5804
0
        }
5805
0
    }
5806
5807
0
    rv = tls13_ComputeFinalSecrets(ss);
5808
0
    if (rv != SECSuccess) {
5809
0
        return SECFailure;
5810
0
    }
5811
5812
0
    rv = tls13_FinishHandshake(ss);
5813
0
    if (rv != SECSuccess) {
5814
0
        return SECFailure;
5815
0
    }
5816
5817
0
    ssl_GetXmitBufLock(ss);
5818
    /* If resumption, authType is the original value and not ssl_auth_psk. */
5819
0
    if (ss->opt.enableSessionTickets && ss->sec.authType != ssl_auth_psk) {
5820
0
        rv = tls13_SendNewSessionTicket(ss, NULL, 0);
5821
0
        if (rv != SECSuccess) {
5822
0
            goto loser;
5823
0
        }
5824
0
        rv = ssl3_FlushHandshake(ss, 0);
5825
0
        if (rv != SECSuccess) {
5826
0
            goto loser;
5827
0
        }
5828
0
    }
5829
0
    ssl_ReleaseXmitBufLock(ss);
5830
0
    return SECSuccess;
5831
5832
0
loser:
5833
0
    ssl_ReleaseXmitBufLock(ss);
5834
0
    return SECFailure;
5835
0
}
5836
5837
static SECStatus
5838
tls13_FinishHandshake(sslSocket *ss)
5839
0
{
5840
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
5841
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5842
0
    PORT_Assert(ss->ssl3.hs.restartTarget == NULL);
5843
5844
    /* The first handshake is now completed. */
5845
0
    ss->handshake = NULL;
5846
5847
    /* Don't need this. */
5848
0
    PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
5849
0
    ss->ssl3.hs.clientHsTrafficSecret = NULL;
5850
0
    PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
5851
0
    ss->ssl3.hs.serverHsTrafficSecret = NULL;
5852
5853
0
    TLS13_SET_HS_STATE(ss, idle_handshake);
5854
5855
0
    return ssl_FinishHandshake(ss);
5856
0
}
5857
5858
/* Do the parts of sending the client's second round that require
5859
 * the XmitBuf lock. */
5860
static SECStatus
5861
tls13_SendClientSecondFlight(sslSocket *ss)
5862
0
{
5863
0
    SECStatus rv;
5864
0
    unsigned int offset = 0;
5865
5866
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5867
0
    PORT_Assert(!ss->ssl3.hs.clientCertificatePending);
5868
5869
0
    PRBool sendClientCert = !ss->ssl3.sendEmptyCert &&
5870
0
                            ss->ssl3.clientCertChain != NULL &&
5871
0
                            ss->ssl3.clientPrivateKey != NULL;
5872
5873
0
    if (ss->firstHsDone) {
5874
0
        offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf);
5875
0
    }
5876
5877
0
    if (ss->ssl3.sendEmptyCert) {
5878
0
        ss->ssl3.sendEmptyCert = PR_FALSE;
5879
0
        rv = ssl3_SendEmptyCertificate(ss);
5880
        /* Don't send verify */
5881
0
        if (rv != SECSuccess) {
5882
0
            goto alert_error; /* error code is set. */
5883
0
        }
5884
0
    } else if (sendClientCert) {
5885
0
        rv = tls13_SendCertificate(ss);
5886
0
        if (rv != SECSuccess) {
5887
0
            goto alert_error; /* err code was set. */
5888
0
        }
5889
0
    }
5890
5891
0
    if (ss->firstHsDone) {
5892
0
        rv = ssl3_UpdatePostHandshakeHashes(ss,
5893
0
                                            SSL_BUFFER_BASE(&ss->sec.ci.sendBuf) + offset,
5894
0
                                            SSL_BUFFER_LEN(&ss->sec.ci.sendBuf) - offset);
5895
0
        if (rv != SECSuccess) {
5896
0
            goto alert_error; /* err code was set. */
5897
0
        }
5898
0
    }
5899
5900
0
    if (ss->ssl3.hs.clientCertRequested) {
5901
0
        SECITEM_FreeItem(&ss->xtnData.certReqContext, PR_FALSE);
5902
0
        if (ss->xtnData.certReqAuthorities.arena) {
5903
0
            PORT_FreeArena(ss->xtnData.certReqAuthorities.arena, PR_FALSE);
5904
0
            ss->xtnData.certReqAuthorities.arena = NULL;
5905
0
        }
5906
0
        PORT_Memset(&ss->xtnData.certReqAuthorities, 0,
5907
0
                    sizeof(ss->xtnData.certReqAuthorities));
5908
0
        ss->ssl3.hs.clientCertRequested = PR_FALSE;
5909
0
    }
5910
5911
0
    if (sendClientCert) {
5912
0
        if (ss->firstHsDone) {
5913
0
            offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf);
5914
0
        }
5915
5916
0
        rv = tls13_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
5917
0
        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
5918
0
        ss->ssl3.clientPrivateKey = NULL;
5919
0
        if (rv != SECSuccess) {
5920
0
            goto alert_error; /* err code was set. */
5921
0
        }
5922
5923
0
        if (ss->firstHsDone) {
5924
0
            rv = ssl3_UpdatePostHandshakeHashes(ss,
5925
0
                                                SSL_BUFFER_BASE(&ss->sec.ci.sendBuf) + offset,
5926
0
                                                SSL_BUFFER_LEN(&ss->sec.ci.sendBuf) - offset);
5927
0
            if (rv != SECSuccess) {
5928
0
                goto alert_error; /* err code was set. */
5929
0
            }
5930
0
        }
5931
0
    }
5932
5933
0
    rv = tls13_SendFinished(ss, ss->firstHsDone ? ss->ssl3.hs.clientTrafficSecret : ss->ssl3.hs.clientHsTrafficSecret);
5934
0
    if (rv != SECSuccess) {
5935
0
        goto alert_error; /* err code was set. */
5936
0
    }
5937
0
    rv = ssl3_FlushHandshake(ss, 0);
5938
0
    if (rv != SECSuccess) {
5939
        /* No point in sending an alert here because we're not going to
5940
         * be able to send it if we couldn't flush the handshake. */
5941
0
        goto error;
5942
0
    }
5943
5944
0
    return SECSuccess;
5945
5946
0
alert_error:
5947
0
    FATAL_ERROR(ss, PORT_GetError(), internal_error);
5948
0
    return SECFailure;
5949
0
error:
5950
0
    LOG_ERROR(ss, PORT_GetError());
5951
0
    return SECFailure;
5952
0
}
5953
5954
static SECStatus
5955
tls13_SendClientSecondRound(sslSocket *ss)
5956
0
{
5957
0
    SECStatus rv;
5958
5959
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
5960
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5961
5962
    /* Defer client authentication sending if we are still waiting for server
5963
     * authentication.  This avoids unnecessary disclosure of client credentials
5964
     * to an unauthenticated server.
5965
     */
5966
0
    if (ss->ssl3.hs.restartTarget) {
5967
0
        PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
5968
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5969
0
        return SECFailure;
5970
0
    }
5971
0
    if (ss->ssl3.hs.authCertificatePending || ss->ssl3.hs.clientCertificatePending) {
5972
0
        SSL_TRC(3, ("%d: TLS13[%d]: deferring tls13_SendClientSecondRound because"
5973
0
                    " certificate authentication is still pending.",
5974
0
                    SSL_GETPID(), ss->fd));
5975
0
        ss->ssl3.hs.restartTarget = tls13_SendClientSecondRound;
5976
0
        PORT_SetError(PR_WOULD_BLOCK_ERROR);
5977
0
        return SECFailure;
5978
0
    }
5979
5980
0
    rv = tls13_ComputeApplicationSecrets(ss);
5981
0
    if (rv != SECSuccess) {
5982
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
5983
0
        return SECFailure;
5984
0
    }
5985
5986
0
    if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
5987
0
        ssl_GetXmitBufLock(ss); /*******************************/
5988
0
        rv = tls13_SendEndOfEarlyData(ss);
5989
0
        ssl_ReleaseXmitBufLock(ss); /*******************************/
5990
0
        if (rv != SECSuccess) {
5991
0
            return SECFailure; /* Error code already set. */
5992
0
        }
5993
0
    } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss) &&
5994
0
               ss->ssl3.hs.zeroRttState == ssl_0rtt_none &&
5995
0
               !ss->ssl3.hs.helloRetry) {
5996
0
        ssl_GetXmitBufLock(ss); /*******************************/
5997
0
        rv = ssl3_SendChangeCipherSpecsInt(ss);
5998
0
        ssl_ReleaseXmitBufLock(ss); /*******************************/
5999
0
        if (rv != SECSuccess) {
6000
0
            return rv;
6001
0
        }
6002
0
    }
6003
6004
0
    rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
6005
0
                             ssl_secret_write, PR_FALSE);
6006
0
    if (rv != SECSuccess) {
6007
0
        FATAL_ERROR(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, internal_error);
6008
0
        return SECFailure;
6009
0
    }
6010
6011
0
    rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
6012
0
                             ssl_secret_read, PR_FALSE);
6013
0
    if (rv != SECSuccess) {
6014
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
6015
0
        return SECFailure;
6016
0
    }
6017
6018
0
    ssl_GetXmitBufLock(ss); /*******************************/
6019
    /* This call can't block, as clientAuthCertificatePending is checked above */
6020
0
    rv = tls13_SendClientSecondFlight(ss);
6021
0
    ssl_ReleaseXmitBufLock(ss); /*******************************/
6022
0
    if (rv != SECSuccess) {
6023
0
        return SECFailure;
6024
0
    }
6025
0
    rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
6026
0
                             ssl_secret_write, PR_FALSE);
6027
0
    if (rv != SECSuccess) {
6028
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6029
0
        return SECFailure;
6030
0
    }
6031
6032
0
    rv = tls13_ComputeFinalSecrets(ss);
6033
0
    if (rv != SECSuccess) {
6034
0
        return SECFailure;
6035
0
    }
6036
6037
    /* The handshake is now finished */
6038
0
    return tls13_FinishHandshake(ss);
6039
0
}
6040
6041
/*
6042
 *  enum { (65535) } TicketExtensionType;
6043
 *
6044
 *  struct {
6045
 *      TicketExtensionType extension_type;
6046
 *      opaque extension_data<0..2^16-1>;
6047
 *  } TicketExtension;
6048
 *
6049
 *   struct {
6050
 *       uint32 ticket_lifetime;
6051
 *       uint32 ticket_age_add;
6052
 *       opaque ticket_nonce<1..255>;
6053
 *       opaque ticket<1..2^16-1>;
6054
 *       TicketExtension extensions<0..2^16-2>;
6055
 *   } NewSessionTicket;
6056
 */
6057
6058
static SECStatus
6059
tls13_SendNewSessionTicket(sslSocket *ss, const PRUint8 *appToken,
6060
                           unsigned int appTokenLen)
6061
0
{
6062
0
    PRUint16 message_length;
6063
0
    PK11SymKey *secret;
6064
0
    SECItem ticket_data = { 0, NULL, 0 };
6065
0
    SECStatus rv;
6066
0
    NewSessionTicket ticket = { 0 };
6067
0
    PRUint32 max_early_data_size_len = 0;
6068
0
    PRUint32 greaseLen = 0;
6069
0
    PRUint8 ticketNonce[sizeof(ss->ssl3.hs.ticketNonce)];
6070
0
    sslBuffer ticketNonceBuf = SSL_BUFFER(ticketNonce);
6071
6072
0
    SSL_TRC(3, ("%d: TLS13[%d]: send new session ticket message %d",
6073
0
                SSL_GETPID(), ss->fd, ss->ssl3.hs.ticketNonce));
6074
6075
0
    ticket.flags = 0;
6076
0
    if (ss->opt.enable0RttData) {
6077
0
        ticket.flags |= ticket_allow_early_data;
6078
0
        max_early_data_size_len = 8; /* type + len + value. */
6079
0
    }
6080
0
    ticket.ticket_lifetime_hint = ssl_ticket_lifetime;
6081
6082
0
    if (ss->opt.enableGrease) {
6083
0
        greaseLen = 4; /* type + len + 0 (empty) */
6084
0
    }
6085
6086
    /* The ticket age obfuscator. */
6087
0
    rv = PK11_GenerateRandom((PRUint8 *)&ticket.ticket_age_add,
6088
0
                             sizeof(ticket.ticket_age_add));
6089
0
    if (rv != SECSuccess)
6090
0
        goto loser;
6091
6092
0
    rv = sslBuffer_AppendNumber(&ticketNonceBuf, ss->ssl3.hs.ticketNonce,
6093
0
                                sizeof(ticketNonce));
6094
0
    if (rv != SECSuccess) {
6095
0
        goto loser;
6096
0
    }
6097
0
    ++ss->ssl3.hs.ticketNonce;
6098
0
    rv = tls13_HkdfExpandLabel(ss->ssl3.hs.resumptionMasterSecret,
6099
0
                               tls13_GetHash(ss),
6100
0
                               ticketNonce, sizeof(ticketNonce),
6101
0
                               kHkdfLabelResumption,
6102
0
                               strlen(kHkdfLabelResumption),
6103
0
                               CKM_HKDF_DERIVE,
6104
0
                               tls13_GetHashSize(ss),
6105
0
                               ss->protocolVariant, &secret);
6106
0
    if (rv != SECSuccess) {
6107
0
        goto loser;
6108
0
    }
6109
6110
0
    rv = ssl3_EncodeSessionTicket(ss, &ticket, appToken, appTokenLen,
6111
0
                                  secret, &ticket_data);
6112
0
    PK11_FreeSymKey(secret);
6113
0
    if (rv != SECSuccess)
6114
0
        goto loser;
6115
6116
0
    message_length =
6117
0
        4 +                       /* lifetime */
6118
0
        4 +                       /* ticket_age_add */
6119
0
        1 + sizeof(ticketNonce) + /* ticket_nonce */
6120
0
        2 +                       /* extensions lentgh */
6121
0
        max_early_data_size_len + /* max_early_data_size extension length */
6122
0
        greaseLen +               /* GREASE extension length */
6123
0
        2 +                       /* ticket length */
6124
0
        ticket_data.len;
6125
6126
0
    rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
6127
0
                                    message_length);
6128
0
    if (rv != SECSuccess)
6129
0
        goto loser;
6130
6131
    /* This is a fixed value. */
6132
0
    rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
6133
0
    if (rv != SECSuccess)
6134
0
        goto loser;
6135
6136
0
    rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_age_add, 4);
6137
0
    if (rv != SECSuccess)
6138
0
        goto loser;
6139
6140
    /* The ticket nonce. */
6141
0
    rv = ssl3_AppendHandshakeVariable(ss, ticketNonce, sizeof(ticketNonce), 1);
6142
0
    if (rv != SECSuccess)
6143
0
        goto loser;
6144
6145
    /* Encode the ticket. */
6146
0
    rv = ssl3_AppendHandshakeVariable(
6147
0
        ss, ticket_data.data, ticket_data.len, 2);
6148
0
    if (rv != SECSuccess)
6149
0
        goto loser;
6150
6151
    /* Extensions */
6152
0
    rv = ssl3_AppendHandshakeNumber(ss, max_early_data_size_len + greaseLen, 2);
6153
0
    if (rv != SECSuccess)
6154
0
        goto loser;
6155
6156
    /* GREASE NewSessionTicket:
6157
     * When sending a NewSessionTicket message in TLS 1.3, a server MAY select
6158
     * one or more GREASE extension values and advertise them as extensions
6159
     * with varying length and contents [RFC8701, SEction 4.1]. */
6160
0
    if (ss->opt.enableGrease) {
6161
0
        PR_ASSERT(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
6162
6163
0
        PRUint16 grease;
6164
0
        rv = tls13_RandomGreaseValue(&grease);
6165
0
        if (rv != SECSuccess)
6166
0
            goto loser;
6167
        /* Extension type */
6168
0
        rv = ssl3_AppendHandshakeNumber(ss, grease, 2);
6169
0
        if (rv != SECSuccess)
6170
0
            goto loser;
6171
        /* Extension length */
6172
0
        rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
6173
0
        if (rv != SECSuccess)
6174
0
            goto loser;
6175
0
    }
6176
6177
    /* Max early data size extension. */
6178
0
    if (max_early_data_size_len) {
6179
0
        rv = ssl3_AppendHandshakeNumber(
6180
0
            ss, ssl_tls13_early_data_xtn, 2);
6181
0
        if (rv != SECSuccess)
6182
0
            goto loser;
6183
6184
        /* Length */
6185
0
        rv = ssl3_AppendHandshakeNumber(ss, 4, 2);
6186
0
        if (rv != SECSuccess)
6187
0
            goto loser;
6188
6189
0
        rv = ssl3_AppendHandshakeNumber(ss, ss->opt.maxEarlyDataSize, 4);
6190
0
        if (rv != SECSuccess)
6191
0
            goto loser;
6192
0
    }
6193
6194
0
    SECITEM_FreeItem(&ticket_data, PR_FALSE);
6195
0
    return SECSuccess;
6196
6197
0
loser:
6198
0
    if (ticket_data.data) {
6199
0
        SECITEM_FreeItem(&ticket_data, PR_FALSE);
6200
0
    }
6201
0
    return SECFailure;
6202
0
}
6203
6204
SECStatus
6205
SSLExp_SendSessionTicket(PRFileDesc *fd, const PRUint8 *token,
6206
                         unsigned int tokenLen)
6207
0
{
6208
0
    sslSocket *ss;
6209
0
    SECStatus rv;
6210
6211
0
    ss = ssl_FindSocket(fd);
6212
0
    if (!ss) {
6213
0
        return SECFailure;
6214
0
    }
6215
6216
0
    if (IS_DTLS(ss)) {
6217
0
        PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION);
6218
0
        return SECFailure;
6219
0
    }
6220
6221
0
    if (!ss->sec.isServer || !tls13_IsPostHandshake(ss) ||
6222
0
        tokenLen > 0xffff) {
6223
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
6224
0
        return SECFailure;
6225
0
    }
6226
6227
    /* Disable tickets if we can trace this connection back to a PSK.
6228
     * We aren't able to issue tickets (currently) without a certificate.
6229
     * As PSK =~ resumption, there is no reason to do this. */
6230
0
    if (ss->sec.authType == ssl_auth_psk) {
6231
0
        PORT_SetError(SSL_ERROR_FEATURE_DISABLED);
6232
0
        return SECFailure;
6233
0
    }
6234
6235
0
    ssl_GetSSL3HandshakeLock(ss);
6236
0
    ssl_GetXmitBufLock(ss);
6237
0
    rv = tls13_SendNewSessionTicket(ss, token, tokenLen);
6238
0
    if (rv == SECSuccess) {
6239
0
        rv = ssl3_FlushHandshake(ss, 0);
6240
0
    }
6241
0
    ssl_ReleaseXmitBufLock(ss);
6242
0
    ssl_ReleaseSSL3HandshakeLock(ss);
6243
6244
0
    return rv;
6245
0
}
6246
6247
static SECStatus
6248
tls13_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
6249
1
{
6250
1
    SECStatus rv;
6251
1
    PRUint32 utmp;
6252
1
    NewSessionTicket ticket = { 0 };
6253
1
    SECItem data;
6254
1
    SECItem ticket_nonce;
6255
1
    SECItem ticket_data;
6256
6257
1
    SSL_TRC(3, ("%d: TLS13[%d]: handle new session ticket message",
6258
1
                SSL_GETPID(), ss->fd));
6259
6260
1
    rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET,
6261
1
                              idle_handshake);
6262
1
    if (rv != SECSuccess) {
6263
1
        return SECFailure;
6264
1
    }
6265
0
    if (!tls13_IsPostHandshake(ss) || ss->sec.isServer) {
6266
0
        FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET,
6267
0
                    unexpected_message);
6268
0
        return SECFailure;
6269
0
    }
6270
6271
0
    ticket.received_timestamp = ssl_Time(ss);
6272
0
    rv = ssl3_ConsumeHandshakeNumber(ss, &ticket.ticket_lifetime_hint, 4, &b,
6273
0
                                     &length);
6274
0
    if (rv != SECSuccess) {
6275
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
6276
0
                    decode_error);
6277
0
        return SECFailure;
6278
0
    }
6279
0
    ticket.ticket.type = siBuffer;
6280
6281
0
    rv = ssl3_ConsumeHandshake(ss, &utmp, sizeof(utmp),
6282
0
                               &b, &length);
6283
0
    if (rv != SECSuccess) {
6284
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
6285
0
        return SECFailure;
6286
0
    }
6287
0
    ticket.ticket_age_add = PR_ntohl(utmp);
6288
6289
    /* The nonce. */
6290
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &ticket_nonce, 1, &b, &length);
6291
0
    if (rv != SECSuccess) {
6292
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
6293
0
                    decode_error);
6294
0
        return SECFailure;
6295
0
    }
6296
6297
    /* Get the ticket value. */
6298
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &ticket_data, 2, &b, &length);
6299
0
    if (rv != SECSuccess || !ticket_data.len) {
6300
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
6301
0
                    decode_error);
6302
0
        return SECFailure;
6303
0
    }
6304
6305
    /* Parse extensions. */
6306
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &data, 2, &b, &length);
6307
0
    if (rv != SECSuccess || length) {
6308
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
6309
0
                    decode_error);
6310
0
        return SECFailure;
6311
0
    }
6312
6313
0
    rv = ssl3_HandleExtensions(ss, &data.data,
6314
0
                               &data.len, ssl_hs_new_session_ticket);
6315
0
    if (rv != SECSuccess) {
6316
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
6317
0
                    decode_error);
6318
0
        return SECFailure;
6319
0
    }
6320
0
    if (ss->xtnData.max_early_data_size) {
6321
0
        ticket.flags |= ticket_allow_early_data;
6322
0
        ticket.max_early_data_size = ss->xtnData.max_early_data_size;
6323
0
    }
6324
6325
0
    if (!ss->opt.noCache) {
6326
0
        PK11SymKey *secret;
6327
6328
0
        PORT_Assert(ss->sec.ci.sid);
6329
0
        rv = SECITEM_CopyItem(NULL, &ticket.ticket, &ticket_data);
6330
0
        if (rv != SECSuccess) {
6331
0
            FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
6332
0
            return SECFailure;
6333
0
        }
6334
0
        PRINT_BUF(50, (ss, "Caching session ticket",
6335
0
                       ticket.ticket.data,
6336
0
                       ticket.ticket.len));
6337
6338
        /* Replace a previous session ticket when
6339
         * we receive a second NewSessionTicket message. */
6340
0
        if (ss->sec.ci.sid->cached == in_client_cache ||
6341
0
            ss->sec.ci.sid->cached == in_external_cache) {
6342
            /* Create a new session ID. */
6343
0
            sslSessionID *sid = ssl3_NewSessionID(ss, PR_FALSE);
6344
0
            if (!sid) {
6345
0
                return SECFailure;
6346
0
            }
6347
6348
            /* Copy over the peerCert. */
6349
0
            PORT_Assert(ss->sec.ci.sid->peerCert);
6350
0
            sid->peerCert = CERT_DupCertificate(ss->sec.ci.sid->peerCert);
6351
0
            if (!sid->peerCert) {
6352
0
                ssl_FreeSID(sid);
6353
0
                return SECFailure;
6354
0
            }
6355
6356
            /* Destroy the old SID. */
6357
0
            ssl_UncacheSessionID(ss);
6358
0
            ssl_FreeSID(ss->sec.ci.sid);
6359
0
            ss->sec.ci.sid = sid;
6360
0
        }
6361
6362
0
        ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ticket);
6363
0
        PORT_Assert(!ticket.ticket.data);
6364
6365
0
        rv = tls13_HkdfExpandLabel(ss->ssl3.hs.resumptionMasterSecret,
6366
0
                                   tls13_GetHash(ss),
6367
0
                                   ticket_nonce.data, ticket_nonce.len,
6368
0
                                   kHkdfLabelResumption,
6369
0
                                   strlen(kHkdfLabelResumption),
6370
0
                                   CKM_HKDF_DERIVE,
6371
0
                                   tls13_GetHashSize(ss),
6372
0
                                   ss->protocolVariant, &secret);
6373
0
        if (rv != SECSuccess) {
6374
0
            return SECFailure;
6375
0
        }
6376
6377
0
        rv = ssl3_FillInCachedSID(ss, ss->sec.ci.sid, secret);
6378
0
        PK11_FreeSymKey(secret);
6379
0
        if (rv != SECSuccess) {
6380
0
            return SECFailure;
6381
0
        }
6382
6383
        /* Cache the session. */
6384
0
        ssl_CacheSessionID(ss);
6385
0
    }
6386
6387
0
    return SECSuccess;
6388
0
}
6389
6390
#define _M_NONE 0
6391
5.81k
#define _M(a) (1 << PR_MIN(a, 31))
6392
#define _M1(a) (_M(ssl_hs_##a))
6393
#define _M2(a, b) (_M1(a) | _M1(b))
6394
#define _M3(a, b, c) (_M1(a) | _M2(b, c))
6395
6396
static const struct {
6397
    PRUint16 ex_value;
6398
    PRUint32 messages;
6399
} KnownExtensions[] = {
6400
    { ssl_server_name_xtn, _M2(client_hello, encrypted_extensions) },
6401
    { ssl_supported_groups_xtn, _M2(client_hello, encrypted_extensions) },
6402
    { ssl_signature_algorithms_xtn, _M2(client_hello, certificate_request) },
6403
    { ssl_signature_algorithms_cert_xtn, _M2(client_hello,
6404
                                             certificate_request) },
6405
    { ssl_use_srtp_xtn, _M2(client_hello, encrypted_extensions) },
6406
    { ssl_app_layer_protocol_xtn, _M2(client_hello, encrypted_extensions) },
6407
    { ssl_padding_xtn, _M1(client_hello) },
6408
    { ssl_tls13_key_share_xtn, _M3(client_hello, server_hello,
6409
                                   hello_retry_request) },
6410
    { ssl_tls13_pre_shared_key_xtn, _M2(client_hello, server_hello) },
6411
    { ssl_tls13_psk_key_exchange_modes_xtn, _M1(client_hello) },
6412
    { ssl_tls13_early_data_xtn, _M3(client_hello, encrypted_extensions,
6413
                                    new_session_ticket) },
6414
    { ssl_signed_cert_timestamp_xtn, _M3(client_hello, certificate_request,
6415
                                         certificate) },
6416
    { ssl_cert_status_xtn, _M3(client_hello, certificate_request,
6417
                               certificate) },
6418
    { ssl_delegated_credentials_xtn, _M2(client_hello, certificate) },
6419
    { ssl_tls13_cookie_xtn, _M2(client_hello, hello_retry_request) },
6420
    { ssl_tls13_certificate_authorities_xtn, _M2(client_hello, certificate_request) },
6421
    { ssl_tls13_supported_versions_xtn, _M3(client_hello, server_hello,
6422
                                            hello_retry_request) },
6423
    { ssl_record_size_limit_xtn, _M2(client_hello, encrypted_extensions) },
6424
    { ssl_tls13_encrypted_client_hello_xtn, _M3(client_hello, encrypted_extensions, hello_retry_request) },
6425
    { ssl_tls13_outer_extensions_xtn, _M_NONE /* Encoding/decoding only */ },
6426
    { ssl_tls13_post_handshake_auth_xtn, _M1(client_hello) },
6427
    { ssl_certificate_compression_xtn, _M2(client_hello, certificate_request) }
6428
};
6429
6430
tls13ExtensionStatus
6431
tls13_ExtensionStatus(PRUint16 extension, SSLHandshakeType message)
6432
5.81k
{
6433
5.81k
    unsigned int i;
6434
6435
5.81k
    PORT_Assert((message == ssl_hs_client_hello) ||
6436
5.81k
                (message == ssl_hs_server_hello) ||
6437
5.81k
                (message == ssl_hs_hello_retry_request) ||
6438
5.81k
                (message == ssl_hs_encrypted_extensions) ||
6439
5.81k
                (message == ssl_hs_new_session_ticket) ||
6440
5.81k
                (message == ssl_hs_certificate) ||
6441
5.81k
                (message == ssl_hs_certificate_request));
6442
6443
72.9k
    for (i = 0; i < PR_ARRAY_SIZE(KnownExtensions); i++) {
6444
        /* Hacky check for message numbers > 30. */
6445
72.9k
        PORT_Assert(!(KnownExtensions[i].messages & (1U << 31)));
6446
72.9k
        if (KnownExtensions[i].ex_value == extension) {
6447
5.81k
            break;
6448
5.81k
        }
6449
72.9k
    }
6450
5.81k
    if (i >= PR_ARRAY_SIZE(KnownExtensions)) {
6451
1
        return tls13_extension_unknown;
6452
1
    }
6453
6454
    /* Return "disallowed" if the message mask bit isn't set. */
6455
5.81k
    if (!(_M(message) & KnownExtensions[i].messages)) {
6456
5
        return tls13_extension_disallowed;
6457
5
    }
6458
6459
5.81k
    return tls13_extension_allowed;
6460
5.81k
}
6461
6462
#undef _M
6463
#undef _M1
6464
#undef _M2
6465
#undef _M3
6466
6467
/* We cheat a bit on additional data because the AEAD interface
6468
 * which doesn't have room for the record number. The AAD we
6469
 * format is serialized record number followed by the true AD
6470
 * (i.e., the record header) plus the serialized record number. */
6471
static SECStatus
6472
tls13_FormatAdditionalData(
6473
    sslSocket *ss,
6474
    const PRUint8 *header, unsigned int headerLen,
6475
    DTLSEpoch epoch, sslSequenceNumber seqNum,
6476
    PRUint8 *aad, unsigned int *aadLength, unsigned int maxLength)
6477
10.7k
{
6478
10.7k
    SECStatus rv;
6479
10.7k
    sslBuffer buf = SSL_BUFFER_FIXED(aad, maxLength);
6480
6481
10.7k
    if (IS_DTLS_1_OR_12(ss)) {
6482
0
        rv = sslBuffer_AppendNumber(&buf, epoch, 2);
6483
0
        if (rv != SECSuccess) {
6484
0
            return SECFailure;
6485
0
        }
6486
0
    }
6487
10.7k
    rv = sslBuffer_AppendNumber(&buf, seqNum, IS_DTLS_1_OR_12(ss) ? 6 : 8);
6488
10.7k
    if (rv != SECSuccess) {
6489
0
        return SECFailure;
6490
0
    }
6491
6492
10.7k
    rv = sslBuffer_Append(&buf, header, headerLen);
6493
10.7k
    if (rv != SECSuccess) {
6494
0
        return SECFailure;
6495
0
    }
6496
6497
10.7k
    *aadLength = buf.len;
6498
6499
10.7k
    return SECSuccess;
6500
10.7k
}
6501
6502
PRInt32
6503
tls13_LimitEarlyData(sslSocket *ss, SSLContentType type, PRInt32 toSend)
6504
0
{
6505
0
    PRInt32 reduced;
6506
6507
0
    PORT_Assert(type == ssl_ct_application_data);
6508
0
    PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
6509
0
    PORT_Assert(!ss->firstHsDone);
6510
0
    if (ss->ssl3.cwSpec->epoch != TrafficKeyEarlyApplicationData) {
6511
0
        return toSend;
6512
0
    }
6513
6514
0
    if (IS_DTLS(ss) && toSend > ss->ssl3.cwSpec->earlyDataRemaining) {
6515
        /* Don't split application data records in DTLS. */
6516
0
        return 0;
6517
0
    }
6518
6519
0
    reduced = PR_MIN(toSend, ss->ssl3.cwSpec->earlyDataRemaining);
6520
0
    ss->ssl3.cwSpec->earlyDataRemaining -= reduced;
6521
0
    return reduced;
6522
0
}
6523
6524
SECStatus
6525
tls13_ProtectRecord(sslSocket *ss,
6526
                    ssl3CipherSpec *cwSpec,
6527
                    SSLContentType type,
6528
                    const PRUint8 *pIn,
6529
                    PRUint32 contentLen,
6530
                    sslBuffer *wrBuf)
6531
10.9k
{
6532
10.9k
    const ssl3BulkCipherDef *cipher_def = cwSpec->cipherDef;
6533
10.9k
    const int tagLen = cipher_def->tag_size;
6534
10.9k
    SECStatus rv;
6535
6536
10.9k
    PORT_Assert(cwSpec->direction == ssl_secret_write);
6537
10.9k
    SSL_TRC(3, ("%d: TLS13[%d]: spec=%d epoch=%d (%s) protect 0x%0llx len=%u",
6538
10.9k
                SSL_GETPID(), ss->fd, cwSpec, cwSpec->epoch, cwSpec->phase,
6539
10.9k
                cwSpec->nextSeqNum, contentLen));
6540
6541
10.9k
    if (contentLen + 1 + tagLen > SSL_BUFFER_SPACE(wrBuf)) {
6542
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6543
0
        return SECFailure;
6544
0
    }
6545
6546
    /* Copy the data into the wrBuf. We're going to encrypt in-place
6547
     * in the AEAD branch anyway */
6548
10.9k
    PORT_Memcpy(SSL_BUFFER_NEXT(wrBuf), pIn, contentLen);
6549
6550
10.9k
    if (cipher_def->calg == ssl_calg_null) {
6551
        /* Shortcut for plaintext */
6552
10.7k
        rv = sslBuffer_Skip(wrBuf, contentLen, NULL);
6553
10.7k
        PORT_Assert(rv == SECSuccess);
6554
10.7k
    } else {
6555
173
        PRUint8 hdr[13];
6556
173
        sslBuffer buf = SSL_BUFFER_FIXED(hdr, sizeof(hdr));
6557
173
        PRBool needsLength;
6558
173
        PRUint8 aad[21];
6559
173
        const int ivLen = cipher_def->iv_size + cipher_def->explicit_nonce_size;
6560
173
        unsigned int ivOffset = ivLen - sizeof(sslSequenceNumber);
6561
173
        unsigned char ivOut[MAX_IV_LENGTH];
6562
6563
173
        unsigned int aadLen;
6564
173
        unsigned int len;
6565
6566
173
        PORT_Assert(cipher_def->type == type_aead);
6567
6568
        /* If the following condition holds, we can skip the padding logic for
6569
         * DTLS 1.3 (4.2.3). This will be the case until we support a cipher
6570
         * with tag length < 15B. */
6571
173
        PORT_Assert(tagLen + 1 /* cType */ >= 16);
6572
6573
        /* Add the content type at the end. */
6574
173
        *(SSL_BUFFER_NEXT(wrBuf) + contentLen) = type;
6575
6576
        /* Create the header (ugly that we have to do it twice). */
6577
173
        rv = ssl_InsertRecordHeader(ss, cwSpec, ssl_ct_application_data,
6578
173
                                    &buf, &needsLength);
6579
173
        if (rv != SECSuccess) {
6580
0
            return SECFailure;
6581
0
        }
6582
173
        if (needsLength) {
6583
173
            rv = sslBuffer_AppendNumber(&buf, contentLen + 1 + tagLen, 2);
6584
173
            if (rv != SECSuccess) {
6585
0
                return SECFailure;
6586
0
            }
6587
173
        }
6588
173
        rv = tls13_FormatAdditionalData(ss, SSL_BUFFER_BASE(&buf), SSL_BUFFER_LEN(&buf),
6589
173
                                        cwSpec->epoch, cwSpec->nextSeqNum,
6590
173
                                        aad, &aadLen, sizeof(aad));
6591
173
        if (rv != SECSuccess) {
6592
0
            return SECFailure;
6593
0
        }
6594
        /* set up initial IV value */
6595
173
        ivOffset = tls13_SetupAeadIv(IS_DTLS(ss), cwSpec->version, ivOut, cwSpec->keyMaterial.iv,
6596
173
                                     ivOffset, ivLen, cwSpec->epoch);
6597
173
        rv = tls13_AEAD(cwSpec->cipherContext, PR_FALSE,
6598
173
                        CKG_GENERATE_COUNTER_XOR, ivOffset * BPB,
6599
173
                        ivOut, ivOut, ivLen,             /* iv */
6600
173
                        NULL, 0,                         /* nonce */
6601
173
                        aad + sizeof(sslSequenceNumber), /* aad */
6602
173
                        aadLen - sizeof(sslSequenceNumber),
6603
173
                        SSL_BUFFER_NEXT(wrBuf),  /* output  */
6604
173
                        &len,                    /* out len */
6605
173
                        SSL_BUFFER_SPACE(wrBuf), /* max out */
6606
173
                        tagLen,
6607
173
                        SSL_BUFFER_NEXT(wrBuf), /* input */
6608
173
                        contentLen + 1);        /* input len */
6609
173
        if (rv != SECSuccess) {
6610
0
            PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
6611
0
            return SECFailure;
6612
0
        }
6613
173
        rv = sslBuffer_Skip(wrBuf, len, NULL);
6614
173
        PORT_Assert(rv == SECSuccess);
6615
173
    }
6616
6617
10.9k
    return SECSuccess;
6618
10.9k
}
6619
6620
/* Unprotect a TLS 1.3 record and leave the result in plaintext.
6621
 *
6622
 * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
6623
 * Therefore, we MUST not call SSL3_SendAlert().
6624
 *
6625
 * If SECFailure is returned, we:
6626
 * 1. Set |*alert| to the alert to be sent.
6627
 * 2. Call PORT_SetError() with an appropriate code.
6628
 */
6629
SECStatus
6630
tls13_UnprotectRecord(sslSocket *ss,
6631
                      ssl3CipherSpec *spec,
6632
                      SSL3Ciphertext *cText,
6633
                      sslBuffer *plaintext,
6634
                      SSLContentType *innerType,
6635
                      SSL3AlertDescription *alert)
6636
11.0k
{
6637
11.0k
    const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
6638
11.0k
    const int ivLen = cipher_def->iv_size + cipher_def->explicit_nonce_size;
6639
11.0k
    const int tagLen = cipher_def->tag_size;
6640
11.0k
    const int innerTypeLen = 1;
6641
6642
11.0k
    PRUint8 aad[21];
6643
11.0k
    unsigned int aadLen;
6644
11.0k
    SECStatus rv;
6645
6646
11.0k
    *alert = bad_record_mac; /* Default alert for most issues. */
6647
6648
11.0k
    PORT_Assert(spec->direction == ssl_secret_read);
6649
11.0k
    SSL_TRC(3, ("%d: TLS13[%d]: spec=%d epoch=%d (%s) unprotect 0x%0llx len=%u",
6650
11.0k
                SSL_GETPID(), ss->fd, spec, spec->epoch, spec->phase,
6651
11.0k
                cText->seqNum, cText->buf->len));
6652
6653
    /* Verify that the outer content type is right.
6654
     *
6655
     * For the inner content type as well as lower TLS versions this is checked
6656
     * in ssl3con.c/ssl3_HandleNonApllicationData().
6657
     *
6658
     * For DTLS 1.3 this is checked in ssl3gthr.c/dtls_GatherData(). DTLS drops
6659
     * invalid records silently [RFC6347, Section 4.1.2.7].
6660
     *
6661
     * Also allow the DTLS short header in TLS 1.3. */
6662
11.0k
    if (!(cText->hdr[0] == ssl_ct_application_data ||
6663
11.0k
          (IS_DTLS(ss) &&
6664
11.0k
           ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
6665
11.0k
           (cText->hdr[0] & 0xe0) == 0x20))) {
6666
538
        SSL_TRC(3,
6667
538
                ("%d: TLS13[%d]: record has invalid exterior type=%2.2x",
6668
538
                 SSL_GETPID(), ss->fd, cText->hdr[0]));
6669
538
        PORT_SetError(SSL_ERROR_RX_UNEXPECTED_RECORD_TYPE);
6670
538
        *alert = unexpected_message;
6671
538
        return SECFailure;
6672
538
    }
6673
6674
    /* We can perform this test in variable time because the record's total
6675
     * length and the ciphersuite are both public knowledge. */
6676
10.5k
    if (cText->buf->len < tagLen) {
6677
0
        SSL_TRC(3,
6678
0
                ("%d: TLS13[%d]: record too short to contain valid AEAD data",
6679
0
                 SSL_GETPID(), ss->fd));
6680
0
        PORT_SetError(SSL_ERROR_BAD_MAC_READ);
6681
0
        return SECFailure;
6682
0
    }
6683
6684
    /* Check if the ciphertext can be valid if we assume maximum plaintext and
6685
     * add the specific ciphersuite expansion.
6686
     * This way we detect overlong plaintexts/padding before decryption.
6687
     * This check enforces size limitations more strict than the RFC.
6688
     * (see RFC8446, Section 5.2) */
6689
10.5k
    if (cText->buf->len > (spec->recordSizeLimit + innerTypeLen + tagLen)) {
6690
13
        *alert = record_overflow;
6691
13
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
6692
13
        return SECFailure;
6693
13
    }
6694
6695
    /* Check the version number in the record. Stream only. */
6696
10.5k
    if (!IS_DTLS(ss)) {
6697
0
        SSL3ProtocolVersion version =
6698
0
            ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
6699
0
            (SSL3ProtocolVersion)cText->hdr[2];
6700
0
        if (version != spec->recordVersion) {
6701
            /* Do we need a better error here? */
6702
0
            SSL_TRC(3, ("%d: TLS13[%d]: record has bogus version",
6703
0
                        SSL_GETPID(), ss->fd));
6704
0
            return SECFailure;
6705
0
        }
6706
0
    }
6707
6708
    /* Decrypt */
6709
10.5k
    PORT_Assert(cipher_def->type == type_aead);
6710
10.5k
    rv = tls13_FormatAdditionalData(ss, cText->hdr, cText->hdrLen,
6711
10.5k
                                    spec->epoch, cText->seqNum,
6712
10.5k
                                    aad, &aadLen, sizeof(aad));
6713
10.5k
    if (rv != SECSuccess) {
6714
6715
0
        return SECFailure;
6716
0
    }
6717
10.5k
    rv = tls13_AEAD(spec->cipherContext, PR_TRUE,
6718
10.5k
                    CKG_NO_GENERATE, 0,                /* ignored for decrypt */
6719
10.5k
                    spec->keyMaterial.iv, NULL, ivLen, /* iv */
6720
10.5k
                    aad, sizeof(sslSequenceNumber),    /* nonce */
6721
10.5k
                    aad + sizeof(sslSequenceNumber),   /* aad */
6722
10.5k
                    aadLen - sizeof(sslSequenceNumber),
6723
10.5k
                    plaintext->buf,   /* output  */
6724
10.5k
                    &plaintext->len,  /* outlen */
6725
10.5k
                    plaintext->space, /* maxout */
6726
10.5k
                    tagLen,
6727
10.5k
                    cText->buf->buf,  /* in */
6728
10.5k
                    cText->buf->len); /* inlen */
6729
10.5k
    if (rv != SECSuccess) {
6730
10.5k
        if (IS_DTLS(ss)) {
6731
10.5k
            spec->deprotectionFailures++;
6732
10.5k
        }
6733
6734
10.5k
        SSL_TRC(3,
6735
10.5k
                ("%d: TLS13[%d]: record has bogus MAC",
6736
10.5k
                 SSL_GETPID(), ss->fd));
6737
10.5k
        PORT_SetError(SSL_ERROR_BAD_MAC_READ);
6738
10.5k
        return SECFailure;
6739
10.5k
    }
6740
6741
    /* There is a similar test in ssl3_HandleRecord, but this test is needed to
6742
     * account for padding. */
6743
0
    if (plaintext->len > spec->recordSizeLimit + innerTypeLen) {
6744
0
        *alert = record_overflow;
6745
0
        PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
6746
0
        return SECFailure;
6747
0
    }
6748
6749
    /* The record is right-padded with 0s, followed by the true
6750
     * content type, so read from the right until we receive a
6751
     * nonzero byte. */
6752
0
    while (plaintext->len > 0 && !(plaintext->buf[plaintext->len - 1])) {
6753
0
        --plaintext->len;
6754
0
    }
6755
6756
    /* Bogus padding. */
6757
0
    if (plaintext->len < 1) {
6758
0
        SSL_TRC(3, ("%d: TLS13[%d]: empty record", SSL_GETPID(), ss->fd));
6759
        /* It's safe to report this specifically because it happened
6760
         * after the MAC has been verified. */
6761
0
        *alert = unexpected_message;
6762
0
        PORT_SetError(SSL_ERROR_BAD_BLOCK_PADDING);
6763
0
        return SECFailure;
6764
0
    }
6765
6766
    /* Record the type. */
6767
0
    *innerType = (SSLContentType)plaintext->buf[plaintext->len - 1];
6768
0
    --plaintext->len;
6769
6770
    /* Check for zero-length encrypted Alert and Handshake fragments
6771
     * (zero-length + inner content type byte).
6772
     *
6773
     * Implementations MUST NOT send Handshake and Alert records that have a
6774
     * zero-length TLSInnerPlaintext.content; if such a message is received,
6775
     * the receiving implementation MUST terminate the connection with an
6776
     * "unexpected_message" alert [RFC8446, Section 5.4]. */
6777
0
    if (!plaintext->len && ((!IS_DTLS(ss) && cText->hdr[0] == ssl_ct_application_data) ||
6778
0
                            (IS_DTLS(ss) && dtls_IsDtls13Ciphertext(spec->version, cText->hdr[0])))) {
6779
0
        switch (*innerType) {
6780
0
            case ssl_ct_alert:
6781
0
                *alert = unexpected_message;
6782
0
                PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
6783
0
                return SECFailure;
6784
0
            case ssl_ct_handshake:
6785
0
                *alert = unexpected_message;
6786
0
                PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
6787
0
                return SECFailure;
6788
0
            default:
6789
0
                break;
6790
0
        }
6791
0
    }
6792
6793
    /* Check that we haven't received too much 0-RTT data. */
6794
0
    if (spec->epoch == TrafficKeyEarlyApplicationData &&
6795
0
        *innerType == ssl_ct_application_data) {
6796
0
        if (plaintext->len > spec->earlyDataRemaining) {
6797
0
            *alert = unexpected_message;
6798
0
            PORT_SetError(SSL_ERROR_TOO_MUCH_EARLY_DATA);
6799
0
            return SECFailure;
6800
0
        }
6801
0
        spec->earlyDataRemaining -= plaintext->len;
6802
0
    }
6803
6804
0
    SSL_TRC(10,
6805
0
            ("%d: TLS13[%d]: %s received record of length=%d, type=%d",
6806
0
             SSL_GETPID(), ss->fd, SSL_ROLE(ss), plaintext->len, *innerType));
6807
6808
0
    return SECSuccess;
6809
0
}
6810
6811
/* 0-RTT is only permitted if:
6812
 *
6813
 * 1. We are doing TLS 1.3
6814
 * 2. This isn't a second ClientHello (in response to HelloRetryRequest)
6815
 * 3. The 0-RTT option is set.
6816
 * 4. We have a valid ticket or an External PSK.
6817
 * 5. If resuming:
6818
 *    5a. The server is willing to accept 0-RTT.
6819
 *    5b. We have not changed our ALPN settings to disallow the ALPN tag
6820
 *    in the ticket.
6821
 *
6822
 * Called from tls13_ClientSendEarlyDataXtn().
6823
 */
6824
PRBool
6825
tls13_ClientAllow0Rtt(const sslSocket *ss, const sslSessionID *sid)
6826
11.0k
{
6827
    /* We checked that the cipher suite was still allowed back in
6828
     * ssl3_SendClientHello. */
6829
11.0k
    if (sid->version < SSL_LIBRARY_VERSION_TLS_1_3) {
6830
1.47k
        return PR_FALSE;
6831
1.47k
    }
6832
9.52k
    if (ss->ssl3.hs.helloRetry) {
6833
1.27k
        return PR_FALSE;
6834
1.27k
    }
6835
8.25k
    if (!ss->opt.enable0RttData) {
6836
4.20k
        return PR_FALSE;
6837
4.20k
    }
6838
4.05k
    if (PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)) {
6839
1.86k
        return PR_FALSE;
6840
1.86k
    }
6841
2.18k
    sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
6842
6843
2.18k
    if (psk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL) {
6844
2.18k
        return PR_FALSE;
6845
2.18k
    }
6846
0
    if (!psk->maxEarlyData) {
6847
0
        return PR_FALSE;
6848
0
    }
6849
6850
0
    if (psk->type == ssl_psk_external) {
6851
0
        return psk->hash == tls13_GetHashForCipherSuite(psk->zeroRttSuite);
6852
0
    }
6853
0
    if (psk->type == ssl_psk_resume) {
6854
0
        if (!ss->statelessResume)
6855
0
            return PR_FALSE;
6856
0
        if ((sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data) == 0)
6857
0
            return PR_FALSE;
6858
0
        return ssl_AlpnTagAllowed(ss, &sid->u.ssl3.alpnSelection);
6859
0
    }
6860
0
    PORT_Assert(0);
6861
0
    return PR_FALSE;
6862
0
}
6863
6864
SECStatus
6865
tls13_MaybeDo0RTTHandshake(sslSocket *ss)
6866
9.52k
{
6867
9.52k
    SECStatus rv;
6868
6869
    /* Don't do anything if there is no early_data xtn, which means we're
6870
     * not doing early data. */
6871
9.52k
    if (!ssl3_ExtensionAdvertised(ss, ssl_tls13_early_data_xtn)) {
6872
9.52k
        return SECSuccess;
6873
9.52k
    }
6874
6875
0
    ss->ssl3.hs.zeroRttState = ssl_0rtt_sent;
6876
0
    ss->ssl3.hs.zeroRttSuite = ss->ssl3.hs.cipher_suite;
6877
    /* Note: Reset the preliminary info here rather than just add 0-RTT.  We are
6878
     * only guessing what might happen at this point.*/
6879
0
    ss->ssl3.hs.preliminaryInfo = ssl_preinfo_0rtt_cipher_suite;
6880
6881
0
    SSL_TRC(3, ("%d: TLS13[%d]: in 0-RTT mode", SSL_GETPID(), ss->fd));
6882
6883
    /* Set the ALPN data as if it was negotiated. We check in the ServerHello
6884
     * handler that the server negotiates the same value. */
6885
0
    if (ss->sec.ci.sid->u.ssl3.alpnSelection.len) {
6886
0
        ss->xtnData.nextProtoState = SSL_NEXT_PROTO_EARLY_VALUE;
6887
0
        rv = SECITEM_CopyItem(NULL, &ss->xtnData.nextProto,
6888
0
                              &ss->sec.ci.sid->u.ssl3.alpnSelection);
6889
0
        if (rv != SECSuccess) {
6890
0
            return SECFailure;
6891
0
        }
6892
0
    }
6893
6894
0
    if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) {
6895
        /* Pretend that this is a proper ChangeCipherSpec even though it is sent
6896
         * before receiving the ServerHello. */
6897
0
        ssl_GetSpecWriteLock(ss);
6898
0
        tls13_SetSpecRecordVersion(ss, ss->ssl3.cwSpec);
6899
0
        ssl_ReleaseSpecWriteLock(ss);
6900
0
        ssl_GetXmitBufLock(ss);
6901
0
        rv = ssl3_SendChangeCipherSpecsInt(ss);
6902
0
        ssl_ReleaseXmitBufLock(ss);
6903
0
        if (rv != SECSuccess) {
6904
0
            return SECFailure;
6905
0
        }
6906
0
    }
6907
6908
    /* If we have any message that was saved for later hashing.
6909
     * The updated hash is then used in tls13_DeriveEarlySecrets. */
6910
0
    rv = ssl3_MaybeUpdateHashWithSavedRecord(ss);
6911
0
    if (rv != SECSuccess) {
6912
0
        return SECFailure;
6913
0
    }
6914
6915
    /* If we're trying 0-RTT, derive from the first PSK */
6916
0
    PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) && !ss->xtnData.selectedPsk);
6917
0
    ss->xtnData.selectedPsk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
6918
0
    rv = tls13_DeriveEarlySecrets(ss);
6919
0
    if (rv != SECSuccess) {
6920
0
        return SECFailure;
6921
0
    }
6922
6923
    /* Save cwSpec in case we get a HelloRetryRequest and have to send another
6924
     * ClientHello. */
6925
0
    ssl_CipherSpecAddRef(ss->ssl3.cwSpec);
6926
6927
0
    rv = tls13_SetCipherSpec(ss, TrafficKeyEarlyApplicationData,
6928
0
                             ssl_secret_write, PR_TRUE);
6929
0
    ss->xtnData.selectedPsk = NULL;
6930
0
    if (rv != SECSuccess) {
6931
0
        return SECFailure;
6932
0
    }
6933
6934
0
    return SECSuccess;
6935
0
}
6936
6937
PRInt32
6938
tls13_Read0RttData(sslSocket *ss, PRUint8 *buf, PRInt32 len)
6939
0
{
6940
0
    PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData));
6941
0
    PRInt32 offset = 0;
6942
0
    while (!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)) {
6943
0
        TLS13EarlyData *msg =
6944
0
            (TLS13EarlyData *)PR_NEXT_LINK(&ss->ssl3.hs.bufferedEarlyData);
6945
0
        unsigned int tocpy = msg->data.len - msg->consumed;
6946
6947
0
        if (tocpy > (len - offset)) {
6948
0
            if (IS_DTLS(ss)) {
6949
                /* In DTLS, we only return entire records.
6950
                 * So offset and consumed are always zero. */
6951
0
                PORT_Assert(offset == 0);
6952
0
                PORT_Assert(msg->consumed == 0);
6953
0
                PORT_SetError(SSL_ERROR_RX_SHORT_DTLS_READ);
6954
0
                return -1;
6955
0
            }
6956
6957
0
            tocpy = len - offset;
6958
0
        }
6959
6960
0
        PORT_Memcpy(buf + offset, msg->data.data + msg->consumed, tocpy);
6961
0
        offset += tocpy;
6962
0
        msg->consumed += tocpy;
6963
6964
0
        if (msg->consumed == msg->data.len) {
6965
0
            PR_REMOVE_LINK(&msg->link);
6966
0
            SECITEM_ZfreeItem(&msg->data, PR_FALSE);
6967
0
            PORT_ZFree(msg, sizeof(*msg));
6968
0
        }
6969
6970
        /* We are done after one record for DTLS; otherwise, when the buffer fills up. */
6971
0
        if (IS_DTLS(ss) || offset == len) {
6972
0
            break;
6973
0
        }
6974
0
    }
6975
6976
0
    return offset;
6977
0
}
6978
6979
static SECStatus
6980
tls13_SendEndOfEarlyData(sslSocket *ss)
6981
0
{
6982
0
    SECStatus rv;
6983
6984
0
    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6985
6986
0
    if (!ss->opt.suppressEndOfEarlyData) {
6987
0
        SSL_TRC(3, ("%d: TLS13[%d]: send EndOfEarlyData", SSL_GETPID(), ss->fd));
6988
0
        rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_end_of_early_data, 0);
6989
0
        if (rv != SECSuccess) {
6990
0
            return rv; /* err set by AppendHandshake. */
6991
0
        }
6992
0
    }
6993
6994
0
    ss->ssl3.hs.zeroRttState = ssl_0rtt_done;
6995
0
    return SECSuccess;
6996
0
}
6997
6998
static SECStatus
6999
tls13_HandleEndOfEarlyData(sslSocket *ss, const PRUint8 *b, PRUint32 length)
7000
1
{
7001
1
    SECStatus rv;
7002
7003
1
    PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
7004
7005
1
    rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_END_OF_EARLY_DATA,
7006
1
                              wait_end_of_early_data);
7007
1
    if (rv != SECSuccess) {
7008
1
        return SECFailure;
7009
1
    }
7010
7011
    /* We shouldn't be getting any more early data, and if we do,
7012
     * it is because of reordering and we drop it. */
7013
0
    if (IS_DTLS(ss)) {
7014
0
        ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read,
7015
0
                                     TrafficKeyEarlyApplicationData);
7016
0
        dtls_ReceivedFirstMessageInFlight(ss);
7017
0
    }
7018
7019
0
    PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted);
7020
7021
0
    if (length) {
7022
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_END_OF_EARLY_DATA, decode_error);
7023
0
        return SECFailure;
7024
0
    }
7025
7026
0
    rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
7027
0
                             ssl_secret_read, PR_FALSE);
7028
0
    if (rv != SECSuccess) {
7029
0
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
7030
0
        return SECFailure;
7031
0
    }
7032
7033
0
    ss->ssl3.hs.zeroRttState = ssl_0rtt_done;
7034
0
    if (tls13_ShouldRequestClientAuth(ss)) {
7035
0
        TLS13_SET_HS_STATE(ss, wait_client_cert);
7036
0
    } else {
7037
0
        TLS13_SET_HS_STATE(ss, wait_finished);
7038
0
    }
7039
0
    return SECSuccess;
7040
0
}
7041
7042
static SECStatus
7043
tls13_MaybeHandleSuppressedEndOfEarlyData(sslSocket *ss)
7044
0
{
7045
0
    PORT_Assert(ss->sec.isServer);
7046
0
    if (!ss->opt.suppressEndOfEarlyData ||
7047
0
        ss->ssl3.hs.zeroRttState != ssl_0rtt_accepted) {
7048
0
        return SECSuccess;
7049
0
    }
7050
7051
0
    return tls13_HandleEndOfEarlyData(ss, NULL, 0);
7052
0
}
7053
7054
SECStatus
7055
tls13_HandleEarlyApplicationData(sslSocket *ss, sslBuffer *origBuf)
7056
0
{
7057
0
    TLS13EarlyData *ed;
7058
0
    SECItem it = { siBuffer, NULL, 0 };
7059
7060
0
    PORT_Assert(ss->sec.isServer);
7061
0
    PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted);
7062
0
    if (ss->ssl3.hs.zeroRttState != ssl_0rtt_accepted) {
7063
        /* Belt and suspenders. */
7064
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
7065
0
        return SECFailure;
7066
0
    }
7067
7068
0
    PRINT_BUF(3, (NULL, "Received early application data",
7069
0
                  origBuf->buf, origBuf->len));
7070
0
    ed = PORT_ZNew(TLS13EarlyData);
7071
0
    if (!ed) {
7072
0
        FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
7073
0
        return SECFailure;
7074
0
    }
7075
0
    it.data = origBuf->buf;
7076
0
    it.len = origBuf->len;
7077
0
    if (SECITEM_CopyItem(NULL, &ed->data, &it) != SECSuccess) {
7078
0
        FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
7079
0
        return SECFailure;
7080
0
    }
7081
0
    PR_APPEND_LINK(&ed->link, &ss->ssl3.hs.bufferedEarlyData);
7082
7083
0
    origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
7084
7085
0
    return SECSuccess;
7086
0
}
7087
7088
PRUint16
7089
tls13_EncodeVersion(SSL3ProtocolVersion version, SSLProtocolVariant variant)
7090
28.2k
{
7091
28.2k
    if (variant == ssl_variant_datagram) {
7092
28.2k
        return dtls_TLSVersionToDTLSVersion(version);
7093
28.2k
    }
7094
    /* Stream-variant encodings do not change. */
7095
0
    return (PRUint16)version;
7096
28.2k
}
7097
7098
SECStatus
7099
tls13_ClientReadSupportedVersion(sslSocket *ss)
7100
8.47k
{
7101
8.47k
    PRUint32 temp;
7102
8.47k
    TLSExtension *versionExtension;
7103
8.47k
    SECItem it;
7104
8.47k
    SECStatus rv;
7105
7106
    /* Update the version based on the extension, as necessary. */
7107
8.47k
    versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
7108
8.47k
    if (!versionExtension) {
7109
5.58k
        return SECSuccess;
7110
5.58k
    }
7111
7112
    /* Struct copy so we don't damage the extension. */
7113
2.89k
    it = versionExtension->data;
7114
7115
2.89k
    rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, &it.data, &it.len);
7116
2.89k
    if (rv != SECSuccess) {
7117
1
        return SECFailure;
7118
1
    }
7119
2.89k
    if (it.len) {
7120
1
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
7121
1
        return SECFailure;
7122
1
    }
7123
7124
2.89k
    if (temp != tls13_EncodeVersion(SSL_LIBRARY_VERSION_TLS_1_3,
7125
2.89k
                                    ss->protocolVariant)) {
7126
        /* You cannot negotiate < TLS 1.3 with supported_versions. */
7127
13
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
7128
13
        return SECFailure;
7129
13
    }
7130
7131
    /* Any endpoint receiving a Hello message with...ServerHello.legacy_version
7132
     * set to 0x0300 (SSL3) MUST abort the handshake with a "protocol_version"
7133
     * alert. [RFC8446, Section D.5]
7134
     *
7135
     * The ServerHello.legacy_version is read into the ss->version field by
7136
     * ssl_ClientReadVersion(). */
7137
2.87k
    if (ss->version == SSL_LIBRARY_VERSION_3_0) {
7138
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, protocol_version);
7139
0
        return SECFailure;
7140
0
    }
7141
7142
2.87k
    ss->version = SSL_LIBRARY_VERSION_TLS_1_3;
7143
2.87k
    return SECSuccess;
7144
2.87k
}
7145
7146
/* Pick the highest version we support that is also advertised. */
7147
SECStatus
7148
tls13_NegotiateVersion(sslSocket *ss, const TLSExtension *supportedVersions)
7149
0
{
7150
0
    PRUint16 version;
7151
    /* Make a copy so we're nondestructive. */
7152
0
    SECItem data = supportedVersions->data;
7153
0
    SECItem versions;
7154
0
    SECStatus rv;
7155
7156
0
    rv = ssl3_ConsumeHandshakeVariable(ss, &versions, 1,
7157
0
                                       &data.data, &data.len);
7158
0
    if (rv != SECSuccess) {
7159
0
        return SECFailure;
7160
0
    }
7161
0
    if (data.len || !versions.len || (versions.len & 1)) {
7162
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
7163
0
        return SECFailure;
7164
0
    }
7165
0
    for (version = ss->vrange.max; version >= ss->vrange.min; --version) {
7166
0
        if (version < SSL_LIBRARY_VERSION_TLS_1_3 &&
7167
0
            (ss->ssl3.hs.helloRetry || ss->ssl3.hs.echAccepted)) {
7168
            /* Prevent negotiating to a lower version after 1.3 HRR or ECH
7169
             * When accepting ECH, a different alert is generated.
7170
             */
7171
0
            SSL3AlertDescription alert = ss->ssl3.hs.echAccepted ? illegal_parameter : protocol_version;
7172
0
            PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
7173
0
            FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, alert);
7174
0
            return SECFailure;
7175
0
        }
7176
7177
0
        PRUint16 wire = tls13_EncodeVersion(version, ss->protocolVariant);
7178
0
        unsigned long offset;
7179
7180
0
        for (offset = 0; offset < versions.len; offset += 2) {
7181
0
            PRUint16 supported =
7182
0
                (versions.data[offset] << 8) | versions.data[offset + 1];
7183
0
            if (supported == wire) {
7184
0
                ss->version = version;
7185
0
                return SECSuccess;
7186
0
            }
7187
0
        }
7188
0
    }
7189
7190
0
    FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, protocol_version);
7191
0
    return SECFailure;
7192
0
}
7193
7194
/* This is TLS 1.3 or might negotiate to it. */
7195
PRBool
7196
tls13_MaybeTls13(sslSocket *ss)
7197
55.7k
{
7198
55.7k
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
7199
8.85k
        return PR_TRUE;
7200
8.85k
    }
7201
7202
46.9k
    if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
7203
7.48k
        return PR_FALSE;
7204
7.48k
    }
7205
7206
39.4k
    if (!(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version)) {
7207
22.2k
        return PR_TRUE;
7208
22.2k
    }
7209
7210
17.1k
    return PR_FALSE;
7211
39.4k
}
7212
7213
/* Setup random client GREASE values according to RFC8701. State must be kept
7214
 * so an equal ClientHello might be send on HelloRetryRequest. */
7215
SECStatus
7216
tls13_ClientGreaseSetup(sslSocket *ss)
7217
7.97k
{
7218
7.97k
    if (!ss->opt.enableGrease) {
7219
4.04k
        return SECSuccess;
7220
4.04k
    }
7221
7222
3.93k
    PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
7223
7224
3.93k
    if (ss->ssl3.hs.grease) {
7225
0
        return SECFailure;
7226
0
    }
7227
3.93k
    ss->ssl3.hs.grease = PORT_Alloc(sizeof(tls13ClientGrease));
7228
3.93k
    if (!ss->ssl3.hs.grease) {
7229
0
        return SECFailure;
7230
0
    }
7231
7232
3.93k
    tls13ClientGrease *grease = ss->ssl3.hs.grease;
7233
    /* We require eight GREASE values and randoms. */
7234
3.93k
    PRUint8 random[8];
7235
7236
    /* Generate random GREASE values. */
7237
3.93k
    if (PK11_GenerateRandom(random, sizeof(random)) != SECSuccess) {
7238
0
        return SECFailure;
7239
0
    }
7240
31.4k
    for (size_t i = 0; i < PR_ARRAY_SIZE(grease->idx); i++) {
7241
27.5k
        random[i] = ((random[i] & 0xf0) | 0x0a);
7242
27.5k
        grease->idx[i] = ((random[i] << 8) | random[i]);
7243
27.5k
    }
7244
    /* Specific PskKeyExchangeMode GREASE value. */
7245
3.93k
    grease->pskKem = 0x0b + ((random[8 - 1] >> 5) * 0x1f);
7246
7247
    /* Duplicate extensions are not allowed. */
7248
3.93k
    if (grease->idx[grease_extension1] == grease->idx[grease_extension2]) {
7249
0
        grease->idx[grease_extension2] ^= 0x1010;
7250
0
    }
7251
7252
3.93k
    return SECSuccess;
7253
3.93k
}
7254
7255
/* Destroy client GREASE state. */
7256
void
7257
tls13_ClientGreaseDestroy(sslSocket *ss)
7258
18.7k
{
7259
18.7k
    if (ss->ssl3.hs.grease) {
7260
3.93k
        PORT_Free(ss->ssl3.hs.grease);
7261
3.93k
        ss->ssl3.hs.grease = NULL;
7262
3.93k
    }
7263
18.7k
}
7264
7265
/* Generate a random GREASE value according to RFC8701.
7266
 * This function does not provide valid PskKeyExchangeMode GREASE values! */
7267
SECStatus
7268
tls13_RandomGreaseValue(PRUint16 *out)
7269
0
{
7270
0
    PRUint8 random;
7271
7272
0
    if (PK11_GenerateRandom(&random, sizeof(random)) != SECSuccess) {
7273
0
        return SECFailure;
7274
0
    }
7275
7276
0
    random = ((random & 0xf0) | 0x0a);
7277
0
    *out = ((random << 8) | random);
7278
7279
0
    return SECSuccess;
7280
0
}
7281
7282
/* Set TLS 1.3 GREASE Extension random GREASE type. */
7283
SECStatus
7284
tls13_MaybeGreaseExtensionType(const sslSocket *ss,
7285
                               const SSLHandshakeType message,
7286
                               PRUint16 *exType)
7287
128k
{
7288
128k
    if (*exType != ssl_tls13_grease_xtn) {
7289
118k
        return SECSuccess;
7290
118k
    }
7291
7292
9.53k
    PR_ASSERT(ss->opt.enableGrease);
7293
9.53k
    PR_ASSERT(message == ssl_hs_client_hello ||
7294
9.53k
              message == ssl_hs_certificate_request);
7295
7296
    /* GREASE ClientHello:
7297
     * A client MAY select one or more GREASE extension values and
7298
     * advertise them as extensions with varying length and contents
7299
     * [RFC8701, Section 3.1]. */
7300
9.53k
    if (message == ssl_hs_client_hello) {
7301
9.53k
        PR_ASSERT(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
7302
        /* Check if the first GREASE extension was already added. */
7303
9.53k
        if (!ssl3_ExtensionAdvertised(ss, ss->ssl3.hs.grease->idx[grease_extension1])) {
7304
4.76k
            *exType = ss->ssl3.hs.grease->idx[grease_extension1];
7305
4.76k
        } else {
7306
4.76k
            *exType = ss->ssl3.hs.grease->idx[grease_extension2];
7307
4.76k
        }
7308
9.53k
    }
7309
    /* GREASE CertificateRequest:
7310
     * When sending a CertificateRequest in TLS 1.3, a server MAY behave as
7311
     * follows: A server MAY select one or more GREASE extension values and
7312
     * advertise them as extensions with varying length and contents
7313
     * [RFC8701, Section 4.1]. */
7314
0
    else if (message == ssl_hs_certificate_request) {
7315
0
        PR_ASSERT(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
7316
        /* Get random grease extension type. */
7317
0
        SECStatus rv = tls13_RandomGreaseValue(exType);
7318
0
        if (rv != SECSuccess) {
7319
0
            return SECFailure;
7320
0
        }
7321
0
    }
7322
7323
9.53k
    return SECSuccess;
7324
9.53k
}