Coverage Report

Created: 2026-02-05 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/nss/lib/ssl/tls13ech.c
Line
Count
Source
1
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
/*
3
 * This Source Code Form is subject to the terms of the Mozilla Public
4
 * License, v. 2.0. If a copy of the MPL was not distributed with this
5
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
#include "nss.h"
8
#include "pk11func.h"
9
#include "pk11hpke.h"
10
#include "ssl.h"
11
#include "sslproto.h"
12
#include "sslimpl.h"
13
#include "selfencrypt.h"
14
#include "ssl3exthandle.h"
15
#include "tls13ech.h"
16
#include "tls13exthandle.h"
17
#include "tls13hashstate.h"
18
#include "tls13hkdf.h"
19
20
extern SECStatus
21
ssl3_UpdateHandshakeHashesInt(sslSocket *ss, const unsigned char *b,
22
                              unsigned int l, sslBuffer *transcriptBuf);
23
extern SECStatus
24
ssl3_HandleClientHelloPreamble(sslSocket *ss, PRUint8 **b, PRUint32 *length, SECItem *sidBytes,
25
                               SECItem *cookieBytes, SECItem *suites, SECItem *comps);
26
extern SECStatus
27
tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key,
28
                   const char *label,
29
                   unsigned int labelLen,
30
                   const SSL3Hashes *hashes,
31
                   PK11SymKey **dest,
32
                   SSLHashType hash);
33
34
const char keylogLabelECHSecret[] = "ECH_SECRET";
35
const char keylogLabelECHConfig[] = "ECH_CONFIG";
36
37
PRBool
38
tls13_Debug_CheckXtnBegins(const PRUint8 *start, const PRUint16 xtnType)
39
47
{
40
47
#ifdef DEBUG
41
47
    SECStatus rv;
42
47
    sslReader ext_reader = SSL_READER(start, 2);
43
47
    PRUint64 extension_number;
44
47
    rv = sslRead_ReadNumber(&ext_reader, 2, &extension_number);
45
47
    return ((rv == SECSuccess) && (extension_number == xtnType));
46
#else
47
    return PR_TRUE;
48
#endif
49
47
}
50
51
void
52
tls13_DestroyEchConfig(sslEchConfig *config)
53
9.74k
{
54
9.74k
    if (!config) {
55
0
        return;
56
0
    }
57
9.74k
    SECITEM_FreeItem(&config->contents.publicKey, PR_FALSE);
58
9.74k
    SECITEM_FreeItem(&config->contents.suites, PR_FALSE);
59
9.74k
    SECITEM_FreeItem(&config->raw, PR_FALSE);
60
9.74k
    PORT_Free(config->contents.publicName);
61
9.74k
    config->contents.publicName = NULL;
62
9.74k
    PORT_ZFree(config, sizeof(*config));
63
9.74k
}
64
65
void
66
tls13_DestroyEchConfigs(PRCList *list)
67
76.2k
{
68
76.2k
    PRCList *cur_p;
69
86.0k
    while (!PR_CLIST_IS_EMPTY(list)) {
70
9.74k
        cur_p = PR_LIST_TAIL(list);
71
9.74k
        PR_REMOVE_LINK(cur_p);
72
9.74k
        tls13_DestroyEchConfig((sslEchConfig *)cur_p);
73
9.74k
    }
74
76.2k
}
75
76
void
77
tls13_DestroyEchXtnState(sslEchXtnState *state)
78
361k
{
79
361k
    if (!state) {
80
361k
        return;
81
361k
    }
82
236
    SECITEM_FreeItem(&state->innerCh, PR_FALSE);
83
236
    SECITEM_FreeItem(&state->senderPubKey, PR_FALSE);
84
236
    SECITEM_FreeItem(&state->retryConfigs, PR_FALSE);
85
236
    PORT_ZFree(state, sizeof(*state));
86
236
}
87
88
SECStatus
89
tls13_CopyEchConfigs(PRCList *oConfigs, PRCList *configs)
90
32.5k
{
91
32.5k
    SECStatus rv;
92
32.5k
    sslEchConfig *config;
93
32.5k
    sslEchConfig *newConfig = NULL;
94
95
32.5k
    for (PRCList *cur_p = PR_LIST_HEAD(oConfigs);
96
32.5k
         cur_p != oConfigs;
97
32.5k
         cur_p = PR_NEXT_LINK(cur_p)) {
98
0
        config = (sslEchConfig *)PR_LIST_TAIL(oConfigs);
99
0
        newConfig = PORT_ZNew(sslEchConfig);
100
0
        if (!newConfig) {
101
0
            goto loser;
102
0
        }
103
104
0
        rv = SECITEM_CopyItem(NULL, &newConfig->raw, &config->raw);
105
0
        if (rv != SECSuccess) {
106
0
            goto loser;
107
0
        }
108
0
        newConfig->contents.publicName = PORT_Strdup(config->contents.publicName);
109
0
        if (!newConfig->contents.publicName) {
110
0
            goto loser;
111
0
        }
112
0
        rv = SECITEM_CopyItem(NULL, &newConfig->contents.publicKey,
113
0
                              &config->contents.publicKey);
114
0
        if (rv != SECSuccess) {
115
0
            goto loser;
116
0
        }
117
0
        rv = SECITEM_CopyItem(NULL, &newConfig->contents.suites,
118
0
                              &config->contents.suites);
119
0
        if (rv != SECSuccess) {
120
0
            goto loser;
121
0
        }
122
0
        newConfig->contents.configId = config->contents.configId;
123
0
        newConfig->contents.kemId = config->contents.kemId;
124
0
        newConfig->contents.kdfId = config->contents.kdfId;
125
0
        newConfig->contents.aeadId = config->contents.aeadId;
126
0
        newConfig->contents.maxNameLen = config->contents.maxNameLen;
127
0
        newConfig->version = config->version;
128
0
        PR_APPEND_LINK(&newConfig->link, configs);
129
0
    }
130
32.5k
    return SECSuccess;
131
132
0
loser:
133
0
    tls13_DestroyEchConfig(newConfig);
134
0
    tls13_DestroyEchConfigs(configs);
135
0
    return SECFailure;
136
32.5k
}
137
138
/*
139
 * struct {
140
 *     HpkeKdfId kdf_id;
141
 *     HpkeAeadId aead_id;
142
 * } HpkeSymmetricCipherSuite;
143
 *
144
 * struct {
145
 *     uint8 config_id;
146
 *     HpkeKemId kem_id;
147
 *     HpkePublicKey public_key;
148
 *     HpkeSymmetricCipherSuite cipher_suites<4..2^16-4>;
149
 * } HpkeKeyConfig;
150
 *
151
 * struct {
152
 *     HpkeKeyConfig key_config;
153
 *     uint16 maximum_name_length;
154
 *     opaque public_name<1..2^16-1>;
155
 *     Extension extensions<0..2^16-1>;
156
 * } ECHConfigContents;
157
 *
158
 * struct {
159
 *     uint16 version;
160
 *     uint16 length;
161
 *     select (ECHConfig.version) {
162
 *       case 0xfe0d: ECHConfigContents contents;
163
 *     }
164
 * } ECHConfig;
165
 */
166
static SECStatus
167
tls13_DecodeEchConfigContents(const sslReadBuffer *rawConfig,
168
                              sslEchConfig **outConfig)
169
14.4k
{
170
14.4k
    SECStatus rv;
171
14.4k
    sslEchConfigContents contents = { 0 };
172
14.4k
    sslEchConfig *decodedConfig;
173
14.4k
    PRUint64 tmpn;
174
14.4k
    PRUint64 tmpn2;
175
14.4k
    sslReadBuffer tmpBuf;
176
14.4k
    PRUint16 *extensionTypes = NULL;
177
14.4k
    unsigned int extensionIndex = 0;
178
14.4k
    sslReader configReader = SSL_READER(rawConfig->buf, rawConfig->len);
179
14.4k
    sslReader suiteReader;
180
14.4k
    sslReader extensionReader;
181
14.4k
    PRBool hasValidSuite = PR_FALSE;
182
14.4k
    PRBool unsupportedMandatoryXtn = PR_FALSE;
183
184
    /* HpkeKeyConfig key_config */
185
    /* uint8 config_id */
186
14.4k
    rv = sslRead_ReadNumber(&configReader, 1, &tmpn);
187
14.4k
    if (rv != SECSuccess) {
188
3
        goto loser;
189
3
    }
190
14.3k
    contents.configId = tmpn;
191
192
    /* HpkeKemId kem_id */
193
14.3k
    rv = sslRead_ReadNumber(&configReader, 2, &tmpn);
194
14.3k
    if (rv != SECSuccess) {
195
3
        goto loser;
196
3
    }
197
14.3k
    contents.kemId = tmpn;
198
199
    /* HpkePublicKey public_key */
200
14.3k
    rv = sslRead_ReadVariable(&configReader, 2, &tmpBuf);
201
14.3k
    if (rv != SECSuccess) {
202
5
        goto loser;
203
5
    }
204
14.3k
    rv = SECITEM_MakeItem(NULL, &contents.publicKey, (PRUint8 *)tmpBuf.buf, tmpBuf.len);
205
14.3k
    if (rv != SECSuccess) {
206
0
        goto loser;
207
0
    }
208
209
    /* HpkeSymmetricCipherSuite cipher_suites<4..2^16-4> */
210
14.3k
    rv = sslRead_ReadVariable(&configReader, 2, &tmpBuf);
211
14.3k
    if (rv != SECSuccess) {
212
27
        goto loser;
213
27
    }
214
14.3k
    if (tmpBuf.len & 1) {
215
4
        PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_CONFIG);
216
4
        goto loser;
217
4
    }
218
14.3k
    suiteReader = (sslReader)SSL_READER(tmpBuf.buf, tmpBuf.len);
219
54.9k
    while (SSL_READER_REMAINING(&suiteReader)) {
220
        /* HpkeKdfId kdf_id */
221
50.5k
        rv = sslRead_ReadNumber(&suiteReader, 2, &tmpn);
222
50.5k
        if (rv != SECSuccess) {
223
0
            goto loser;
224
0
        }
225
        /* HpkeAeadId aead_id */
226
50.5k
        rv = sslRead_ReadNumber(&suiteReader, 2, &tmpn2);
227
50.5k
        if (rv != SECSuccess) {
228
18
            goto loser;
229
18
        }
230
50.5k
        if (!hasValidSuite) {
231
            /* Use the first compatible ciphersuite. */
232
50.5k
            rv = PK11_HPKE_ValidateParameters(contents.kemId, tmpn, tmpn2);
233
50.5k
            if (rv == SECSuccess) {
234
9.97k
                hasValidSuite = PR_TRUE;
235
9.97k
                contents.kdfId = tmpn;
236
9.97k
                contents.aeadId = tmpn2;
237
9.97k
                break;
238
9.97k
            }
239
50.5k
        }
240
50.5k
    }
241
242
14.3k
    rv = SECITEM_MakeItem(NULL, &contents.suites, (PRUint8 *)tmpBuf.buf, tmpBuf.len);
243
14.3k
    if (rv != SECSuccess) {
244
0
        goto loser;
245
0
    }
246
247
    /* uint8 maximum_name_length */
248
14.3k
    rv = sslRead_ReadNumber(&configReader, 1, &tmpn);
249
14.3k
    if (rv != SECSuccess) {
250
55
        goto loser;
251
55
    }
252
14.2k
    contents.maxNameLen = (PRUint8)tmpn;
253
254
    /* opaque public_name<1..2^16-1> */
255
14.2k
    rv = sslRead_ReadVariable(&configReader, 1, &tmpBuf);
256
14.2k
    if (rv != SECSuccess) {
257
13
        goto loser;
258
13
    }
259
260
14.2k
    if (tmpBuf.len == 0) {
261
7
        PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_CONFIG);
262
7
        goto loser;
263
7
    }
264
14.2k
    if (!tls13_IsLDH(tmpBuf.buf, tmpBuf.len) ||
265
14.1k
        tls13_IsIp(tmpBuf.buf, tmpBuf.len)) {
266
261
        PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_CONFIG);
267
261
        goto loser;
268
261
    }
269
270
14.0k
    contents.publicName = PORT_ZAlloc(tmpBuf.len + 1);
271
14.0k
    if (!contents.publicName) {
272
0
        goto loser;
273
0
    }
274
14.0k
    PORT_Memcpy(contents.publicName, (PRUint8 *)tmpBuf.buf, tmpBuf.len);
275
276
    /* Extensions. We don't support any, but must
277
     * check for any that are marked critical. */
278
14.0k
    rv = sslRead_ReadVariable(&configReader, 2, &tmpBuf);
279
14.0k
    if (rv != SECSuccess) {
280
157
        goto loser;
281
157
    }
282
283
13.8k
    extensionReader = (sslReader)SSL_READER(tmpBuf.buf, tmpBuf.len);
284
13.8k
    extensionTypes = PORT_NewArray(PRUint16, tmpBuf.len / 2 * sizeof(PRUint16));
285
13.8k
    if (!extensionTypes) {
286
0
        goto loser;
287
0
    }
288
289
15.9k
    while (SSL_READER_REMAINING(&extensionReader)) {
290
        /* Get the extension's type field */
291
2.19k
        rv = sslRead_ReadNumber(&extensionReader, 2, &tmpn);
292
2.19k
        if (rv != SECSuccess) {
293
15
            goto loser;
294
15
        }
295
296
5.69k
        for (unsigned int i = 0; i < extensionIndex; i++) {
297
3.51k
            if (extensionTypes[i] == tmpn) {
298
5
                PORT_SetError(SEC_ERROR_EXTENSION_VALUE_INVALID);
299
5
                goto loser;
300
5
            }
301
3.51k
        }
302
2.17k
        extensionTypes[extensionIndex++] = (PRUint16)tmpn;
303
304
        /* Clients MUST parse the extension list and check for unsupported
305
         * mandatory extensions.  If an unsupported mandatory extension is
306
         * present, clients MUST ignore the ECHConfig
307
         * [draft-ietf-tls-esni, Section 4.2]. */
308
2.17k
        if (tmpn & (1 << 15)) {
309
1.02k
            unsupportedMandatoryXtn = PR_TRUE;
310
1.02k
        }
311
312
        /* Skip. */
313
2.17k
        rv = sslRead_ReadVariable(&extensionReader, 2, &tmpBuf);
314
2.17k
        if (rv != SECSuccess) {
315
56
            goto loser;
316
56
        }
317
2.17k
    }
318
319
    /* Check that we consumed the entire ECHConfig */
320
13.7k
    if (SSL_READER_REMAINING(&configReader)) {
321
33
        PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_CONFIG);
322
33
        goto loser;
323
33
    }
324
325
    /* If the ciphersuites were compatible AND if NO unsupported mandatory
326
     * extensions were found set the outparam. Return success either way if the
327
     * config was well-formed. */
328
13.7k
    if (hasValidSuite && !unsupportedMandatoryXtn) {
329
9.74k
        decodedConfig = PORT_ZNew(sslEchConfig);
330
9.74k
        if (!decodedConfig) {
331
0
            goto loser;
332
0
        }
333
9.74k
        decodedConfig->contents = contents;
334
9.74k
        *outConfig = decodedConfig;
335
9.74k
    } else {
336
3.99k
        PORT_Free(contents.publicName);
337
3.99k
        SECITEM_FreeItem(&contents.publicKey, PR_FALSE);
338
3.99k
        SECITEM_FreeItem(&contents.suites, PR_FALSE);
339
3.99k
    }
340
13.7k
    PORT_Free(extensionTypes);
341
13.7k
    return SECSuccess;
342
343
662
loser:
344
662
    PORT_Free(extensionTypes);
345
662
    PORT_Free(contents.publicName);
346
662
    SECITEM_FreeItem(&contents.publicKey, PR_FALSE);
347
662
    SECITEM_FreeItem(&contents.suites, PR_FALSE);
348
662
    return SECFailure;
349
13.7k
}
350
351
/* Decode an ECHConfigList struct and store each ECHConfig
352
 * into |configs|.  */
353
SECStatus
354
tls13_DecodeEchConfigs(const SECItem *data, PRCList *configs)
355
9.98k
{
356
9.98k
    SECStatus rv;
357
9.98k
    sslEchConfig *decodedConfig = NULL;
358
9.98k
    sslReader rdr = SSL_READER(data->data, data->len);
359
9.98k
    sslReadBuffer tmp;
360
9.98k
    sslReadBuffer singleConfig;
361
9.98k
    PRUint64 version;
362
9.98k
    PRUint64 length;
363
9.98k
    PORT_Assert(PR_CLIST_IS_EMPTY(configs));
364
365
9.98k
    rv = sslRead_ReadVariable(&rdr, 2, &tmp);
366
9.98k
    if (rv != SECSuccess) {
367
23
        return SECFailure;
368
23
    }
369
9.96k
    SSL_TRC(100, ("Read EchConfig list of size %u", SSL_READER_REMAINING(&rdr)));
370
9.96k
    if (SSL_READER_REMAINING(&rdr)) {
371
71
        PORT_SetError(SEC_ERROR_BAD_DATA);
372
71
        return SECFailure;
373
71
    }
374
375
9.89k
    sslReader configsReader = SSL_READER(tmp.buf, tmp.len);
376
377
9.89k
    if (!SSL_READER_REMAINING(&configsReader)) {
378
1
        PORT_SetError(SEC_ERROR_BAD_DATA);
379
1
        return SECFailure;
380
1
    }
381
382
    /* Handle each ECHConfig. */
383
29.5k
    while (SSL_READER_REMAINING(&configsReader)) {
384
20.3k
        singleConfig.buf = SSL_READER_CURRENT(&configsReader);
385
        /* uint16 version */
386
20.3k
        rv = sslRead_ReadNumber(&configsReader, 2, &version);
387
20.3k
        if (rv != SECSuccess) {
388
15
            goto loser;
389
15
        }
390
        /* uint16 length */
391
20.3k
        rv = sslRead_ReadNumber(&configsReader, 2, &length);
392
20.3k
        if (rv != SECSuccess) {
393
17
            goto loser;
394
17
        }
395
20.3k
        singleConfig.len = 4 + length;
396
397
20.3k
        rv = sslRead_Read(&configsReader, length, &tmp);
398
20.3k
        if (rv != SECSuccess) {
399
72
            goto loser;
400
72
        }
401
402
20.2k
        if (version == TLS13_ECH_VERSION) {
403
14.4k
            rv = tls13_DecodeEchConfigContents(&tmp, &decodedConfig);
404
14.4k
            if (rv != SECSuccess) {
405
662
                goto loser; /* code set */
406
662
            }
407
408
13.7k
            if (decodedConfig) {
409
9.74k
                decodedConfig->version = version;
410
9.74k
                rv = SECITEM_MakeItem(NULL, &decodedConfig->raw, singleConfig.buf,
411
9.74k
                                      singleConfig.len);
412
9.74k
                if (rv != SECSuccess) {
413
0
                    goto loser;
414
0
                }
415
416
9.74k
                PR_APPEND_LINK(&decodedConfig->link, configs);
417
9.74k
                decodedConfig = NULL;
418
9.74k
            }
419
13.7k
        }
420
20.2k
    }
421
9.12k
    return SECSuccess;
422
423
766
loser:
424
766
    tls13_DestroyEchConfigs(configs);
425
766
    return SECFailure;
426
9.88k
}
427
428
/* Encode an ECHConfigList structure. We only create one config, and as the
429
 * primary use for this function is to generate test inputs, we don't
430
 * validate against what HPKE and libssl can actually support. */
431
SECStatus
432
SSLExp_EncodeEchConfigId(PRUint8 configId, const char *publicName, unsigned int maxNameLen,
433
                         HpkeKemId kemId, const SECKEYPublicKey *pubKey,
434
                         const HpkeSymmetricSuite *hpkeSuites, unsigned int hpkeSuiteCount,
435
                         PRUint8 *out, unsigned int *outlen, unsigned int maxlen)
436
0
{
437
0
    SECStatus rv;
438
0
    unsigned int savedOffset;
439
0
    unsigned int len;
440
0
    sslBuffer b = SSL_BUFFER_EMPTY;
441
0
    PRUint8 tmpBuf[66]; // Large enough for an EC public key, currently only X25519.
442
0
    unsigned int tmpLen;
443
444
0
    if (!publicName || !hpkeSuites || hpkeSuiteCount == 0 ||
445
0
        !pubKey || maxNameLen == 0 || !out || !outlen) {
446
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
447
0
        return SECFailure;
448
0
    }
449
450
    /* ECHConfig ECHConfigList<1..2^16-1>; */
451
0
    rv = sslBuffer_Skip(&b, 2, NULL);
452
0
    if (rv != SECSuccess) {
453
0
        goto loser;
454
0
    }
455
456
    /*
457
     * struct {
458
     *     uint16 version;
459
     *     uint16 length;
460
     *     select (ECHConfig.version) {
461
     *       case 0xfe0d: ECHConfigContents contents;
462
     *     }
463
     * } ECHConfig;
464
     */
465
0
    rv = sslBuffer_AppendNumber(&b, TLS13_ECH_VERSION, 2);
466
0
    if (rv != SECSuccess) {
467
0
        goto loser;
468
0
    }
469
470
0
    rv = sslBuffer_Skip(&b, 2, &savedOffset);
471
0
    if (rv != SECSuccess) {
472
0
        goto loser;
473
0
    }
474
475
    /*
476
     * struct {
477
     *     uint8 config_id;
478
     *     HpkeKemId kem_id;
479
     *     HpkePublicKey public_key;
480
     *     HpkeSymmetricCipherSuite cipher_suites<4..2^16-4>;
481
     * } HpkeKeyConfig;
482
     */
483
0
    rv = sslBuffer_AppendNumber(&b, configId, 1);
484
0
    if (rv != SECSuccess) {
485
0
        goto loser;
486
0
    }
487
488
0
    rv = sslBuffer_AppendNumber(&b, kemId, 2);
489
0
    if (rv != SECSuccess) {
490
0
        goto loser;
491
0
    }
492
493
0
    rv = PK11_HPKE_Serialize(pubKey, tmpBuf, &tmpLen, sizeof(tmpBuf));
494
0
    if (rv != SECSuccess) {
495
0
        goto loser;
496
0
    }
497
0
    rv = sslBuffer_AppendVariable(&b, tmpBuf, tmpLen, 2);
498
0
    if (rv != SECSuccess) {
499
0
        goto loser;
500
0
    }
501
502
0
    rv = sslBuffer_AppendNumber(&b, hpkeSuiteCount * 4, 2);
503
0
    if (rv != SECSuccess) {
504
0
        goto loser;
505
0
    }
506
0
    for (unsigned int i = 0; i < hpkeSuiteCount; i++) {
507
0
        rv = sslBuffer_AppendNumber(&b, hpkeSuites[i].kdfId, 2);
508
0
        if (rv != SECSuccess) {
509
0
            goto loser;
510
0
        }
511
0
        rv = sslBuffer_AppendNumber(&b, hpkeSuites[i].aeadId, 2);
512
0
        if (rv != SECSuccess) {
513
0
            goto loser;
514
0
        }
515
0
    }
516
517
    /*
518
     * struct {
519
     *     HpkeKeyConfig key_config;
520
     *     uint8 maximum_name_length;
521
     *     opaque public_name<1..255>;
522
     *     Extension extensions<0..2^16-1>;
523
     * } ECHConfigContents;
524
     */
525
0
    rv = sslBuffer_AppendNumber(&b, maxNameLen, 1);
526
0
    if (rv != SECSuccess) {
527
0
        goto loser;
528
0
    }
529
530
0
    len = PORT_Strlen(publicName);
531
0
    if (len > 0xff) {
532
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
533
0
        goto loser;
534
0
    }
535
0
    rv = sslBuffer_AppendVariable(&b, (const PRUint8 *)publicName, len, 1);
536
0
    if (rv != SECSuccess) {
537
0
        goto loser;
538
0
    }
539
540
    /* extensions */
541
0
    rv = sslBuffer_AppendNumber(&b, 0, 2);
542
0
    if (rv != SECSuccess) {
543
0
        goto loser;
544
0
    }
545
546
    /* Write the length now that we know it. */
547
0
    rv = sslBuffer_InsertLength(&b, 0, 2);
548
0
    if (rv != SECSuccess) {
549
0
        goto loser;
550
0
    }
551
0
    rv = sslBuffer_InsertLength(&b, savedOffset, 2);
552
0
    if (rv != SECSuccess) {
553
0
        goto loser;
554
0
    }
555
556
0
    if (SSL_BUFFER_LEN(&b) > maxlen) {
557
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
558
0
        goto loser;
559
0
    }
560
0
    PORT_Memcpy(out, SSL_BUFFER_BASE(&b), SSL_BUFFER_LEN(&b));
561
0
    *outlen = SSL_BUFFER_LEN(&b);
562
0
    sslBuffer_Clear(&b);
563
0
    return SECSuccess;
564
565
0
loser:
566
0
    sslBuffer_Clear(&b);
567
0
    return SECFailure;
568
0
}
569
570
SECStatus
571
SSLExp_GetEchRetryConfigs(PRFileDesc *fd, SECItem *retryConfigs)
572
0
{
573
0
    SECStatus rv;
574
0
    sslSocket *ss;
575
0
    SECItem out = { siBuffer, NULL, 0 };
576
577
0
    if (!fd || !retryConfigs) {
578
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
579
0
        return SECFailure;
580
0
    }
581
0
    ss = ssl_FindSocket(fd);
582
0
    if (!ss) {
583
0
        SSL_DBG(("%d: SSL[%d]: bad socket in %s",
584
0
                 SSL_GETPID(), fd, __FUNCTION__));
585
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
586
0
        return SECFailure;
587
0
    }
588
589
    /* We don't distinguish between "handshake completed
590
     * without retry configs", and "handshake not completed".
591
     * An application should only call this after receiving a
592
     * RETRY_WITH_ECH error code, which implies retry_configs. */
593
0
    if (!ss->xtnData.ech || !ss->xtnData.ech->retryConfigsValid) {
594
0
        PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
595
0
        return SECFailure;
596
0
    }
597
598
    /* May be empty. */
599
0
    rv = SECITEM_CopyItem(NULL, &out, &ss->xtnData.ech->retryConfigs);
600
0
    if (rv == SECFailure) {
601
0
        return SECFailure;
602
0
    }
603
0
    *retryConfigs = out;
604
0
    return SECSuccess;
605
0
}
606
607
SECStatus
608
SSLExp_RemoveEchConfigs(PRFileDesc *fd)
609
9.98k
{
610
9.98k
    sslSocket *ss;
611
612
9.98k
    if (!fd) {
613
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
614
0
        return SECFailure;
615
0
    }
616
617
9.98k
    ss = ssl_FindSocket(fd);
618
9.98k
    if (!ss) {
619
0
        SSL_DBG(("%d: SSL[%d]: bad socket in %s",
620
0
                 SSL_GETPID(), fd, __FUNCTION__));
621
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
622
0
        return SECFailure;
623
0
    }
624
625
9.98k
    SECKEY_DestroyPrivateKey(ss->echPrivKey);
626
9.98k
    ss->echPrivKey = NULL;
627
9.98k
    SECKEY_DestroyPublicKey(ss->echPubKey);
628
9.98k
    ss->echPubKey = NULL;
629
9.98k
    tls13_DestroyEchConfigs(&ss->echConfigs);
630
631
    /* Also remove any retry_configs and handshake context. */
632
9.98k
    if (ss->xtnData.ech && ss->xtnData.ech->retryConfigs.len) {
633
0
        SECITEM_FreeItem(&ss->xtnData.ech->retryConfigs, PR_FALSE);
634
0
    }
635
636
9.98k
    if (ss->ssl3.hs.echHpkeCtx) {
637
0
        PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE);
638
0
        ss->ssl3.hs.echHpkeCtx = NULL;
639
0
    }
640
9.98k
    PORT_Free(CONST_CAST(char, ss->ssl3.hs.echPublicName));
641
9.98k
    ss->ssl3.hs.echPublicName = NULL;
642
643
9.98k
    return SECSuccess;
644
9.98k
}
645
646
/* Import one or more ECHConfigs for the given keypair. The AEAD/KDF
647
 * may differ , but only X25519 is supported for the KEM.*/
648
SECStatus
649
SSLExp_SetServerEchConfigs(PRFileDesc *fd,
650
                           const SECKEYPublicKey *pubKey, const SECKEYPrivateKey *privKey,
651
                           const PRUint8 *echConfigs, unsigned int echConfigsLen)
652
0
{
653
0
    sslSocket *ss;
654
0
    SECStatus rv;
655
0
    SECItem data = { siBuffer, CONST_CAST(PRUint8, echConfigs), echConfigsLen };
656
657
0
    if (!fd || !pubKey || !privKey || !echConfigs || echConfigsLen == 0) {
658
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
659
0
        return SECFailure;
660
0
    }
661
662
0
    ss = ssl_FindSocket(fd);
663
0
    if (!ss) {
664
0
        SSL_DBG(("%d: SSL[%d]: bad socket in %s",
665
0
                 SSL_GETPID(), fd, __FUNCTION__));
666
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
667
0
        return SECFailure;
668
0
    }
669
670
0
    if (IS_DTLS(ss)) {
671
0
        return SECFailure;
672
0
    }
673
674
    /* Overwrite if we're already configured. */
675
0
    rv = SSLExp_RemoveEchConfigs(fd);
676
0
    if (rv != SECSuccess) {
677
0
        return SECFailure;
678
0
    }
679
680
0
    rv = tls13_DecodeEchConfigs(&data, &ss->echConfigs);
681
0
    if (rv != SECSuccess) {
682
0
        goto loser;
683
0
    }
684
0
    if (PR_CLIST_IS_EMPTY(&ss->echConfigs)) {
685
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
686
0
        goto loser;
687
0
    }
688
689
0
    ss->echPubKey = SECKEY_CopyPublicKey(pubKey);
690
0
    if (!ss->echPubKey) {
691
0
        goto loser;
692
0
    }
693
0
    ss->echPrivKey = SECKEY_CopyPrivateKey(privKey);
694
0
    if (!ss->echPrivKey) {
695
0
        goto loser;
696
0
    }
697
0
    return SECSuccess;
698
699
0
loser:
700
0
    tls13_DestroyEchConfigs(&ss->echConfigs);
701
0
    SECKEY_DestroyPrivateKey(ss->echPrivKey);
702
0
    SECKEY_DestroyPublicKey(ss->echPubKey);
703
0
    ss->echPubKey = NULL;
704
0
    ss->echPrivKey = NULL;
705
0
    return SECFailure;
706
0
}
707
708
/* Client enable. For now, we'll use the first
709
 * compatible config (server preference). */
710
SECStatus
711
SSLExp_SetClientEchConfigs(PRFileDesc *fd,
712
                           const PRUint8 *echConfigs,
713
                           unsigned int echConfigsLen)
714
9.98k
{
715
9.98k
    SECStatus rv;
716
9.98k
    sslSocket *ss;
717
9.98k
    SECItem data = { siBuffer, CONST_CAST(PRUint8, echConfigs), echConfigsLen };
718
719
9.98k
    if (!fd || !echConfigs || echConfigsLen == 0) {
720
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
721
0
        return SECFailure;
722
0
    }
723
724
9.98k
    ss = ssl_FindSocket(fd);
725
9.98k
    if (!ss) {
726
0
        SSL_DBG(("%d: SSL[%d]: bad socket in %s",
727
0
                 SSL_GETPID(), fd, __FUNCTION__));
728
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
729
0
        return SECFailure;
730
0
    }
731
732
9.98k
    if (IS_DTLS(ss)) {
733
0
        return SECFailure;
734
0
    }
735
736
    /* Overwrite if we're already configured. */
737
9.98k
    rv = SSLExp_RemoveEchConfigs(fd);
738
9.98k
    if (rv != SECSuccess) {
739
0
        return SECFailure;
740
0
    }
741
742
9.98k
    rv = tls13_DecodeEchConfigs(&data, &ss->echConfigs);
743
9.98k
    if (rv != SECSuccess) {
744
861
        return SECFailure;
745
861
    }
746
9.12k
    if (PR_CLIST_IS_EMPTY(&ss->echConfigs)) {
747
56
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
748
56
        return SECFailure;
749
56
    }
750
751
9.06k
    return SECSuccess;
752
9.12k
}
753
754
/* Set up ECH. This generates an ephemeral sender
755
 * keypair and the HPKE context */
756
SECStatus
757
tls13_ClientSetupEch(sslSocket *ss, sslClientHelloType type)
758
17.4k
{
759
17.4k
    SECStatus rv;
760
17.4k
    HpkeContext *cx = NULL;
761
17.4k
    SECKEYPublicKey *pkR = NULL;
762
17.4k
    SECItem hpkeInfo = { siBuffer, NULL, 0 };
763
17.4k
    sslEchConfig *cfg = NULL;
764
765
17.4k
    if (PR_CLIST_IS_EMPTY(&ss->echConfigs) ||
766
4.10k
        !ssl_ShouldSendSNIExtension(ss, ss->url) ||
767
13.3k
        IS_DTLS(ss)) {
768
13.3k
        return SECSuccess;
769
13.3k
    }
770
771
    /* Maybe apply our own priority if >1. For now, we only support
772
     * one version and one KEM. Each ECHConfig can specify multiple
773
     * KDF/AEADs, so just use the first. */
774
4.10k
    cfg = (sslEchConfig *)PR_LIST_HEAD(&ss->echConfigs);
775
776
4.10k
    SSL_TRC(50, ("%d: TLS13[%d]: Setup client ECH",
777
4.10k
                 SSL_GETPID(), ss->fd));
778
779
4.10k
    switch (type) {
780
3.44k
        case client_hello_initial:
781
3.44k
            PORT_Assert(!ss->ssl3.hs.echHpkeCtx && !ss->ssl3.hs.echPublicName);
782
3.44k
            cx = PK11_HPKE_NewContext(cfg->contents.kemId, cfg->contents.kdfId,
783
3.44k
                                      cfg->contents.aeadId, NULL, NULL);
784
3.44k
            break;
785
660
        case client_hello_retry:
786
660
            if (!ss->ssl3.hs.echHpkeCtx || !ss->ssl3.hs.echPublicName) {
787
0
                FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
788
0
                return SECFailure;
789
0
            }
790
            /* Nothing else to do. */
791
660
            return SECSuccess;
792
0
        default:
793
0
            PORT_Assert(0);
794
0
            goto loser;
795
4.10k
    }
796
3.44k
    if (!cx) {
797
0
        goto loser;
798
0
    }
799
800
3.44k
    rv = PK11_HPKE_Deserialize(cx, cfg->contents.publicKey.data, cfg->contents.publicKey.len, &pkR);
801
3.44k
    if (rv != SECSuccess) {
802
0
        goto loser;
803
0
    }
804
805
3.44k
    if (!SECITEM_AllocItem(NULL, &hpkeInfo, strlen(kHpkeInfoEch) + 1 + cfg->raw.len)) {
806
0
        goto loser;
807
0
    }
808
3.44k
    PORT_Memcpy(&hpkeInfo.data[0], kHpkeInfoEch, strlen(kHpkeInfoEch));
809
3.44k
    PORT_Memset(&hpkeInfo.data[strlen(kHpkeInfoEch)], 0, 1);
810
3.44k
    PORT_Memcpy(&hpkeInfo.data[strlen(kHpkeInfoEch) + 1], cfg->raw.data, cfg->raw.len);
811
812
3.44k
    PRINT_BUF(50, (ss, "Info", hpkeInfo.data, hpkeInfo.len));
813
814
    /* Setup with an ephemeral sender keypair. */
815
3.44k
    rv = PK11_HPKE_SetupS(cx, NULL, NULL, pkR, &hpkeInfo);
816
3.44k
    if (rv != SECSuccess) {
817
19
        goto loser;
818
19
    }
819
820
3.42k
    rv = ssl3_GetNewRandom(ss->ssl3.hs.client_inner_random);
821
3.42k
    if (rv != SECSuccess) {
822
0
        goto loser; /* code set */
823
0
    }
824
825
    /* If ECH is rejected, the application will use SSLChannelInfo
826
     * to fetch this field and perform cert chain verification. */
827
3.42k
    ss->ssl3.hs.echPublicName = PORT_Strdup(cfg->contents.publicName);
828
3.42k
    if (!ss->ssl3.hs.echPublicName) {
829
0
        goto loser;
830
0
    }
831
832
3.42k
    ss->ssl3.hs.echHpkeCtx = cx;
833
3.42k
    SECKEY_DestroyPublicKey(pkR);
834
3.42k
    SECITEM_FreeItem(&hpkeInfo, PR_FALSE);
835
3.42k
    return SECSuccess;
836
837
19
loser:
838
19
    PK11_HPKE_DestroyContext(cx, PR_TRUE);
839
19
    SECKEY_DestroyPublicKey(pkR);
840
19
    SECITEM_FreeItem(&hpkeInfo, PR_FALSE);
841
19
    PORT_Assert(PORT_GetError() != 0);
842
19
    return SECFailure;
843
3.42k
}
844
845
/*
846
 * outerAAD - The associated data for the AEAD (the entire client hello with the ECH payload zeroed)
847
 * chInner - The plaintext which will be encrypted (the ClientHelloInner plus padding)
848
 * echPayload - Output location. A buffer containing all-zeroes of at least chInner->len + TLS13_ECH_AEAD_TAG_LEN bytes.
849
 *
850
 * echPayload may point into outerAAD to avoid the need to duplicate the ClientHelloOuter buffer.
851
 */
852
static SECStatus
853
tls13_EncryptClientHello(sslSocket *ss, SECItem *aadItem, const sslBuffer *chInner, PRUint8 *echPayload)
854
4.08k
{
855
4.08k
    SECStatus rv;
856
4.08k
    SECItem chPt = { siBuffer, chInner->buf, chInner->len };
857
4.08k
    SECItem *chCt = NULL;
858
859
4.08k
    PRINT_BUF(50, (ss, "aad for ECH Encrypt", aadItem->data, aadItem->len));
860
4.08k
    PRINT_BUF(50, (ss, "plaintext for ECH Encrypt", chInner->buf, chInner->len));
861
862
#ifndef UNSAFE_FUZZER_MODE
863
    rv = PK11_HPKE_Seal(ss->ssl3.hs.echHpkeCtx, aadItem, &chPt, &chCt);
864
4.08k
    if (rv != SECSuccess) {
865
0
        goto loser;
866
0
    }
867
4.08k
    PRINT_BUF(50, (ss, "ciphertext from ECH Encrypt", chCt->data, chCt->len));
868
#else
869
    /* Fake a tag. */
870
0
    chCt = SECITEM_AllocItem(NULL, NULL, chPt.len + TLS13_ECH_AEAD_TAG_LEN);
871
0
    if (!chCt) {
872
0
        goto loser;
873
0
    }
874
0
    PORT_Memcpy(chCt->data, chPt.data, chPt.len);
875
0
#endif
876
877
0
#ifdef DEBUG
878
    /* When encrypting in-place, the payload is part of the AAD and must be zeroed. */
879
0
    PRUint8 val = 0;
880
1.21M
    for (int i = 0; i < chCt->len; i++) {
881
1.20M
        val |= *(echPayload + i);
882
1.20M
    }
883
4.08k
    PRINT_BUF(100, (ss, "Empty Placeholder for output of ECH Encryption", echPayload, chCt->len));
884
4.08k
    PR_ASSERT(val == 0);
885
0
#endif
886
887
4.08k
    PORT_Memcpy(echPayload, chCt->data, chCt->len);
888
4.08k
    SECITEM_FreeItem(chCt, PR_TRUE);
889
0
    return SECSuccess;
890
891
0
loser:
892
0
    SECITEM_FreeItem(chCt, PR_TRUE);
893
0
    return SECFailure;
894
4.08k
}
Unexecuted instantiation: tls13ech.c:tls13_EncryptClientHello
tls13ech.c:tls13_EncryptClientHello
Line
Count
Source
854
4.08k
{
855
4.08k
    SECStatus rv;
856
4.08k
    SECItem chPt = { siBuffer, chInner->buf, chInner->len };
857
4.08k
    SECItem *chCt = NULL;
858
859
4.08k
    PRINT_BUF(50, (ss, "aad for ECH Encrypt", aadItem->data, aadItem->len));
860
4.08k
    PRINT_BUF(50, (ss, "plaintext for ECH Encrypt", chInner->buf, chInner->len));
861
862
4.08k
#ifndef UNSAFE_FUZZER_MODE
863
4.08k
    rv = PK11_HPKE_Seal(ss->ssl3.hs.echHpkeCtx, aadItem, &chPt, &chCt);
864
4.08k
    if (rv != SECSuccess) {
865
0
        goto loser;
866
0
    }
867
4.08k
    PRINT_BUF(50, (ss, "ciphertext from ECH Encrypt", chCt->data, chCt->len));
868
#else
869
    /* Fake a tag. */
870
    chCt = SECITEM_AllocItem(NULL, NULL, chPt.len + TLS13_ECH_AEAD_TAG_LEN);
871
    if (!chCt) {
872
        goto loser;
873
    }
874
    PORT_Memcpy(chCt->data, chPt.data, chPt.len);
875
#endif
876
877
4.08k
#ifdef DEBUG
878
    /* When encrypting in-place, the payload is part of the AAD and must be zeroed. */
879
4.08k
    PRUint8 val = 0;
880
1.21M
    for (int i = 0; i < chCt->len; i++) {
881
1.20M
        val |= *(echPayload + i);
882
1.20M
    }
883
4.08k
    PRINT_BUF(100, (ss, "Empty Placeholder for output of ECH Encryption", echPayload, chCt->len));
884
4.08k
    PR_ASSERT(val == 0);
885
4.08k
#endif
886
887
4.08k
    PORT_Memcpy(echPayload, chCt->data, chCt->len);
888
4.08k
    SECITEM_FreeItem(chCt, PR_TRUE);
889
4.08k
    return SECSuccess;
890
891
0
loser:
892
0
    SECITEM_FreeItem(chCt, PR_TRUE);
893
0
    return SECFailure;
894
4.08k
}
895
896
SECStatus
897
tls13_GetMatchingEchConfigs(const sslSocket *ss, HpkeKdfId kdf, HpkeAeadId aead,
898
                            const PRUint8 configId, const sslEchConfig *cur, sslEchConfig **next)
899
22
{
900
22
    SSL_TRC(50, ("%d: TLS13[%d]: GetMatchingEchConfig %d",
901
22
                 SSL_GETPID(), ss->fd, configId));
902
903
    /* If |cur|, resume the search at that node, else the list head. */
904
22
    for (PRCList *cur_p = cur ? ((PRCList *)cur)->next : PR_LIST_HEAD(&ss->echConfigs);
905
22
         cur_p != &ss->echConfigs;
906
22
         cur_p = PR_NEXT_LINK(cur_p)) {
907
0
        sslEchConfig *echConfig = (sslEchConfig *)cur_p;
908
0
        if (echConfig->contents.configId == configId &&
909
0
            echConfig->contents.aeadId == aead &&
910
0
            echConfig->contents.kdfId == kdf) {
911
0
            *next = echConfig;
912
0
            return SECSuccess;
913
0
        }
914
0
    }
915
916
22
    *next = NULL;
917
22
    return SECSuccess;
918
22
}
919
920
/* Given a CH with extensions, copy from the start up to the extensions
921
 * into |writer| and return the extensions themselves in |extensions|.
922
 * If |explicitSid|, place this value into |writer| as the SID. Else,
923
 * the sid is copied from |reader| to |writer|. */
924
static SECStatus
925
tls13_CopyChPreamble(sslSocket *ss, sslReader *reader, const SECItem *explicitSid, sslBuffer *writer, sslReadBuffer *extensions)
926
0
{
927
0
    SECStatus rv;
928
0
    sslReadBuffer tmpReadBuf;
929
930
    /* Locate the extensions. */
931
0
    rv = sslRead_Read(reader, 2 + SSL3_RANDOM_LENGTH, &tmpReadBuf);
932
0
    if (rv != SECSuccess) {
933
0
        return SECFailure;
934
0
    }
935
0
    rv = sslBuffer_Append(writer, tmpReadBuf.buf, tmpReadBuf.len);
936
0
    if (rv != SECSuccess) {
937
0
        return SECFailure;
938
0
    }
939
940
    /* legacy_session_id */
941
0
    rv = sslRead_ReadVariable(reader, 1, &tmpReadBuf);
942
0
    if (rv != SECSuccess) {
943
0
        return SECFailure;
944
0
    }
945
0
    if (explicitSid) {
946
        /* Encoded SID should be empty when copying from CHOuter. */
947
0
        if (tmpReadBuf.len > 0) {
948
0
            PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_EXTENSION);
949
0
            return SECFailure;
950
0
        }
951
0
        rv = sslBuffer_AppendVariable(writer, explicitSid->data, explicitSid->len, 1);
952
0
    } else {
953
0
        rv = sslBuffer_AppendVariable(writer, tmpReadBuf.buf, tmpReadBuf.len, 1);
954
0
    }
955
0
    if (rv != SECSuccess) {
956
0
        return SECFailure;
957
0
    }
958
959
    /* cipher suites */
960
0
    rv = sslRead_ReadVariable(reader, 2, &tmpReadBuf);
961
0
    if (rv != SECSuccess) {
962
0
        return SECFailure;
963
0
    }
964
0
    rv = sslBuffer_AppendVariable(writer, tmpReadBuf.buf, tmpReadBuf.len, 2);
965
0
    if (rv != SECSuccess) {
966
0
        return SECFailure;
967
0
    }
968
969
    /* compression */
970
0
    rv = sslRead_ReadVariable(reader, 1, &tmpReadBuf);
971
0
    if (rv != SECSuccess) {
972
0
        return SECFailure;
973
0
    }
974
0
    rv = sslBuffer_AppendVariable(writer, tmpReadBuf.buf, tmpReadBuf.len, 1);
975
0
    if (rv != SECSuccess) {
976
0
        return SECFailure;
977
0
    }
978
979
    /* extensions */
980
0
    rv = sslRead_ReadVariable(reader, 2, extensions);
981
0
    if (rv != SECSuccess) {
982
0
        return SECFailure;
983
0
    }
984
985
    /* padding (optional) */
986
0
    sslReadBuffer padding;
987
0
    rv = sslRead_Read(reader, SSL_READER_REMAINING(reader), &padding);
988
0
    if (rv != SECSuccess) {
989
0
        return SECFailure;
990
0
    }
991
0
    PRUint8 result = 0;
992
0
    for (int i = 0; i < padding.len; i++) {
993
0
        result |= padding.buf[i];
994
0
    }
995
0
    if (result) {
996
0
        SSL_TRC(50, ("%d: TLS13: Invalid ECH ClientHelloInner padding decoded", SSL_GETPID()));
997
0
        FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ECH_EXTENSION, illegal_parameter);
998
0
        return SECFailure;
999
0
    }
1000
0
    return SECSuccess;
1001
0
}
1002
1003
/*
1004
 * The ClientHelloOuterAAD is a serialized ClientHello structure, defined in
1005
 * Section 4.1.2 of [RFC8446], which matches the ClientHelloOuter except the
1006
 * payload field of the "encrypted_client_hello" is replaced with a byte
1007
 * string of the same length but whose contents are zeros. This value does
1008
 * not include the four-byte header from the Handshake structure.
1009
 */
1010
static SECStatus
1011
tls13_ServerMakeChOuterAAD(sslSocket *ss, const PRUint8 *outerCh, unsigned int outerChLen, SECItem *outerAAD)
1012
0
{
1013
0
    SECStatus rv;
1014
0
    sslBuffer aad = SSL_BUFFER_EMPTY;
1015
0
    const unsigned int echPayloadLen = ss->xtnData.ech->innerCh.len;               /* Length of incoming payload */
1016
0
    const unsigned int echPayloadOffset = ss->xtnData.ech->payloadStart - outerCh; /* Offset from start of CHO */
1017
1018
0
    PORT_Assert(outerChLen > echPayloadLen);
1019
0
    PORT_Assert(echPayloadOffset + echPayloadLen <= outerChLen);
1020
0
    PORT_Assert(ss->sec.isServer);
1021
0
    PORT_Assert(ss->xtnData.ech);
1022
1023
0
#ifdef DEBUG
1024
    /* Safety check that payload length pointed to by offset matches expected length */
1025
0
    sslReader echXtnReader = SSL_READER(outerCh + echPayloadOffset - 2, 2);
1026
0
    PRUint64 parsedXtnSize;
1027
0
    rv = sslRead_ReadNumber(&echXtnReader, 2, &parsedXtnSize);
1028
0
    PR_ASSERT(rv == SECSuccess);
1029
0
    PR_ASSERT(parsedXtnSize == echPayloadLen);
1030
0
#endif
1031
1032
0
    rv = sslBuffer_Append(&aad, outerCh, outerChLen);
1033
0
    if (rv != SECSuccess) {
1034
0
        goto loser;
1035
0
    }
1036
0
    PORT_Memset(aad.buf + echPayloadOffset, 0, echPayloadLen);
1037
1038
0
    PRINT_BUF(50, (ss, "AAD for ECH Decryption", aad.buf, aad.len));
1039
1040
0
    outerAAD->data = aad.buf;
1041
0
    outerAAD->len = aad.len;
1042
0
    return SECSuccess;
1043
1044
0
loser:
1045
0
    sslBuffer_Clear(&aad);
1046
0
    return SECFailure;
1047
0
}
1048
1049
SECStatus
1050
tls13_OpenClientHelloInner(sslSocket *ss, const SECItem *outer, const SECItem *outerAAD, sslEchConfig *cfg, SECItem **chInner)
1051
0
{
1052
0
    SECStatus rv;
1053
0
    HpkeContext *cx = NULL;
1054
0
    SECItem *decryptedChInner = NULL;
1055
0
    SECItem hpkeInfo = { siBuffer, NULL, 0 };
1056
0
    SSL_TRC(50, ("%d: TLS13[%d]: Server opening ECH Inner%s", SSL_GETPID(),
1057
0
                 ss->fd, ss->ssl3.hs.helloRetry ? " after HRR" : ""));
1058
1059
0
    if (!ss->ssl3.hs.helloRetry) {
1060
0
        PORT_Assert(!ss->ssl3.hs.echHpkeCtx);
1061
0
        cx = PK11_HPKE_NewContext(cfg->contents.kemId, cfg->contents.kdfId,
1062
0
                                  cfg->contents.aeadId, NULL, NULL);
1063
0
        if (!cx) {
1064
0
            goto loser;
1065
0
        }
1066
1067
0
        if (!SECITEM_AllocItem(NULL, &hpkeInfo, strlen(kHpkeInfoEch) + 1 + cfg->raw.len)) {
1068
0
            goto loser;
1069
0
        }
1070
0
        PORT_Memcpy(&hpkeInfo.data[0], kHpkeInfoEch, strlen(kHpkeInfoEch));
1071
0
        PORT_Memset(&hpkeInfo.data[strlen(kHpkeInfoEch)], 0, 1);
1072
0
        PORT_Memcpy(&hpkeInfo.data[strlen(kHpkeInfoEch) + 1], cfg->raw.data, cfg->raw.len);
1073
1074
0
        rv = PK11_HPKE_SetupR(cx, ss->echPubKey, ss->echPrivKey,
1075
0
                              &ss->xtnData.ech->senderPubKey, &hpkeInfo);
1076
0
        if (rv != SECSuccess) {
1077
0
            goto loser; /* code set */
1078
0
        }
1079
0
    } else {
1080
0
        PORT_Assert(ss->ssl3.hs.echHpkeCtx);
1081
0
        cx = ss->ssl3.hs.echHpkeCtx;
1082
0
    }
1083
1084
#ifndef UNSAFE_FUZZER_MODE
1085
0
    rv = PK11_HPKE_Open(cx, outerAAD, &ss->xtnData.ech->innerCh, &decryptedChInner);
1086
0
    if (rv != SECSuccess) {
1087
0
        SSL_TRC(10, ("%d: SSL3[%d]: Failed to decrypt inner CH with this candidate",
1088
0
                     SSL_GETPID(), ss->fd));
1089
0
        goto loser; /* code set */
1090
0
    }
1091
#else
1092
0
    rv = SECITEM_CopyItem(NULL, decryptedChInner, &ss->xtnData.ech->innerCh);
1093
0
    if (rv != SECSuccess || decryptedChInner->len <= TLS13_ECH_AEAD_TAG_LEN) {
1094
0
        goto loser;
1095
0
    }
1096
0
    decryptedChInner->len -= TLS13_ECH_AEAD_TAG_LEN; /* Fake tag */
1097
0
#endif
1098
1099
    /* Stash the context, we may need it for HRR. */
1100
0
    ss->ssl3.hs.echHpkeCtx = cx;
1101
0
    *chInner = decryptedChInner;
1102
0
    PRINT_BUF(100, (ss, "Decrypted ECH Inner", decryptedChInner->data, decryptedChInner->len));
1103
0
    SECITEM_FreeItem(&hpkeInfo, PR_FALSE);
1104
0
    return SECSuccess;
1105
1106
0
loser:
1107
0
    SECITEM_FreeItem(decryptedChInner, PR_TRUE);
1108
0
    SECITEM_FreeItem(&hpkeInfo, PR_FALSE);
1109
0
    if (cx != ss->ssl3.hs.echHpkeCtx) {
1110
        /* Don't double-free if it's already global. */
1111
0
        PK11_HPKE_DestroyContext(cx, PR_TRUE);
1112
0
    }
1113
0
    return SECFailure;
1114
0
}
Unexecuted instantiation: tls13_OpenClientHelloInner
Unexecuted instantiation: tls13_OpenClientHelloInner
1115
1116
/* This is the maximum number of extension hooks that the following functions can handle. */
1117
0
#define MAX_EXTENSION_WRITERS 32
1118
1119
static SECStatus
1120
tls13_WriteDupXtnsToChInner(PRBool compressing, sslBuffer *dupXtns, sslBuffer *chInnerXtns)
1121
9.73k
{
1122
9.73k
    SECStatus rv;
1123
9.73k
    if (compressing && SSL_BUFFER_LEN(dupXtns) > 0) {
1124
5.65k
        rv = sslBuffer_AppendNumber(chInnerXtns, ssl_tls13_outer_extensions_xtn, 2);
1125
5.65k
        if (rv != SECSuccess) {
1126
0
            return SECFailure;
1127
0
        }
1128
5.65k
        rv = sslBuffer_AppendNumber(chInnerXtns, dupXtns->len + 1, 2);
1129
5.65k
        if (rv != SECSuccess) {
1130
0
            return SECFailure;
1131
0
        }
1132
5.65k
        rv = sslBuffer_AppendBufferVariable(chInnerXtns, dupXtns, 1);
1133
5.65k
        if (rv != SECSuccess) {
1134
0
            return SECFailure;
1135
0
        }
1136
5.65k
    } else {
1137
        /* dupXtns carries whole extensions with lengths on each. */
1138
4.08k
        rv = sslBuffer_AppendBuffer(chInnerXtns, dupXtns);
1139
4.08k
        if (rv != SECSuccess) {
1140
0
            return SECFailure;
1141
0
        }
1142
4.08k
    }
1143
9.73k
    sslBuffer_Clear(dupXtns);
1144
9.73k
    return SECSuccess;
1145
9.73k
}
1146
1147
/* Add ordinary extensions to CHInner.
1148
 * The value of the extension from CHOuter is in |extensionData|.
1149
 *
1150
 * If the value is to be compressed, it is written to |dupXtns|.
1151
 * Otherwise, a full extension is written to |chInnerXtns|.
1152
 *
1153
 * This function is always called twice:
1154
 * once without compression and once with compression if possible.
1155
 *
1156
 * Because we want to allow extensions that did not appear in CHOuter
1157
 * to be included in CHInner, we also need to track which extensions
1158
 * have been included.  This is what |called| and |nCalled| track.
1159
 */
1160
static SECStatus
1161
tls13_ChInnerAppendExtension(sslSocket *ss, PRUint16 extensionType,
1162
                             const sslReadBuffer *extensionData,
1163
                             sslBuffer *dupXtns, sslBuffer *chInnerXtns,
1164
                             PRBool compressing,
1165
                             PRUint16 *called, unsigned int *nCalled)
1166
73.3k
{
1167
73.3k
    PRUint8 buf[1024] = { 0 };
1168
73.3k
    const PRUint8 *p;
1169
73.3k
    unsigned int len = 0;
1170
73.3k
    PRBool willCompress;
1171
1172
73.3k
    PORT_Assert(extensionType != ssl_tls13_encrypted_client_hello_xtn);
1173
73.3k
    sslCustomExtensionHooks *hook = ss->opt.callExtensionWriterOnEchInner
1174
73.3k
                                        ? ssl_FindCustomExtensionHooks(ss, extensionType)
1175
73.3k
                                        : NULL;
1176
73.3k
    if (hook && hook->writer) {
1177
0
        if (*nCalled >= MAX_EXTENSION_WRITERS) {
1178
0
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); /* TODO new code? */
1179
0
            return SECFailure;
1180
0
        }
1181
1182
0
        PRBool append = (*hook->writer)(ss->fd, ssl_hs_client_hello,
1183
0
                                        buf, &len, sizeof(buf), hook->writerArg);
1184
0
        called[(*nCalled)++] = extensionType;
1185
0
        if (!append) {
1186
            /* This extension is not going to appear in CHInner. */
1187
            /* TODO: consider removing this extension from ss->xtnData.advertised.
1188
             * The consequence of not removing it is that we won't complain
1189
             * if the server accepts ECH and then includes this extension.
1190
             * The cost is a complete reworking of ss->xtnData.advertised.
1191
             */
1192
0
            return SECSuccess;
1193
0
        }
1194
        /* It can be compressed if it is the same as the outer value. */
1195
0
        willCompress = (len == extensionData->len &&
1196
0
                        NSS_SecureMemcmp(buf, extensionData->buf, len) == 0);
1197
0
        p = buf;
1198
73.3k
    } else {
1199
        /* Non-custom extensions are duplicated when compressing. */
1200
73.3k
        willCompress = PR_TRUE;
1201
73.3k
        p = extensionData->buf;
1202
73.3k
        len = extensionData->len;
1203
73.3k
    }
1204
1205
    /* Duplicated extensions all need to go together. */
1206
73.3k
    sslBuffer *dst = willCompress ? dupXtns : chInnerXtns;
1207
73.3k
    SECStatus rv = sslBuffer_AppendNumber(dst, extensionType, 2);
1208
73.3k
    if (rv != SECSuccess) {
1209
0
        return SECFailure;
1210
0
    }
1211
73.3k
    if (!willCompress || !compressing) {
1212
30.7k
        rv = sslBuffer_AppendVariable(dst, p, len, 2);
1213
30.7k
        if (rv != SECSuccess) {
1214
0
            return SECFailure;
1215
0
        }
1216
30.7k
    }
1217
    /* As this function is called twice, we only want to update our state the second time. */
1218
73.3k
    if (compressing) {
1219
42.6k
        ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = extensionType;
1220
42.6k
        SSL_TRC(50, ("Appending extension=%d to the Client Hello Inner. Compressed?=%d", extensionType, willCompress));
1221
42.6k
    }
1222
73.3k
    return SECSuccess;
1223
73.3k
}
1224
1225
/* Call any custom extension handlers that didn't want to be added to CHOuter. */
1226
static SECStatus
1227
tls13_ChInnerAdditionalExtensionWriters(sslSocket *ss, const PRUint16 *called,
1228
                                        unsigned int nCalled, sslBuffer *chInnerXtns)
1229
9.73k
{
1230
9.73k
    if (!ss->opt.callExtensionWriterOnEchInner) {
1231
9.73k
        return SECSuccess;
1232
9.73k
    }
1233
1234
0
    for (PRCList *cursor = PR_NEXT_LINK(&ss->extensionHooks);
1235
0
         cursor != &ss->extensionHooks;
1236
0
         cursor = PR_NEXT_LINK(cursor)) {
1237
0
        sslCustomExtensionHooks *hook = (sslCustomExtensionHooks *)cursor;
1238
1239
        /* Skip if this hook was already called. */
1240
0
        PRBool hookCalled = PR_FALSE;
1241
0
        for (unsigned int i = 0; i < nCalled; ++i) {
1242
0
            if (called[i] == hook->type) {
1243
0
                hookCalled = PR_TRUE;
1244
0
                break;
1245
0
            }
1246
0
        }
1247
0
        if (hookCalled) {
1248
0
            continue;
1249
0
        }
1250
1251
        /* This is a cut-down version of ssl_CallCustomExtensionSenders(). */
1252
0
        PRUint8 buf[1024];
1253
0
        unsigned int len = 0;
1254
0
        PRBool append = (*hook->writer)(ss->fd, ssl_hs_client_hello,
1255
0
                                        buf, &len, sizeof(buf), hook->writerArg);
1256
0
        if (!append) {
1257
0
            continue;
1258
0
        }
1259
1260
0
        SECStatus rv = sslBuffer_AppendNumber(chInnerXtns, hook->type, 2);
1261
0
        if (rv != SECSuccess) {
1262
0
            return SECFailure;
1263
0
        }
1264
0
        rv = sslBuffer_AppendVariable(chInnerXtns, buf, len, 2);
1265
0
        if (rv != SECSuccess) {
1266
0
            return SECFailure;
1267
0
        }
1268
0
        ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = hook->type;
1269
0
    }
1270
0
    return SECSuccess;
1271
0
}
1272
1273
/* Take the PSK extension CHOuter and fill it with junk. */
1274
static SECStatus
1275
tls13_RandomizePsk(PRUint8 *buf, unsigned int len)
1276
1.91k
{
1277
1.91k
    sslReader rdr = SSL_READER(buf, len);
1278
1279
    /* Read the length of identities. */
1280
1.91k
    PRUint64 outerLen = 0;
1281
1.91k
    SECStatus rv = sslRead_ReadNumber(&rdr, 2, &outerLen);
1282
1.91k
    if (rv != SECSuccess) {
1283
0
        return SECFailure;
1284
0
    }
1285
1.91k
    PORT_Assert(outerLen < len + 2);
1286
1287
    /* Read the length of PskIdentity.identity */
1288
1.91k
    PRUint64 innerLen = 0;
1289
1.91k
    rv = sslRead_ReadNumber(&rdr, 2, &innerLen);
1290
1.91k
    if (rv != SECSuccess) {
1291
0
        return SECFailure;
1292
0
    }
1293
    /* identities should contain just one identity. */
1294
1.91k
    PORT_Assert(outerLen == innerLen + 6);
1295
1296
    /* Randomize PskIdentity.{identity,obfuscated_ticket_age}. */
1297
1.91k
    rv = PK11_GenerateRandom(buf + rdr.offset, innerLen + 4);
1298
1.91k
    if (rv != SECSuccess) {
1299
0
        return SECFailure;
1300
0
    }
1301
1.91k
    rdr.offset += innerLen + 4;
1302
1303
    /* Read the length of binders. */
1304
1.91k
    rv = sslRead_ReadNumber(&rdr, 2, &outerLen);
1305
1.91k
    if (rv != SECSuccess) {
1306
0
        return SECFailure;
1307
0
    }
1308
1.91k
    PORT_Assert(outerLen + rdr.offset == len);
1309
1310
    /* Read the length of the binder. */
1311
1.91k
    rv = sslRead_ReadNumber(&rdr, 1, &innerLen);
1312
1.91k
    if (rv != SECSuccess) {
1313
0
        return SECFailure;
1314
0
    }
1315
    /* binders should contain just one binder. */
1316
1.91k
    PORT_Assert(outerLen == innerLen + 1);
1317
1318
    /* Randomize the binder. */
1319
1.91k
    rv = PK11_GenerateRandom(buf + rdr.offset, innerLen);
1320
1.91k
    if (rv != SECSuccess) {
1321
0
        return SECFailure;
1322
0
    }
1323
1324
1.91k
    return SECSuccess;
1325
1.91k
}
1326
1327
/* Given a buffer of extensions prepared for CHOuter, translate those extensions to a
1328
 * buffer suitable for CHInner. This is intended to be called twice: once without
1329
 * compression for the transcript hash and binders, and once with compression for
1330
 * encoding the actual CHInner value.
1331
 *
1332
 * Compressed extensions are moved in both runs.  When compressing, they are moved
1333
 * to a single outer_extensions extension, which lists extensions from CHOuter.
1334
 * When not compressing, this produces the ClientHello that will be reconstructed
1335
 * from the compressed ClientHello (that is, what goes into the handshake transcript),
1336
 * so all the compressed extensions need to appear in the same place that the
1337
 * outer_extensions extension appears.
1338
 *
1339
 * On the first run, if |inOutPskXtn| and OuterXtnsBuf contains a PSK extension,
1340
 * remove it and return in the outparam.he caller will compute the binder value
1341
 * based on the uncompressed output. Next, if |compress|, consolidate duplicated
1342
 * extensions (that would otherwise be copied) into a single outer_extensions
1343
 * extension. If |inOutPskXtn|, the extension contains a binder, it is appended
1344
 * after the deduplicated outer_extensions. In the case of GREASE ECH, one call
1345
 * is made to estimate size (wiith compression, null inOutPskXtn).
1346
 */
1347
SECStatus
1348
tls13_ConstructInnerExtensionsFromOuter(sslSocket *ss, sslBuffer *chOuterXtnsBuf,
1349
                                        sslBuffer *chInnerXtns, sslBuffer *inOutPskXtn,
1350
                                        PRBool shouldCompress)
1351
9.73k
{
1352
9.73k
    SECStatus rv;
1353
9.73k
    PRUint64 extensionType;
1354
9.73k
    sslReadBuffer extensionData;
1355
9.73k
    sslBuffer pskXtn = SSL_BUFFER_EMPTY;
1356
9.73k
    sslBuffer dupXtns = SSL_BUFFER_EMPTY; /* Duplicated extensions, types-only if |compress|. */
1357
9.73k
    unsigned int tmpOffset;
1358
9.73k
    unsigned int tmpLen;
1359
9.73k
    unsigned int srcXtnBase; /* To truncate CHOuter and remove the PSK extension. */
1360
1361
9.73k
    PRUint16 called[MAX_EXTENSION_WRITERS] = { 0 }; /* For tracking which has been called. */
1362
9.73k
    unsigned int nCalled = 0;
1363
1364
9.73k
    SSL_TRC(50, ("%d: TLS13[%d]: Constructing ECH inner extensions %s compression",
1365
9.73k
                 SSL_GETPID(), ss->fd, shouldCompress ? "with" : "without"));
1366
1367
    /* When offering the "encrypted_client_hello" extension in its
1368
     * ClientHelloOuter, the client MUST also offer an empty
1369
     * "encrypted_client_hello" extension in its ClientHelloInner. */
1370
9.73k
    rv = sslBuffer_AppendNumber(chInnerXtns, ssl_tls13_encrypted_client_hello_xtn, 2);
1371
9.73k
    if (rv != SECSuccess) {
1372
0
        goto loser;
1373
0
    }
1374
9.73k
    rv = sslBuffer_AppendNumber(chInnerXtns, 1, 2);
1375
9.73k
    if (rv != SECSuccess) {
1376
0
        goto loser;
1377
0
    }
1378
9.73k
    rv = sslBuffer_AppendNumber(chInnerXtns, ech_xtn_type_inner, 1);
1379
9.73k
    if (rv != SECSuccess) {
1380
0
        goto loser;
1381
0
    }
1382
1383
9.73k
    sslReader rdr = SSL_READER(chOuterXtnsBuf->buf, chOuterXtnsBuf->len);
1384
135k
    while (SSL_READER_REMAINING(&rdr)) {
1385
125k
        srcXtnBase = rdr.offset;
1386
125k
        rv = sslRead_ReadNumber(&rdr, 2, &extensionType);
1387
125k
        if (rv != SECSuccess) {
1388
0
            goto loser;
1389
0
        }
1390
1391
        /* Get the extension data. */
1392
125k
        rv = sslRead_ReadVariable(&rdr, 2, &extensionData);
1393
125k
        if (rv != SECSuccess) {
1394
0
            goto loser;
1395
0
        }
1396
1397
        /* Skip extensions that are TLS < 1.3 only, since CHInner MUST
1398
         * negotiate TLS 1.3 or above.
1399
         * If the extension is supported by default (sslSupported) but unknown
1400
         * to TLS 1.3 it must be a TLS < 1.3 only extension. */
1401
125k
        SSLExtensionSupport sslSupported;
1402
125k
        (void)SSLExp_GetExtensionSupport(extensionType, &sslSupported);
1403
125k
        if (sslSupported != ssl_ext_none &&
1404
101k
            tls13_ExtensionStatus(extensionType, ssl_hs_client_hello) == tls13_extension_unknown) {
1405
28.4k
            continue;
1406
28.4k
        }
1407
1408
97.4k
        switch (extensionType) {
1409
9.73k
            case ssl_server_name_xtn:
1410
                /* Write the real (private) SNI value. */
1411
9.73k
                rv = sslBuffer_AppendNumber(chInnerXtns, extensionType, 2);
1412
9.73k
                if (rv != SECSuccess) {
1413
0
                    goto loser;
1414
0
                }
1415
9.73k
                rv = sslBuffer_Skip(chInnerXtns, 2, &tmpOffset);
1416
9.73k
                if (rv != SECSuccess) {
1417
0
                    goto loser;
1418
0
                }
1419
9.73k
                tmpLen = SSL_BUFFER_LEN(chInnerXtns);
1420
9.73k
                rv = ssl3_ClientFormatServerNameXtn(ss, ss->url,
1421
9.73k
                                                    strlen(ss->url),
1422
9.73k
                                                    NULL, chInnerXtns);
1423
9.73k
                if (rv != SECSuccess) {
1424
0
                    goto loser;
1425
0
                }
1426
9.73k
                tmpLen = SSL_BUFFER_LEN(chInnerXtns) - tmpLen;
1427
9.73k
                rv = sslBuffer_InsertNumber(chInnerXtns, tmpOffset, tmpLen, 2);
1428
9.73k
                if (rv != SECSuccess) {
1429
0
                    goto loser;
1430
0
                }
1431
                /* Only update state on second invocation of this function */
1432
9.73k
                if (shouldCompress) {
1433
5.65k
                    ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = extensionType;
1434
5.65k
                }
1435
9.73k
                break;
1436
9.73k
            case ssl_tls13_supported_versions_xtn:
1437
                /* Only TLS 1.3 and GREASE on CHInner. */
1438
9.73k
                rv = sslBuffer_AppendNumber(chInnerXtns, extensionType, 2);
1439
9.73k
                if (rv != SECSuccess) {
1440
0
                    goto loser;
1441
0
                }
1442
                /* Extension length. */
1443
9.73k
                tmpLen = (ss->opt.enableGrease) ? 5 : 3;
1444
9.73k
                rv = sslBuffer_AppendNumber(chInnerXtns, tmpLen, 2);
1445
9.73k
                if (rv != SECSuccess) {
1446
0
                    goto loser;
1447
0
                }
1448
                /* ProtocolVersion length */
1449
9.73k
                rv = sslBuffer_AppendNumber(chInnerXtns, tmpLen - 1, 1);
1450
9.73k
                if (rv != SECSuccess) {
1451
0
                    goto loser;
1452
0
                }
1453
                /* ProtocolVersion TLS 1.3 */
1454
9.73k
                rv = sslBuffer_AppendNumber(chInnerXtns, SSL_LIBRARY_VERSION_TLS_1_3, 2);
1455
9.73k
                if (rv != SECSuccess) {
1456
0
                    goto loser;
1457
0
                }
1458
                /* ProtocolVersion GREASE */
1459
9.73k
                if (ss->opt.enableGrease) {
1460
5.10k
                    rv = sslBuffer_AppendNumber(chInnerXtns, ss->ssl3.hs.grease->idx[grease_version], 2);
1461
5.10k
                    if (rv != SECSuccess) {
1462
0
                        goto loser;
1463
0
                    }
1464
5.10k
                }
1465
                /* Only update state on second invocation of this function */
1466
9.73k
                if (shouldCompress) {
1467
5.65k
                    ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = extensionType;
1468
5.65k
                }
1469
9.73k
                break;
1470
4.67k
            case ssl_tls13_pre_shared_key_xtn:
1471
4.67k
                if (inOutPskXtn && !shouldCompress) {
1472
1.91k
                    rv = sslBuffer_AppendNumber(&pskXtn, extensionType, 2);
1473
1.91k
                    if (rv != SECSuccess) {
1474
0
                        goto loser;
1475
0
                    }
1476
1.91k
                    rv = sslBuffer_AppendVariable(&pskXtn, extensionData.buf,
1477
1.91k
                                                  extensionData.len, 2);
1478
1.91k
                    if (rv != SECSuccess) {
1479
0
                        goto loser;
1480
0
                    }
1481
                    /* This should be the last extension. */
1482
1.91k
                    PORT_Assert(srcXtnBase == ss->xtnData.lastXtnOffset);
1483
1.91k
                    PORT_Assert(chOuterXtnsBuf->len - srcXtnBase == extensionData.len + 4);
1484
1.91k
                    rv = tls13_RandomizePsk(chOuterXtnsBuf->buf + srcXtnBase + 4,
1485
1.91k
                                            chOuterXtnsBuf->len - srcXtnBase - 4);
1486
1.91k
                    if (rv != SECSuccess) {
1487
0
                        goto loser;
1488
0
                    }
1489
2.76k
                } else if (!inOutPskXtn) {
1490
                    /* When GREASEing, only the length is used.
1491
                     * Order doesn't matter, so just copy the extension. */
1492
853
                    rv = sslBuffer_AppendNumber(chInnerXtns, extensionType, 2);
1493
853
                    if (rv != SECSuccess) {
1494
0
                        goto loser;
1495
0
                    }
1496
853
                    rv = sslBuffer_AppendVariable(chInnerXtns, extensionData.buf,
1497
853
                                                  extensionData.len, 2);
1498
853
                    if (rv != SECSuccess) {
1499
0
                        goto loser;
1500
0
                    }
1501
853
                }
1502
                /* Only update state on second invocation of this function */
1503
4.67k
                if (shouldCompress) {
1504
2.76k
                    ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = extensionType;
1505
2.76k
                }
1506
4.67k
                break;
1507
73.3k
            default: {
1508
                /* This is a regular extension.  We can maybe compress these. */
1509
73.3k
                rv = tls13_ChInnerAppendExtension(ss, extensionType,
1510
73.3k
                                                  &extensionData,
1511
73.3k
                                                  &dupXtns, chInnerXtns,
1512
73.3k
                                                  shouldCompress,
1513
73.3k
                                                  called, &nCalled);
1514
73.3k
                if (rv != SECSuccess) {
1515
0
                    goto loser;
1516
0
                }
1517
73.3k
                break;
1518
73.3k
            }
1519
97.4k
        }
1520
97.4k
    }
1521
1522
9.73k
    rv = tls13_WriteDupXtnsToChInner(shouldCompress, &dupXtns, chInnerXtns);
1523
9.73k
    if (rv != SECSuccess) {
1524
0
        goto loser;
1525
0
    }
1526
1527
    /* Now call custom extension handlers that didn't choose to append anything to
1528
     * the outer ClientHello. */
1529
9.73k
    rv = tls13_ChInnerAdditionalExtensionWriters(ss, called, nCalled, chInnerXtns);
1530
9.73k
    if (rv != SECSuccess) {
1531
0
        goto loser;
1532
0
    }
1533
1534
9.73k
    if (inOutPskXtn) {
1535
        /* On the first, non-compress run, append the (bad) PSK binder.
1536
         * On the second compression run, the caller is responsible for
1537
         * providing an extension with a valid binder, so append that. */
1538
8.16k
        if (shouldCompress) {
1539
4.08k
            rv = sslBuffer_AppendBuffer(chInnerXtns, inOutPskXtn);
1540
4.08k
        } else {
1541
4.08k
            rv = sslBuffer_AppendBuffer(chInnerXtns, &pskXtn);
1542
4.08k
            *inOutPskXtn = pskXtn;
1543
4.08k
        }
1544
8.16k
        if (rv != SECSuccess) {
1545
0
            goto loser;
1546
0
        }
1547
8.16k
    }
1548
1549
9.73k
    return SECSuccess;
1550
1551
0
loser:
1552
0
    sslBuffer_Clear(&pskXtn);
1553
0
    sslBuffer_Clear(&dupXtns);
1554
0
    return SECFailure;
1555
9.73k
}
1556
1557
static SECStatus
1558
tls13_EncodeClientHelloInner(sslSocket *ss, const sslBuffer *chInner, const sslBuffer *chInnerXtns, sslBuffer *out)
1559
5.65k
{
1560
5.65k
    PORT_Assert(ss && chInner && chInnerXtns && out);
1561
5.65k
    SECStatus rv;
1562
5.65k
    sslReadBuffer tmpReadBuf;
1563
5.65k
    sslReader chReader = SSL_READER(chInner->buf, chInner->len);
1564
1565
5.65k
    rv = sslRead_Read(&chReader, 4, &tmpReadBuf);
1566
5.65k
    if (rv != SECSuccess) {
1567
0
        goto loser;
1568
0
    }
1569
1570
5.65k
    rv = sslRead_Read(&chReader, 2 + SSL3_RANDOM_LENGTH, &tmpReadBuf);
1571
5.65k
    if (rv != SECSuccess) {
1572
0
        goto loser;
1573
0
    }
1574
5.65k
    rv = sslBuffer_Append(out, tmpReadBuf.buf, tmpReadBuf.len);
1575
5.65k
    if (rv != SECSuccess) {
1576
0
        goto loser;
1577
0
    }
1578
1579
    /* Skip the legacy_session_id */
1580
5.65k
    rv = sslRead_ReadVariable(&chReader, 1, &tmpReadBuf);
1581
5.65k
    if (rv != SECSuccess) {
1582
0
        goto loser;
1583
0
    }
1584
5.65k
    rv = sslBuffer_AppendNumber(out, 0, 1);
1585
5.65k
    if (rv != SECSuccess) {
1586
0
        goto loser;
1587
0
    }
1588
1589
    /* cipher suites */
1590
5.65k
    rv = sslRead_ReadVariable(&chReader, 2, &tmpReadBuf);
1591
5.65k
    if (rv != SECSuccess) {
1592
0
        goto loser;
1593
0
    }
1594
5.65k
    rv = sslBuffer_AppendVariable(out, tmpReadBuf.buf, tmpReadBuf.len, 2);
1595
5.65k
    if (rv != SECSuccess) {
1596
0
        goto loser;
1597
0
    }
1598
1599
    /* compression methods */
1600
5.65k
    rv = sslRead_ReadVariable(&chReader, 1, &tmpReadBuf);
1601
5.65k
    if (rv != SECSuccess) {
1602
0
        goto loser;
1603
0
    }
1604
5.65k
    rv = sslBuffer_AppendVariable(out, tmpReadBuf.buf, tmpReadBuf.len, 1);
1605
5.65k
    if (rv != SECSuccess) {
1606
0
        goto loser;
1607
0
    }
1608
1609
    /* Append the extensions. */
1610
5.65k
    rv = sslBuffer_AppendBufferVariable(out, chInnerXtns, 2);
1611
5.65k
    if (rv != SECSuccess) {
1612
0
        goto loser;
1613
0
    }
1614
5.65k
    return SECSuccess;
1615
1616
0
loser:
1617
0
    sslBuffer_Clear(out);
1618
0
    return SECFailure;
1619
5.65k
}
1620
1621
SECStatus
1622
tls13_PadChInner(sslBuffer *chInner, uint8_t maxNameLen, uint8_t serverNameLen)
1623
5.65k
{
1624
5.65k
    SECStatus rv;
1625
5.65k
    PORT_Assert(chInner);
1626
5.65k
    PORT_Assert(serverNameLen > 0);
1627
5.65k
    static unsigned char padding[256 + 32] = { 0 };
1628
5.65k
    int16_t name_padding = (int16_t)maxNameLen - (int16_t)serverNameLen;
1629
5.65k
    if (name_padding < 0) {
1630
4.08k
        name_padding = 0;
1631
4.08k
    }
1632
5.65k
    unsigned int rounding_padding = 31 - ((SSL_BUFFER_LEN(chInner) + name_padding) % 32);
1633
5.65k
    unsigned int total_padding = name_padding + rounding_padding;
1634
5.65k
    PORT_Assert(total_padding < sizeof(padding));
1635
5.65k
    SSL_TRC(100, ("computed ECH Inner Client Hello padding of size %u", total_padding));
1636
5.65k
    rv = sslBuffer_Append(chInner, padding, total_padding);
1637
5.65k
    if (rv != SECSuccess) {
1638
0
        sslBuffer_Clear(chInner);
1639
0
        return SECFailure;
1640
0
    }
1641
5.65k
    return SECSuccess;
1642
5.65k
}
1643
1644
/* Build an ECH Xtn body with a zeroed payload for the client hello inner
1645
 *
1646
 *   enum { outer(0), inner(1) } ECHClientHelloType;
1647
 *
1648
 *   struct {
1649
 *      ECHClientHelloType type;
1650
 *      select (ECHClientHello.type) {
1651
 *          case outer:
1652
 *              HpkeSymmetricCipherSuite cipher_suite;
1653
 *              uint8 config_id;
1654
 *              opaque enc<0..2^16-1>;
1655
 *              opaque payload<1..2^16-1>;
1656
 *          case inner:
1657
 *              Empty;
1658
 *      };
1659
 *  } ECHClientHello;
1660
 *
1661
 * payloadLen = Size of zeroed placeholder field for payload.
1662
 * payloadOffset = Out parameter, start of payload field
1663
 * echXtn = Out parameter, constructed ECH Xtn with zeroed placeholder field.
1664
 */
1665
SECStatus
1666
tls13_BuildEchXtn(sslEchConfig *cfg, const SECItem *hpkeEnc, unsigned int payloadLen, PRUint16 *payloadOffset, sslBuffer *echXtn)
1667
4.08k
{
1668
4.08k
    SECStatus rv;
1669
    /* Format the encrypted_client_hello extension. */
1670
4.08k
    rv = sslBuffer_AppendNumber(echXtn, ech_xtn_type_outer, 1);
1671
4.08k
    if (rv != SECSuccess) {
1672
0
        goto loser;
1673
0
    }
1674
4.08k
    rv = sslBuffer_AppendNumber(echXtn, cfg->contents.kdfId, 2);
1675
4.08k
    if (rv != SECSuccess) {
1676
0
        goto loser;
1677
0
    }
1678
4.08k
    rv = sslBuffer_AppendNumber(echXtn, cfg->contents.aeadId, 2);
1679
4.08k
    if (rv != SECSuccess) {
1680
0
        goto loser;
1681
0
    }
1682
1683
4.08k
    rv = sslBuffer_AppendNumber(echXtn, cfg->contents.configId, 1);
1684
4.08k
    if (rv != SECSuccess) {
1685
0
        goto loser;
1686
0
    }
1687
4.08k
    if (hpkeEnc) {
1688
        /* Public Key */
1689
3.42k
        rv = sslBuffer_AppendVariable(echXtn, hpkeEnc->data, hpkeEnc->len, 2);
1690
3.42k
        if (rv != SECSuccess) {
1691
0
            goto loser;
1692
0
        }
1693
3.42k
    } else {
1694
        /* |enc| is empty. */
1695
660
        rv = sslBuffer_AppendNumber(echXtn, 0, 2);
1696
660
        if (rv != SECSuccess) {
1697
0
            goto loser;
1698
0
        }
1699
660
    }
1700
4.08k
    payloadLen += TLS13_ECH_AEAD_TAG_LEN;
1701
4.08k
    rv = sslBuffer_AppendNumber(echXtn, payloadLen, 2);
1702
4.08k
    if (rv != SECSuccess) {
1703
0
        goto loser;
1704
0
    }
1705
4.08k
    *payloadOffset = echXtn->len;
1706
4.08k
    rv = sslBuffer_Fill(echXtn, 0, payloadLen);
1707
4.08k
    if (rv != SECSuccess) {
1708
0
        goto loser;
1709
0
    }
1710
4.08k
    PRINT_BUF(100, (NULL, "ECH Xtn with Placeholder:", echXtn->buf, echXtn->len));
1711
4.08k
    return SECSuccess;
1712
0
loser:
1713
0
    sslBuffer_Clear(echXtn);
1714
0
    return SECFailure;
1715
4.08k
}
1716
1717
SECStatus
1718
tls13_ConstructClientHelloWithEch(sslSocket *ss, const sslSessionID *sid, PRBool freshSid,
1719
                                  sslBuffer *chOuter, sslBuffer *chOuterXtnsBuf)
1720
4.08k
{
1721
4.08k
    SECStatus rv;
1722
4.08k
    sslBuffer chInner = SSL_BUFFER_EMPTY;
1723
4.08k
    sslBuffer encodedChInner = SSL_BUFFER_EMPTY;
1724
4.08k
    sslBuffer paddingChInner = SSL_BUFFER_EMPTY;
1725
4.08k
    sslBuffer chInnerXtns = SSL_BUFFER_EMPTY;
1726
4.08k
    sslBuffer pskXtn = SSL_BUFFER_EMPTY;
1727
4.08k
    unsigned int preambleLen;
1728
1729
4.08k
    SSL_TRC(50, ("%d: TLS13[%d]: Constructing ECH inner", SSL_GETPID(), ss->fd));
1730
1731
    /* Create the full (uncompressed) inner extensions and steal any PSK extension.
1732
     * NB: Neither chOuterXtnsBuf nor chInnerXtns are length-prefixed. */
1733
4.08k
    rv = tls13_ConstructInnerExtensionsFromOuter(ss, chOuterXtnsBuf, &chInnerXtns,
1734
4.08k
                                                 &pskXtn, PR_FALSE);
1735
4.08k
    if (rv != SECSuccess) {
1736
0
        goto loser; /* code set */
1737
0
    }
1738
1739
4.08k
    rv = ssl3_CreateClientHelloPreamble(ss, sid, PR_FALSE, SSL_LIBRARY_VERSION_TLS_1_3,
1740
4.08k
                                        PR_TRUE, &chInnerXtns, &chInner);
1741
4.08k
    if (rv != SECSuccess) {
1742
0
        goto loser; /* code set */
1743
0
    }
1744
4.08k
    preambleLen = SSL_BUFFER_LEN(&chInner);
1745
1746
    /* Write handshake header length. tls13_EncryptClientHello will
1747
     * remove this upon encoding, but the transcript needs it. This assumes
1748
     * the 4B stream-variant header. */
1749
4.08k
    PORT_Assert(!IS_DTLS(ss));
1750
4.08k
    rv = sslBuffer_InsertNumber(&chInner, 1,
1751
4.08k
                                chInner.len + 2 + chInnerXtns.len - 4, 3);
1752
4.08k
    if (rv != SECSuccess) {
1753
0
        goto loser;
1754
0
    }
1755
1756
4.08k
    if (pskXtn.len) {
1757
1.91k
        PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn));
1758
1.91k
        rv = tls13_WriteExtensionsWithBinder(ss, &chInnerXtns, &chInner);
1759
        /* Update the stolen PSK extension with the binder value. */
1760
1.91k
        PORT_Memcpy(pskXtn.buf, &chInnerXtns.buf[chInnerXtns.len - pskXtn.len], pskXtn.len);
1761
2.17k
    } else {
1762
2.17k
        rv = sslBuffer_AppendBufferVariable(&chInner, &chInnerXtns, 2);
1763
2.17k
    }
1764
4.08k
    if (rv != SECSuccess) {
1765
0
        goto loser;
1766
0
    }
1767
1768
4.08k
    PRINT_BUF(50, (ss, "Uncompressed CHInner", chInner.buf, chInner.len));
1769
4.08k
    rv = ssl3_UpdateHandshakeHashesInt(ss, chInner.buf, chInner.len,
1770
4.08k
                                       &ss->ssl3.hs.echInnerMessages);
1771
4.08k
    if (rv != SECSuccess) {
1772
0
        goto loser; /* code set */
1773
0
    }
1774
1775
    /* Un-append the extensions, then append compressed via Encoded. */
1776
4.08k
    SSL_BUFFER_LEN(&chInner) = preambleLen;
1777
4.08k
    sslBuffer_Clear(&chInnerXtns);
1778
4.08k
    rv = tls13_ConstructInnerExtensionsFromOuter(ss, chOuterXtnsBuf,
1779
4.08k
                                                 &chInnerXtns, &pskXtn, PR_TRUE);
1780
4.08k
    if (rv != SECSuccess) {
1781
0
        goto loser;
1782
0
    }
1783
1784
4.08k
    rv = tls13_EncodeClientHelloInner(ss, &chInner, &chInnerXtns, &encodedChInner);
1785
4.08k
    if (rv != SECSuccess) {
1786
0
        goto loser;
1787
0
    }
1788
4.08k
    PRINT_BUF(50, (ss, "Compressed CHInner", encodedChInner.buf, encodedChInner.len));
1789
1790
4.08k
    PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->echConfigs));
1791
4.08k
    sslEchConfig *cfg = (sslEchConfig *)PR_LIST_HEAD(&ss->echConfigs);
1792
1793
    /* We are using ECH so SNI must have been included */
1794
4.08k
    rv = tls13_PadChInner(&encodedChInner, cfg->contents.maxNameLen, strlen(ss->url));
1795
4.08k
    if (rv != SECSuccess) {
1796
0
        goto loser;
1797
0
    }
1798
1799
    /* Build the ECH Xtn with placeholder and put it in chOuterXtnsBuf */
1800
4.08k
    sslBuffer echXtn = SSL_BUFFER_EMPTY;
1801
4.08k
    const SECItem *hpkeEnc = NULL;
1802
4.08k
    if (!ss->ssl3.hs.helloRetry) {
1803
3.42k
        hpkeEnc = PK11_HPKE_GetEncapPubKey(ss->ssl3.hs.echHpkeCtx);
1804
3.42k
        if (!hpkeEnc) {
1805
0
            FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
1806
0
            goto loser;
1807
0
        }
1808
3.42k
    }
1809
4.08k
    PRUint16 echXtnPayloadOffset; /* Offset from start of ECH Xtn to ECH Payload */
1810
4.08k
    rv = tls13_BuildEchXtn(cfg, hpkeEnc, encodedChInner.len, &echXtnPayloadOffset, &echXtn);
1811
4.08k
    if (rv != SECSuccess) {
1812
0
        goto loser;
1813
0
    }
1814
4.08k
    ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = ssl_tls13_encrypted_client_hello_xtn;
1815
4.08k
    rv = ssl3_EmplaceExtension(ss, chOuterXtnsBuf, ssl_tls13_encrypted_client_hello_xtn,
1816
4.08k
                               echXtn.buf, echXtn.len, PR_TRUE);
1817
4.08k
    if (rv != SECSuccess) {
1818
0
        goto loser;
1819
0
    }
1820
1821
    /* Add the padding */
1822
4.08k
    rv = ssl_InsertPaddingExtension(ss, chOuter->len, chOuterXtnsBuf);
1823
4.08k
    if (rv != SECSuccess) {
1824
0
        goto loser;
1825
0
    }
1826
1827
    /* Finish the CHO with the ECH Xtn payload zeroed */
1828
4.08k
    rv = ssl3_InsertChHeaderSize(ss, chOuter, chOuterXtnsBuf);
1829
4.08k
    if (rv != SECSuccess) {
1830
0
        goto loser;
1831
0
    }
1832
4.08k
    unsigned int chOuterXtnsOffset = chOuter->len + 2; /* From Start of CHO to Extensions list */
1833
4.08k
    rv = sslBuffer_AppendBufferVariable(chOuter, chOuterXtnsBuf, 2);
1834
4.08k
    if (rv != SECSuccess) {
1835
0
        goto loser;
1836
0
    }
1837
1838
    /* AAD consists of entire CHO, minus the 4 byte handshake header */
1839
4.08k
    SECItem aadItem = { siBuffer, chOuter->buf + 4, chOuter->len - 4 };
1840
    /* ECH Payload begins after CHO Header, after ECH Xtn start, after ECH Xtn header */
1841
4.08k
    PRUint8 *echPayload = chOuter->buf + chOuterXtnsOffset + ss->xtnData.echXtnOffset + 4 + echXtnPayloadOffset;
1842
    /* Insert the encrypted_client_hello xtn and coalesce. */
1843
4.08k
    rv = tls13_EncryptClientHello(ss, &aadItem, &encodedChInner, echPayload);
1844
4.08k
    if (rv != SECSuccess) {
1845
0
        goto loser;
1846
0
    }
1847
1848
4.08k
    sslBuffer_Clear(&echXtn);
1849
4.08k
    sslBuffer_Clear(&chInner);
1850
4.08k
    sslBuffer_Clear(&encodedChInner);
1851
4.08k
    sslBuffer_Clear(&paddingChInner);
1852
4.08k
    sslBuffer_Clear(&chInnerXtns);
1853
4.08k
    sslBuffer_Clear(&pskXtn);
1854
4.08k
    return SECSuccess;
1855
1856
0
loser:
1857
0
    sslBuffer_Clear(&chInner);
1858
0
    sslBuffer_Clear(&encodedChInner);
1859
0
    sslBuffer_Clear(&paddingChInner);
1860
0
    sslBuffer_Clear(&chInnerXtns);
1861
0
    sslBuffer_Clear(&pskXtn);
1862
0
    PORT_Assert(PORT_GetError() != 0);
1863
0
    return SECFailure;
1864
4.08k
}
1865
1866
static SECStatus
1867
tls13_ComputeEchHelloRetryTranscript(sslSocket *ss, const PRUint8 *sh, unsigned int shLen, sslBuffer *out)
1868
27
{
1869
27
    SECStatus rv;
1870
27
    PRUint8 zeroedEchSignal[TLS13_ECH_SIGNAL_LEN] = { 0 };
1871
27
    sslBuffer *previousTranscript;
1872
1873
27
    if (ss->sec.isServer) {
1874
20
        previousTranscript = &(ss->ssl3.hs.messages);
1875
20
    } else {
1876
7
        previousTranscript = &(ss->ssl3.hs.echInnerMessages);
1877
7
    }
1878
    /*
1879
     *  This segment calculates the hash of the Client Hello
1880
     *  TODO(djackson@mozilla.com) - Replace with existing function?
1881
     *  e.g. tls13_ReinjectHandshakeTranscript
1882
     *  TODO(djackson@mozilla.com) - Replace with streaming version
1883
     */
1884
27
    if (!ss->ssl3.hs.helloRetry || !ss->sec.isServer) {
1885
        /*
1886
         * This function can be called in three situations:
1887
         *    - By the server, prior to sending the HRR, when ECH was accepted
1888
         *    - By the client, after receiving the HRR, but before it knows whether ECH was accepted
1889
         *    - By the server, after accepting ECH and receiving CH2 when it needs to reconstruct the HRR
1890
         * In the first two situations, we need to include the message hash of inner ClientHello1 but don't
1891
         * want to alter the buffer containing the current transcript.
1892
         * In the last, the buffer already contains the message hash of inner ClientHello1.
1893
         */
1894
27
        SSL3Hashes hashes;
1895
27
        rv = tls13_ComputeHash(ss, &hashes, previousTranscript->buf, previousTranscript->len, tls13_GetHash(ss));
1896
27
        if (rv != SECSuccess) {
1897
0
            goto loser;
1898
0
        }
1899
27
        rv = sslBuffer_AppendNumber(out, ssl_hs_message_hash, 1);
1900
27
        if (rv != SECSuccess) {
1901
0
            goto loser;
1902
0
        }
1903
27
        rv = sslBuffer_AppendNumber(out, hashes.len, 3);
1904
27
        if (rv != SECSuccess) {
1905
0
            goto loser;
1906
0
        }
1907
27
        rv = sslBuffer_Append(out, hashes.u.raw, hashes.len);
1908
27
        if (rv != SECSuccess) {
1909
0
            goto loser;
1910
0
        }
1911
27
    } else {
1912
0
        rv = sslBuffer_AppendBuffer(out, previousTranscript);
1913
0
        if (rv != SECSuccess) {
1914
0
            goto loser;
1915
0
        }
1916
0
    }
1917
    /* Ensure the first ClientHello has been hashed. */
1918
27
    PR_ASSERT(out->len == tls13_GetHashSize(ss) + 4);
1919
27
    PRINT_BUF(100, (ss, "ECH Client Hello Message Hash", out->buf, out->len));
1920
    /* Message Header */
1921
27
    rv = sslBuffer_AppendNumber(out, ssl_hs_server_hello, 1);
1922
27
    if (rv != SECSuccess) {
1923
0
        goto loser;
1924
0
    }
1925
    /* Message Size */
1926
27
    rv = sslBuffer_AppendNumber(out, shLen, 3);
1927
27
    if (rv != SECSuccess) {
1928
0
        goto loser;
1929
0
    }
1930
    /* Calculate where the HRR ECH Xtn Signal begins */
1931
27
    unsigned int absEchOffset;
1932
27
    if (ss->sec.isServer) {
1933
        /* We know the ECH HRR Xtn is last */
1934
20
        PORT_Assert(shLen >= TLS13_ECH_SIGNAL_LEN);
1935
20
        absEchOffset = shLen - TLS13_ECH_SIGNAL_LEN;
1936
20
    } else {
1937
        /* We parsed the offset earlier */
1938
        /* The result of pointer comparision is unspecified
1939
         * (and pointer arithemtic is undefined) if the pointers
1940
         * do not point to the same array or struct. That means these
1941
         * asserts cannot be relied on for correctness in compiled code,
1942
         * but may help the reader understand the requirements.
1943
         */
1944
7
        PORT_Assert(ss->xtnData.ech->hrrConfirmation > sh);
1945
7
        PORT_Assert(ss->xtnData.ech->hrrConfirmation < sh + shLen);
1946
7
        absEchOffset = ss->xtnData.ech->hrrConfirmation - sh;
1947
7
    }
1948
27
    PR_ASSERT(tls13_Debug_CheckXtnBegins(sh + absEchOffset - 4, ssl_tls13_encrypted_client_hello_xtn));
1949
    /* The HRR up to the ECH Xtn signal */
1950
27
    rv = sslBuffer_Append(out, sh, absEchOffset);
1951
27
    if (rv != SECSuccess) {
1952
0
        goto loser;
1953
0
    }
1954
27
    rv = sslBuffer_Append(out, zeroedEchSignal, sizeof(zeroedEchSignal));
1955
27
    if (rv != SECSuccess) {
1956
0
        goto loser;
1957
0
    }
1958
27
    PR_ASSERT(absEchOffset + TLS13_ECH_SIGNAL_LEN <= shLen);
1959
    /* The remainder of the HRR */
1960
27
    rv = sslBuffer_Append(out, sh + absEchOffset + TLS13_ECH_SIGNAL_LEN, shLen - absEchOffset - TLS13_ECH_SIGNAL_LEN);
1961
27
    if (rv != SECSuccess) {
1962
0
        goto loser;
1963
0
    }
1964
27
    PR_ASSERT(out->len == tls13_GetHashSize(ss) + 4 + shLen + 4);
1965
27
    return SECSuccess;
1966
0
loser:
1967
0
    sslBuffer_Clear(out);
1968
0
    return SECFailure;
1969
27
}
1970
1971
static SECStatus
1972
tls13_ComputeEchServerHelloTranscript(sslSocket *ss, const PRUint8 *sh, unsigned int shLen, sslBuffer *out)
1973
546
{
1974
546
    SECStatus rv;
1975
546
    sslBuffer *chSource = ss->sec.isServer ? &ss->ssl3.hs.messages : &ss->ssl3.hs.echInnerMessages;
1976
546
    unsigned int offset = sizeof(SSL3ProtocolVersion) +
1977
546
                          SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN;
1978
546
    PORT_Assert(sh && shLen > offset);
1979
546
    PORT_Assert(TLS13_ECH_SIGNAL_LEN <= SSL3_RANDOM_LENGTH);
1980
1981
    /* TODO(djackson@mozilla.com) - Replace with streaming version */
1982
1983
546
    rv = sslBuffer_AppendBuffer(out, chSource);
1984
546
    if (rv != SECSuccess) {
1985
0
        goto loser;
1986
0
    }
1987
1988
    /* Re-create the message header. */
1989
546
    rv = sslBuffer_AppendNumber(out, ssl_hs_server_hello, 1);
1990
546
    if (rv != SECSuccess) {
1991
0
        goto loser;
1992
0
    }
1993
1994
546
    rv = sslBuffer_AppendNumber(out, shLen, 3);
1995
546
    if (rv != SECSuccess) {
1996
0
        goto loser;
1997
0
    }
1998
1999
    /* Copy the version and 24B of server_random. */
2000
546
    rv = sslBuffer_Append(out, sh, offset);
2001
546
    if (rv != SECSuccess) {
2002
0
        goto loser;
2003
0
    }
2004
2005
    /* Zero the signal placeholder. */
2006
546
    rv = sslBuffer_AppendNumber(out, 0, TLS13_ECH_SIGNAL_LEN);
2007
546
    if (rv != SECSuccess) {
2008
0
        goto loser;
2009
0
    }
2010
546
    offset += TLS13_ECH_SIGNAL_LEN;
2011
2012
    /* Use the remainder of SH. */
2013
546
    rv = sslBuffer_Append(out, &sh[offset], shLen - offset);
2014
546
    if (rv != SECSuccess) {
2015
0
        goto loser;
2016
0
    }
2017
546
    sslBuffer_Clear(&ss->ssl3.hs.messages);
2018
546
    sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
2019
546
    return SECSuccess;
2020
0
loser:
2021
0
    sslBuffer_Clear(&ss->ssl3.hs.messages);
2022
0
    sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
2023
0
    sslBuffer_Clear(out);
2024
0
    return SECFailure;
2025
546
}
2026
2027
/* Compute the ECH signal using the transcript (up to, including)
2028
 * ServerHello. The server sources this transcript prefix from
2029
 * ss->ssl3.hs.messages, as it never uses ss->ssl3.hs.echInnerMessages.
2030
 * The client uses the inner transcript, echInnerMessages. */
2031
SECStatus
2032
tls13_ComputeEchSignal(sslSocket *ss, PRBool isHrr, const PRUint8 *sh, unsigned int shLen, PRUint8 *out)
2033
573
{
2034
573
    SECStatus rv;
2035
573
    sslBuffer confMsgs = SSL_BUFFER_EMPTY;
2036
573
    SSL3Hashes hashes;
2037
573
    PK11SymKey *echSecret = NULL;
2038
2039
573
    const char *hkdfInfo = isHrr ? kHkdfInfoEchHrrConfirm : kHkdfInfoEchConfirm;
2040
573
    const size_t hkdfInfoLen = strlen(hkdfInfo);
2041
2042
573
    PRINT_BUF(100, (ss, "ECH Server Hello", sh, shLen));
2043
2044
573
    if (isHrr) {
2045
27
        rv = tls13_ComputeEchHelloRetryTranscript(ss, sh, shLen, &confMsgs);
2046
546
    } else {
2047
546
        rv = tls13_ComputeEchServerHelloTranscript(ss, sh, shLen, &confMsgs);
2048
546
    }
2049
573
    if (rv != SECSuccess) {
2050
0
        goto loser;
2051
0
    }
2052
573
    PRINT_BUF(100, (ss, "ECH Transcript", confMsgs.buf, confMsgs.len));
2053
573
    rv = tls13_ComputeHash(ss, &hashes, confMsgs.buf, confMsgs.len,
2054
573
                           tls13_GetHash(ss));
2055
573
    if (rv != SECSuccess) {
2056
0
        goto loser;
2057
0
    }
2058
573
    PRINT_BUF(100, (ss, "ECH Transcript Hash", &hashes.u, hashes.len));
2059
573
    rv = tls13_DeriveEchSecret(ss, &echSecret);
2060
573
    if (rv != SECSuccess) {
2061
0
        return SECFailure;
2062
0
    }
2063
573
    rv = tls13_HkdfExpandLabelRaw(echSecret, tls13_GetHash(ss), hashes.u.raw,
2064
573
                                  hashes.len, hkdfInfo, hkdfInfoLen, ss->protocolVariant,
2065
573
                                  out, TLS13_ECH_SIGNAL_LEN);
2066
573
    if (rv != SECSuccess) {
2067
0
        return SECFailure;
2068
0
    }
2069
573
    SSL_TRC(50, ("%d: TLS13[%d]: %s computed ECH signal", SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
2070
573
    PRINT_BUF(50, (ss, "Computed ECH Signal", out, TLS13_ECH_SIGNAL_LEN));
2071
573
    PK11_FreeSymKey(echSecret);
2072
573
    sslBuffer_Clear(&confMsgs);
2073
573
    return SECSuccess;
2074
2075
0
loser:
2076
0
    PK11_FreeSymKey(echSecret);
2077
0
    sslBuffer_Clear(&confMsgs);
2078
0
    return SECFailure;
2079
573
}
2080
2081
/* Ech Secret is HKDF-Extract(0, ClientHelloInner.random) where
2082
   "0" is a string of Hash.len bytes of value 0. */
2083
SECStatus
2084
tls13_DeriveEchSecret(const sslSocket *ss, PK11SymKey **output)
2085
573
{
2086
573
    SECStatus rv;
2087
573
    PK11SlotInfo *slot = NULL;
2088
573
    PK11SymKey *crKey = NULL;
2089
573
    SECItem rawKey;
2090
573
    const unsigned char *client_random = ss->sec.isServer ? ss->ssl3.hs.client_random : ss->ssl3.hs.client_inner_random;
2091
573
    PRINT_BUF(50, (ss, "Client Random for ECH", client_random, SSL3_RANDOM_LENGTH));
2092
    /* We need a SECItem */
2093
573
    rv = SECITEM_MakeItem(NULL, &rawKey, client_random, SSL3_RANDOM_LENGTH);
2094
573
    if (rv != SECSuccess) {
2095
0
        goto cleanup;
2096
0
    }
2097
    /* We need a slot*/
2098
573
    slot = PK11_GetBestSlot(CKM_HKDF_DERIVE, NULL);
2099
573
    if (!slot) {
2100
0
        rv = SECFailure;
2101
0
        goto cleanup;
2102
0
    }
2103
    /* We import the key */
2104
573
    crKey = PK11_ImportDataKey(slot, CKM_HKDF_DERIVE, PK11_OriginUnwrap,
2105
573
                               CKA_DERIVE, &rawKey, NULL);
2106
573
    if (crKey == NULL) {
2107
0
        rv = SECFailure;
2108
0
        goto cleanup;
2109
0
    }
2110
    /* NULL will be expanded to 0s of hash length */
2111
573
    rv = tls13_HkdfExtract(NULL, crKey, tls13_GetHash(ss), output);
2112
573
    if (rv != SECSuccess) {
2113
0
        goto cleanup;
2114
0
    }
2115
573
    SSL_TRC(50, ("%d: TLS13[%d]: ECH Confirmation Key Derived.",
2116
573
                 SSL_GETPID(), ss->fd));
2117
573
    PRINT_KEY(50, (NULL, "ECH Confirmation Key", *output));
2118
573
cleanup:
2119
573
    SECITEM_ZfreeItem(&rawKey, PR_FALSE);
2120
573
    if (slot) {
2121
573
        PK11_FreeSlot(slot);
2122
573
    }
2123
573
    if (crKey) {
2124
573
        PK11_FreeSymKey(crKey);
2125
573
    }
2126
573
    if (rv != SECSuccess && *output) {
2127
0
        PK11_FreeSymKey(*output);
2128
0
        *output = NULL;
2129
0
    }
2130
573
    return rv;
2131
573
}
2132
2133
/* Called just prior to padding the CH. Use the size of the CH to estimate
2134
 * the size of a corresponding ECH extension, then add it to the buffer. */
2135
SECStatus
2136
tls13_MaybeGreaseEch(sslSocket *ss, const sslBuffer *preamble, sslBuffer *buf)
2137
73.0k
{
2138
73.0k
    SECStatus rv;
2139
73.0k
    sslBuffer chInnerXtns = SSL_BUFFER_EMPTY;
2140
73.0k
    sslBuffer encodedCh = SSL_BUFFER_EMPTY;
2141
73.0k
    sslBuffer greaseBuf = SSL_BUFFER_EMPTY;
2142
73.0k
    unsigned int payloadLen;
2143
73.0k
    HpkeAeadId aead;
2144
73.0k
    PK11SlotInfo *slot = NULL;
2145
73.0k
    PK11SymKey *hmacPrk = NULL;
2146
73.0k
    PK11SymKey *derivedData = NULL;
2147
73.0k
    SECItem *rawData;
2148
73.0k
    CK_HKDF_PARAMS params;
2149
73.0k
    SECItem paramsi;
2150
    /* 1B aead determinant (don't send), 1B config_id, 32B enc, payload */
2151
73.0k
    PR_ASSERT(!ss->sec.isServer);
2152
73.0k
    const int kNonPayloadLen = 34;
2153
2154
73.0k
    if (!ss->opt.enableTls13GreaseEch || ss->ssl3.hs.echHpkeCtx) {
2155
36.5k
        return SECSuccess;
2156
36.5k
    }
2157
2158
36.4k
    if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3 ||
2159
34.5k
        IS_DTLS(ss)) {
2160
34.5k
        return SECSuccess;
2161
34.5k
    }
2162
2163
1.94k
    if (ss->firstHsDone) {
2164
0
        sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
2165
0
    }
2166
2167
    /* In draft-09, CH2 sends exactly the same GREASE ECH extension. */
2168
1.94k
    if (ss->ssl3.hs.helloRetry) {
2169
366
        return ssl3_EmplaceExtension(ss, buf, ssl_tls13_encrypted_client_hello_xtn,
2170
366
                                     ss->ssl3.hs.greaseEchBuf.buf,
2171
366
                                     ss->ssl3.hs.greaseEchBuf.len, PR_TRUE);
2172
366
    }
2173
2174
    /* Compress the extensions for payload length. */
2175
1.57k
    rv = tls13_ConstructInnerExtensionsFromOuter(ss, buf, &chInnerXtns,
2176
1.57k
                                                 NULL, PR_TRUE);
2177
1.57k
    if (rv != SECSuccess) {
2178
0
        goto loser; /* Code set */
2179
0
    }
2180
1.57k
    rv = tls13_EncodeClientHelloInner(ss, preamble, &chInnerXtns, &encodedCh);
2181
1.57k
    if (rv != SECSuccess) {
2182
0
        goto loser; /* Code set */
2183
0
    }
2184
1.57k
    rv = tls13_PadChInner(&encodedCh, ss->ssl3.hs.greaseEchSize, strlen(ss->url));
2185
1.57k
    if (rv != SECSuccess) {
2186
0
        goto loser; /* Code set */
2187
0
    }
2188
2189
1.57k
    payloadLen = encodedCh.len;
2190
1.57k
    payloadLen += TLS13_ECH_AEAD_TAG_LEN; /* Aead tag */
2191
2192
    /* HMAC-Expand to get something that will pass for ciphertext. */
2193
1.57k
    slot = PK11_GetBestSlot(CKM_HKDF_DERIVE, NULL);
2194
1.57k
    if (!slot) {
2195
0
        goto loser;
2196
0
    }
2197
2198
1.57k
    hmacPrk = PK11_KeyGen(slot, CKM_HKDF_DATA, NULL, SHA256_LENGTH, NULL);
2199
1.57k
    if (!hmacPrk) {
2200
0
        goto loser;
2201
0
    }
2202
2203
1.57k
    params.bExtract = CK_FALSE;
2204
1.57k
    params.bExpand = CK_TRUE;
2205
1.57k
    params.prfHashMechanism = CKM_SHA256;
2206
1.57k
    params.pInfo = NULL;
2207
1.57k
    params.ulInfoLen = 0;
2208
1.57k
    paramsi.data = (unsigned char *)&params;
2209
1.57k
    paramsi.len = sizeof(params);
2210
1.57k
    derivedData = PK11_DeriveWithFlags(hmacPrk, CKM_HKDF_DATA,
2211
1.57k
                                       &paramsi, CKM_HKDF_DATA,
2212
1.57k
                                       CKA_DERIVE, kNonPayloadLen + payloadLen,
2213
1.57k
                                       CKF_VERIFY);
2214
1.57k
    if (!derivedData) {
2215
0
        goto loser;
2216
0
    }
2217
2218
1.57k
    rv = PK11_ExtractKeyValue(derivedData);
2219
1.57k
    if (rv != SECSuccess) {
2220
0
        goto loser;
2221
0
    }
2222
2223
1.57k
    rawData = PK11_GetKeyData(derivedData);
2224
1.57k
    if (!rawData) {
2225
0
        goto loser;
2226
0
    }
2227
1.57k
    PORT_Assert(rawData->len == kNonPayloadLen + payloadLen);
2228
2229
    /* struct {
2230
       HpkeSymmetricCipherSuite cipher_suite; // kdf_id, aead_id
2231
       PRUint8 config_id;
2232
       opaque enc<1..2^16-1>;
2233
       opaque payload<1..2^16-1>;
2234
    } ClientECH; */
2235
2236
1.57k
    rv = sslBuffer_AppendNumber(&greaseBuf, ech_xtn_type_outer, 1);
2237
1.57k
    if (rv != SECSuccess) {
2238
0
        goto loser;
2239
0
    }
2240
    /* Only support SHA256. */
2241
1.57k
    rv = sslBuffer_AppendNumber(&greaseBuf, HpkeKdfHkdfSha256, 2);
2242
1.57k
    if (rv != SECSuccess) {
2243
0
        goto loser;
2244
0
    }
2245
2246
    /* HpkeAeadAes128Gcm = 1, HpkeAeadChaCha20Poly1305 = 3, */
2247
1.57k
    aead = (rawData->data[0] & 1) ? HpkeAeadAes128Gcm : HpkeAeadChaCha20Poly1305;
2248
1.57k
    rv = sslBuffer_AppendNumber(&greaseBuf, aead, 2);
2249
1.57k
    if (rv != SECSuccess) {
2250
0
        goto loser;
2251
0
    }
2252
2253
    /* config_id */
2254
1.57k
    rv = sslBuffer_AppendNumber(&greaseBuf, rawData->data[1], 1);
2255
1.57k
    if (rv != SECSuccess) {
2256
0
        goto loser;
2257
0
    }
2258
2259
    /* enc len is fixed 32B for X25519. */
2260
1.57k
    rv = sslBuffer_AppendVariable(&greaseBuf, &rawData->data[2], 32, 2);
2261
1.57k
    if (rv != SECSuccess) {
2262
0
        goto loser;
2263
0
    }
2264
2265
1.57k
    rv = sslBuffer_AppendVariable(&greaseBuf, &rawData->data[kNonPayloadLen], payloadLen, 2);
2266
1.57k
    if (rv != SECSuccess) {
2267
0
        goto loser;
2268
0
    }
2269
2270
    /* Mark ECH as advertised so that we can validate any response.
2271
     * We'll use echHpkeCtx to determine if we sent real or GREASE ECH. */
2272
1.57k
    rv = ssl3_EmplaceExtension(ss, buf, ssl_tls13_encrypted_client_hello_xtn,
2273
1.57k
                               greaseBuf.buf, greaseBuf.len, PR_TRUE);
2274
1.57k
    if (rv != SECSuccess) {
2275
0
        goto loser;
2276
0
    }
2277
2278
    /* Stash the GREASE ECH extension - in the case of HRR, CH2 must echo it. */
2279
1.57k
    PORT_Assert(ss->ssl3.hs.greaseEchBuf.len == 0);
2280
1.57k
    ss->ssl3.hs.greaseEchBuf = greaseBuf;
2281
2282
1.57k
    sslBuffer_Clear(&chInnerXtns);
2283
1.57k
    sslBuffer_Clear(&encodedCh);
2284
1.57k
    PK11_FreeSymKey(hmacPrk);
2285
1.57k
    PK11_FreeSymKey(derivedData);
2286
1.57k
    PK11_FreeSlot(slot);
2287
1.57k
    return SECSuccess;
2288
2289
0
loser:
2290
0
    sslBuffer_Clear(&chInnerXtns);
2291
0
    sslBuffer_Clear(&encodedCh);
2292
0
    PK11_FreeSymKey(hmacPrk);
2293
0
    PK11_FreeSymKey(derivedData);
2294
0
    if (slot) {
2295
0
        PK11_FreeSlot(slot);
2296
0
    }
2297
0
    return SECFailure;
2298
1.57k
}
2299
2300
/*
2301
 * Logs ECH Secret for sslSocket into sslkeylogfile.
2302
 *
2303
 * Called from tls13_SetupClientHello and tls13_MaybeHandleEch.
2304
 *
2305
 * This function is simply a debugging aid and therefore does not return a
2306
 * SECStatus.
2307
 */
2308
void
2309
tls13_EchKeyLog(sslSocket *ss)
2310
14.0k
{
2311
14.0k
#ifdef NSS_ALLOW_SSLKEYLOGFILE
2312
14.0k
    PK11SymKey *shared_secret;
2313
14.0k
    HpkeContext *cx;
2314
14.0k
    sslEchConfig *cfg = NULL;
2315
2316
14.0k
    cx = ss->ssl3.hs.echHpkeCtx;
2317
14.0k
    if (cx && !PR_CLIST_IS_EMPTY(&ss->echConfigs)) {
2318
3.42k
        shared_secret = PK11_HPKE_GetSharedSecret(cx);
2319
3.42k
        if (shared_secret) {
2320
3.42k
            cfg = (sslEchConfig *)PR_LIST_HEAD(&ss->echConfigs);
2321
3.42k
            ssl3_RecordKeyLog(ss, keylogLabelECHSecret, shared_secret);
2322
3.42k
            ssl3_WriteKeyLog(ss, keylogLabelECHConfig, &cfg->raw);
2323
3.42k
        }
2324
3.42k
    }
2325
14.0k
#endif
2326
14.0k
}
2327
2328
SECStatus
2329
tls13_MaybeHandleEch(sslSocket *ss, const PRUint8 *msg, PRUint32 msgLen, SECItem *sidBytes,
2330
                     SECItem *comps, SECItem *cookieBytes, SECItem *suites, SECItem **echInner)
2331
5.46k
{
2332
5.46k
    SECStatus rv;
2333
5.46k
    SECItem *tmpEchInner = NULL;
2334
5.46k
    PRUint8 *b;
2335
5.46k
    PRUint32 length;
2336
5.46k
    TLSExtension *echExtension;
2337
5.46k
    TLSExtension *versionExtension;
2338
5.46k
    PORT_Assert(!ss->ssl3.hs.echAccepted);
2339
5.46k
    SECItem tmpSid = { siBuffer, NULL, 0 };
2340
5.46k
    SECItem tmpCookie = { siBuffer, NULL, 0 };
2341
5.46k
    SECItem tmpSuites = { siBuffer, NULL, 0 };
2342
5.46k
    SECItem tmpComps = { siBuffer, NULL, 0 };
2343
2344
5.46k
    echExtension = ssl3_FindExtension(ss, ssl_tls13_encrypted_client_hello_xtn);
2345
5.46k
    if (echExtension) {
2346
260
        rv = tls13_ServerHandleOuterEchXtn(ss, &ss->xtnData, &echExtension->data);
2347
260
        if (rv != SECSuccess) {
2348
77
            goto loser; /* code set, alert sent. */
2349
77
        }
2350
183
        rv = tls13_MaybeAcceptEch(ss, sidBytes, msg, msgLen, &tmpEchInner);
2351
183
        if (rv != SECSuccess) {
2352
32
            goto loser; /* code set, alert sent. */
2353
32
        }
2354
183
    }
2355
5.35k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
2356
2357
5.35k
    if (ss->ssl3.hs.echAccepted) {
2358
0
        tls13_EchKeyLog(ss);
2359
0
        PORT_Assert(tmpEchInner);
2360
0
        PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.remoteExtensions));
2361
2362
        /* Start over on ECHInner */
2363
0
        b = tmpEchInner->data;
2364
0
        length = tmpEchInner->len;
2365
0
        rv = ssl3_HandleClientHelloPreamble(ss, &b, &length, &tmpSid,
2366
0
                                            &tmpCookie, &tmpSuites, &tmpComps);
2367
0
        if (rv != SECSuccess) {
2368
0
            goto loser; /* code set, alert sent. */
2369
0
        }
2370
2371
0
        versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
2372
0
        if (!versionExtension) {
2373
0
            FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, illegal_parameter);
2374
0
            goto loser;
2375
0
        }
2376
0
        rv = tls13_NegotiateVersion(ss, versionExtension);
2377
0
        if (rv != SECSuccess) {
2378
            /* code and alert set by tls13_NegotiateVersion */
2379
0
            goto loser;
2380
0
        }
2381
2382
0
        *comps = tmpComps;
2383
0
        *cookieBytes = tmpCookie;
2384
0
        *sidBytes = tmpSid;
2385
0
        *suites = tmpSuites;
2386
0
        *echInner = tmpEchInner;
2387
0
    }
2388
5.35k
    return SECSuccess;
2389
2390
109
loser:
2391
109
    SECITEM_FreeItem(tmpEchInner, PR_TRUE);
2392
109
    PORT_Assert(PORT_GetError() != 0);
2393
109
    return SECFailure;
2394
5.35k
}
2395
2396
SECStatus
2397
tls13_MaybeHandleEchSignal(sslSocket *ss, const PRUint8 *sh, PRUint32 shLen, PRBool isHrr)
2398
5.56k
{
2399
5.56k
    SECStatus rv;
2400
5.56k
    PRUint8 computed[TLS13_ECH_SIGNAL_LEN];
2401
5.56k
    const PRUint8 *signal;
2402
5.56k
    PORT_Assert(!ss->sec.isServer);
2403
2404
    /* If !echHpkeCtx, we either didn't advertise or sent GREASE ECH. */
2405
5.56k
    if (!ss->ssl3.hs.echHpkeCtx) {
2406
4.37k
        SSL_TRC(50, ("%d: TLS13[%d]: client only sent GREASE ECH",
2407
4.37k
                     SSL_GETPID(), ss->fd));
2408
4.37k
        ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
2409
4.37k
        return SECSuccess;
2410
4.37k
    }
2411
2412
1.19k
    PORT_Assert(!IS_DTLS(ss));
2413
2414
1.19k
    if (isHrr) {
2415
660
        if (ss->xtnData.ech) {
2416
7
            signal = ss->xtnData.ech->hrrConfirmation;
2417
653
        } else {
2418
653
            SSL_TRC(50, ("%d: TLS13[%d]: client did not receive ECH Xtn from Server HRR",
2419
653
                         SSL_GETPID(), ss->fd));
2420
653
            signal = NULL;
2421
653
            ss->ssl3.hs.echAccepted = PR_FALSE;
2422
653
            ss->ssl3.hs.echDecided = PR_TRUE;
2423
653
        }
2424
660
    } else {
2425
530
        signal = &ss->ssl3.hs.server_random[SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN];
2426
530
    }
2427
2428
1.19k
    PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn));
2429
2430
    /* Check ECH Confirmation for HRR ECH Xtn or ServerHello Random */
2431
1.19k
    if (signal) {
2432
537
        rv = tls13_ComputeEchSignal(ss, isHrr, sh, shLen, computed);
2433
537
        if (rv != SECSuccess) {
2434
0
            return SECFailure;
2435
0
        }
2436
537
        PRINT_BUF(100, (ss, "Server Signal", signal, TLS13_ECH_SIGNAL_LEN));
2437
537
        PRBool new_decision = !NSS_SecureMemcmp(computed, signal, TLS13_ECH_SIGNAL_LEN);
2438
        /* Server can't change its mind on whether to accept ECH */
2439
537
        if (ss->ssl3.hs.echDecided && new_decision != ss->ssl3.hs.echAccepted) {
2440
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
2441
0
            return SECFailure;
2442
0
        }
2443
537
        ss->ssl3.hs.echAccepted = new_decision;
2444
537
        ss->ssl3.hs.echDecided = PR_TRUE;
2445
537
    }
2446
2447
1.19k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
2448
1.19k
    if (ss->ssl3.hs.echAccepted) {
2449
0
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
2450
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
2451
0
            return SECFailure;
2452
0
        }
2453
        /* Server accepted, but sent an extension which was only advertised in the ClientHelloOuter */
2454
0
        if (ss->ssl3.hs.echInvalidExtension) {
2455
0
            (void)SSL3_SendAlert(ss, alert_fatal, unsupported_extension);
2456
0
            PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
2457
0
            return SECFailure;
2458
0
        }
2459
2460
        /* Swap the advertised lists as we've accepted ECH. */
2461
0
        PRUint16 *tempArray = ss->xtnData.advertised;
2462
0
        PRUint16 tempNum = ss->xtnData.numAdvertised;
2463
2464
0
        ss->xtnData.advertised = ss->xtnData.echAdvertised;
2465
0
        ss->xtnData.numAdvertised = ss->xtnData.echNumAdvertised;
2466
2467
0
        ss->xtnData.echAdvertised = tempArray;
2468
0
        ss->xtnData.echNumAdvertised = tempNum;
2469
2470
        /* |enc| must not be included in CH2.ClientECH. */
2471
0
        if (ss->ssl3.hs.helloRetry && ss->sec.isServer &&
2472
0
            ss->xtnData.ech->senderPubKey.len) {
2473
0
            ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
2474
0
            PORT_SetError(SSL_ERROR_BAD_2ND_CLIENT_HELLO);
2475
0
            return SECFailure;
2476
0
        }
2477
0
        ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_tls13_encrypted_client_hello_xtn;
2478
2479
        /* Only overwrite client_random with client_inner_random if CHInner was
2480
         *  succesfully used for handshake (NOT if HRR is received). */
2481
0
        if (!isHrr) {
2482
0
            PORT_Memcpy(ss->ssl3.hs.client_random, ss->ssl3.hs.client_inner_random, SSL3_RANDOM_LENGTH);
2483
0
        }
2484
0
    }
2485
    /* If rejected, leave echHpkeCtx and echPublicName for rejection paths. */
2486
1.19k
    ssl3_CoalesceEchHandshakeHashes(ss);
2487
1.19k
    SSL_TRC(3, ("%d: TLS13[%d]: ECH %s accepted by server",
2488
1.19k
                SSL_GETPID(), ss->fd, ss->ssl3.hs.echAccepted ? "is" : "is not"));
2489
1.19k
    return SECSuccess;
2490
1.19k
}
2491
2492
static SECStatus
2493
tls13_UnencodeChInner(sslSocket *ss, const SECItem *sidBytes, SECItem **echInner)
2494
0
{
2495
0
    SECStatus rv;
2496
0
    sslReadBuffer outerExtensionsList;
2497
0
    sslReadBuffer tmpReadBuf;
2498
0
    sslBuffer unencodedChInner = SSL_BUFFER_EMPTY;
2499
0
    PRCList *outerCursor;
2500
0
    PRCList *innerCursor;
2501
0
    PRBool outerFound;
2502
0
    PRUint32 xtnsOffset;
2503
0
    PRUint64 tmp;
2504
0
    PRUint8 *tmpB;
2505
0
    PRUint32 tmpLength;
2506
0
    sslReader chReader = SSL_READER((*echInner)->data, (*echInner)->len);
2507
0
    PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.echOuterExtensions));
2508
0
    PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ssl3.hs.remoteExtensions));
2509
0
    TLSExtension *echExtension;
2510
0
    int error = SSL_ERROR_INTERNAL_ERROR_ALERT;
2511
0
    int errDesc = internal_error;
2512
2513
0
    PRINT_BUF(100, (ss, "ECH Inner", chReader.buf.buf, chReader.buf.len));
2514
2515
    /* unencodedChInner := preamble, tmpReadBuf := encoded extensions. */
2516
0
    rv = tls13_CopyChPreamble(ss, &chReader, sidBytes, &unencodedChInner, &tmpReadBuf);
2517
0
    if (rv != SECSuccess) {
2518
0
        goto loser; /* code set */
2519
0
    }
2520
2521
    /* Parse inner extensions into ss->ssl3.hs.remoteExtensions. */
2522
0
    tmpB = CONST_CAST(PRUint8, tmpReadBuf.buf);
2523
0
    rv = ssl3_ParseExtensions(ss, &tmpB, &tmpReadBuf.len);
2524
0
    if (rv != SECSuccess) {
2525
0
        goto loser; /* malformed, alert sent. */
2526
0
    }
2527
2528
0
    echExtension = ssl3_FindExtension(ss, ssl_tls13_encrypted_client_hello_xtn);
2529
0
    if (!echExtension) {
2530
0
        error = SSL_ERROR_MISSING_ECH_EXTENSION;
2531
0
        errDesc = illegal_parameter;
2532
0
        goto alert_loser; /* Must have an inner Extension */
2533
0
    }
2534
0
    rv = tls13_ServerHandleInnerEchXtn(ss, &ss->xtnData, &echExtension->data);
2535
0
    if (rv != SECSuccess) {
2536
0
        goto loser; /* code set, alert sent. */
2537
0
    }
2538
2539
    /* Exit early if there are no outer_extensions to decompress. */
2540
0
    if (!ssl3_FindExtension(ss, ssl_tls13_outer_extensions_xtn)) {
2541
0
        rv = sslBuffer_AppendVariable(&unencodedChInner, tmpReadBuf.buf, tmpReadBuf.len, 2);
2542
0
        if (rv != SECSuccess) {
2543
0
            goto loser;
2544
0
        }
2545
0
        sslBuffer_Clear(&unencodedChInner);
2546
0
        return SECSuccess;
2547
0
    }
2548
2549
    /* Save room for uncompressed length. */
2550
0
    rv = sslBuffer_Skip(&unencodedChInner, 2, &xtnsOffset);
2551
0
    if (rv != SECSuccess) {
2552
0
        goto loser;
2553
0
    }
2554
2555
    /* For each inner extension: If not outer_extensions, copy it to the output.
2556
     * Else if outer_extensions, iterate the compressed extension list and append
2557
     * each full extension as contained in CHOuter. Compressed extensions must be
2558
     * contiguous, so decompress at the point at which outer_extensions appears. */
2559
0
    for (innerCursor = PR_NEXT_LINK(&ss->ssl3.hs.remoteExtensions);
2560
0
         innerCursor != &ss->ssl3.hs.remoteExtensions;
2561
0
         innerCursor = PR_NEXT_LINK(innerCursor)) {
2562
0
        TLSExtension *innerExtension = (TLSExtension *)innerCursor;
2563
0
        if (innerExtension->type != ssl_tls13_outer_extensions_xtn) {
2564
0
            SSL_TRC(10, ("%d: SSL3[%d]: copying inner extension of type %d and size %d directly", SSL_GETPID(),
2565
0
                         ss->fd, innerExtension->type, innerExtension->data.len));
2566
0
            rv = sslBuffer_AppendNumber(&unencodedChInner,
2567
0
                                        innerExtension->type, 2);
2568
0
            if (rv != SECSuccess) {
2569
0
                goto loser;
2570
0
            }
2571
0
            rv = sslBuffer_AppendVariable(&unencodedChInner,
2572
0
                                          innerExtension->data.data,
2573
0
                                          innerExtension->data.len, 2);
2574
0
            if (rv != SECSuccess) {
2575
0
                goto loser;
2576
0
            }
2577
0
            continue;
2578
0
        }
2579
2580
        /* Decompress */
2581
0
        sslReader extensionRdr = SSL_READER(innerExtension->data.data,
2582
0
                                            innerExtension->data.len);
2583
0
        rv = sslRead_ReadVariable(&extensionRdr, 1, &outerExtensionsList);
2584
0
        if (rv != SECSuccess) {
2585
0
            SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions has invalid size.",
2586
0
                         SSL_GETPID(), ss->fd));
2587
0
            error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
2588
0
            errDesc = illegal_parameter;
2589
0
            goto alert_loser;
2590
0
        }
2591
0
        if (SSL_READER_REMAINING(&extensionRdr) || (outerExtensionsList.len % 2) != 0 || !outerExtensionsList.len) {
2592
0
            SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions has invalid size.",
2593
0
                         SSL_GETPID(), ss->fd));
2594
0
            error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
2595
0
            errDesc = illegal_parameter;
2596
0
            goto alert_loser;
2597
0
        }
2598
2599
0
        outerCursor = &ss->ssl3.hs.echOuterExtensions;
2600
0
        sslReader compressedTypes = SSL_READER(outerExtensionsList.buf, outerExtensionsList.len);
2601
0
        while (SSL_READER_REMAINING(&compressedTypes)) {
2602
0
            outerFound = PR_FALSE;
2603
0
            rv = sslRead_ReadNumber(&compressedTypes, 2, &tmp);
2604
0
            if (rv != SECSuccess) {
2605
0
                SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions has invalid contents.",
2606
0
                             SSL_GETPID(), ss->fd));
2607
0
                error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
2608
0
                errDesc = illegal_parameter;
2609
0
                goto alert_loser;
2610
0
            }
2611
0
            if (tmp == ssl_tls13_encrypted_client_hello_xtn ||
2612
0
                tmp == ssl_tls13_outer_extensions_xtn) {
2613
0
                SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions contains an invalid reference.",
2614
0
                             SSL_GETPID(), ss->fd));
2615
0
                error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
2616
0
                errDesc = illegal_parameter;
2617
0
                goto alert_loser;
2618
0
            }
2619
0
            do {
2620
0
                const TLSExtension *candidate = (TLSExtension *)outerCursor;
2621
                /* Advance the outerCursor, we never consider the same xtn twice. */
2622
0
                outerCursor = PR_NEXT_LINK(outerCursor);
2623
0
                if (candidate->type == tmp) {
2624
0
                    outerFound = PR_TRUE;
2625
0
                    SSL_TRC(100, ("%d: SSL3[%d]: Decompressing ECH Inner Extension of type %d",
2626
0
                                  SSL_GETPID(), ss->fd, tmp));
2627
0
                    rv = sslBuffer_AppendNumber(&unencodedChInner,
2628
0
                                                candidate->type, 2);
2629
0
                    if (rv != SECSuccess) {
2630
0
                        goto loser;
2631
0
                    }
2632
0
                    rv = sslBuffer_AppendVariable(&unencodedChInner,
2633
0
                                                  candidate->data.data,
2634
0
                                                  candidate->data.len, 2);
2635
0
                    if (rv != SECSuccess) {
2636
0
                        goto loser;
2637
0
                    }
2638
0
                    break;
2639
0
                }
2640
0
            } while (outerCursor != &ss->ssl3.hs.echOuterExtensions);
2641
0
            if (!outerFound) {
2642
0
                SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions has missing,"
2643
0
                             " out of order or duplicate references.",
2644
0
                             SSL_GETPID(), ss->fd));
2645
0
                error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
2646
0
                errDesc = illegal_parameter;
2647
0
                goto alert_loser;
2648
0
            }
2649
0
        }
2650
0
    }
2651
0
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.echOuterExtensions);
2652
0
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
2653
2654
    /* Correct the message and extensions sizes. */
2655
0
    rv = sslBuffer_InsertNumber(&unencodedChInner, xtnsOffset,
2656
0
                                unencodedChInner.len - xtnsOffset - 2, 2);
2657
0
    if (rv != SECSuccess) {
2658
0
        goto loser;
2659
0
    }
2660
2661
0
    tmpB = &unencodedChInner.buf[xtnsOffset];
2662
0
    tmpLength = unencodedChInner.len - xtnsOffset;
2663
0
    rv = ssl3_ConsumeHandshakeNumber64(ss, &tmp, 2, &tmpB, &tmpLength);
2664
0
    if (rv != SECSuccess || tmpLength != tmp) {
2665
0
        error = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
2666
0
        errDesc = internal_error;
2667
0
        goto alert_loser;
2668
0
    }
2669
2670
0
    rv = ssl3_ParseExtensions(ss, &tmpB, &tmpLength);
2671
0
    if (rv != SECSuccess) {
2672
0
        goto loser; /* Error set and alert already sent */
2673
0
    }
2674
2675
0
    SECITEM_FreeItem(*echInner, PR_FALSE);
2676
0
    (*echInner)->data = unencodedChInner.buf;
2677
0
    (*echInner)->len = unencodedChInner.len;
2678
0
    return SECSuccess;
2679
0
alert_loser:
2680
0
    FATAL_ERROR(ss, error, errDesc);
2681
0
loser:
2682
0
    sslBuffer_Clear(&unencodedChInner);
2683
0
    return SECFailure;
2684
0
}
2685
2686
SECStatus
2687
tls13_MaybeAcceptEch(sslSocket *ss, const SECItem *sidBytes, const PRUint8 *chOuter,
2688
                     unsigned int chOuterLen, SECItem **chInner)
2689
183
{
2690
183
    SECStatus rv;
2691
183
    SECItem outer = { siBuffer, CONST_CAST(PRUint8, chOuter), chOuterLen };
2692
183
    SECItem *decryptedChInner = NULL;
2693
183
    SECItem outerAAD = { siBuffer, NULL, 0 };
2694
183
    SECItem cookieData = { siBuffer, NULL, 0 };
2695
183
    sslEchCookieData echData;
2696
183
    sslEchConfig *candidate = NULL; /* non-owning */
2697
183
    TLSExtension *hrrXtn;
2698
183
    PRBool previouslyOfferedEch;
2699
2700
183
    PORT_Assert(!ss->ssl3.hs.echAccepted);
2701
2702
183
    if (!ss->xtnData.ech || ss->xtnData.ech->receivedInnerXtn || IS_DTLS(ss)) {
2703
59
        ss->ssl3.hs.echDecided = PR_TRUE;
2704
59
        return SECSuccess;
2705
59
    }
2706
2707
124
    PORT_Assert(ss->xtnData.ech->innerCh.data);
2708
2709
124
    if (ss->ssl3.hs.helloRetry) {
2710
102
        ss->ssl3.hs.echDecided = PR_TRUE;
2711
102
        PORT_Assert(!ss->ssl3.hs.echHpkeCtx);
2712
2713
102
        hrrXtn = ssl3_FindExtension(ss, ssl_tls13_cookie_xtn);
2714
102
        if (!hrrXtn) {
2715
            /* If the client doesn't echo cookie, we can't decrypt. */
2716
5
            return SECSuccess;
2717
5
        }
2718
2719
97
        PRUint8 *tmp = hrrXtn->data.data;
2720
97
        PRUint32 len = hrrXtn->data.len;
2721
97
        rv = ssl3_ExtConsumeHandshakeVariable(ss, &cookieData, 2,
2722
97
                                              &tmp, &len);
2723
97
        if (rv != SECSuccess) {
2724
2
            return SECFailure;
2725
2
        }
2726
2727
        /* Extract ECH info without restoring hash state. If there's
2728
         * something wrong with the cookie, continue without ECH
2729
         * and let HRR code handle the problem. */
2730
95
        rv = tls13_HandleHrrCookie(ss, cookieData.data, cookieData.len,
2731
95
                                   NULL, NULL, &previouslyOfferedEch, &echData, PR_FALSE);
2732
95
        if (rv != SECSuccess) {
2733
60
            return SECSuccess;
2734
60
        }
2735
2736
35
        ss->ssl3.hs.echHpkeCtx = echData.hpkeCtx;
2737
2738
35
        const PRUint8 greaseConstant[TLS13_ECH_SIGNAL_LEN] = { 0 };
2739
35
        PRBool signal = previouslyOfferedEch &&
2740
18
                        !NSS_SecureMemcmp(greaseConstant, echData.signal, TLS13_ECH_SIGNAL_LEN);
2741
2742
35
        if (echData.configId != ss->xtnData.ech->configId ||
2743
30
            echData.kdfId != ss->xtnData.ech->kdfId ||
2744
30
            echData.aeadId != ss->xtnData.ech->aeadId) {
2745
30
            FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
2746
30
                        illegal_parameter);
2747
30
            return SECFailure;
2748
30
        }
2749
2750
5
        if (!ss->ssl3.hs.echHpkeCtx) {
2751
5
            return SECSuccess;
2752
5
        }
2753
0
        ss->ssl3.hs.echAccepted = signal;
2754
0
    }
2755
2756
22
    if (ss->ssl3.hs.echDecided && !ss->ssl3.hs.echAccepted) {
2757
        /* We don't change our mind */
2758
0
        return SECSuccess;
2759
0
    }
2760
    /* Regardless of where we return, the outcome is decided */
2761
22
    ss->ssl3.hs.echDecided = PR_TRUE;
2762
2763
    /* Cookie data was good, proceed with ECH. */
2764
22
    rv = tls13_GetMatchingEchConfigs(ss, ss->xtnData.ech->kdfId, ss->xtnData.ech->aeadId,
2765
22
                                     ss->xtnData.ech->configId, candidate, &candidate);
2766
22
    if (rv != SECSuccess) {
2767
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2768
0
        return SECFailure;
2769
0
    }
2770
2771
22
    if (candidate) {
2772
0
        rv = tls13_ServerMakeChOuterAAD(ss, chOuter, chOuterLen, &outerAAD);
2773
0
        if (rv != SECSuccess) {
2774
0
            return SECFailure;
2775
0
        }
2776
0
    }
2777
2778
22
    while (candidate) {
2779
0
        rv = tls13_OpenClientHelloInner(ss, &outer, &outerAAD, candidate, &decryptedChInner);
2780
0
        if (rv != SECSuccess) {
2781
            /* Get the next matching config */
2782
0
            rv = tls13_GetMatchingEchConfigs(ss, ss->xtnData.ech->kdfId, ss->xtnData.ech->aeadId,
2783
0
                                             ss->xtnData.ech->configId, candidate, &candidate);
2784
0
            if (rv != SECSuccess) {
2785
0
                FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2786
0
                SECITEM_FreeItem(&outerAAD, PR_FALSE);
2787
0
                return SECFailure;
2788
0
            }
2789
0
            continue;
2790
0
        }
2791
0
        break;
2792
0
    }
2793
22
    SECITEM_FreeItem(&outerAAD, PR_FALSE);
2794
2795
22
    if (rv != SECSuccess || !decryptedChInner) {
2796
22
        if (ss->ssl3.hs.helloRetry) {
2797
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ECH_EXTENSION, decrypt_error);
2798
0
            return SECFailure;
2799
22
        } else {
2800
            /* Send retry_configs (if we have any) when we fail to decrypt or
2801
             * found no candidates. This does *not* count as negotiating ECH. */
2802
22
            return ssl3_RegisterExtensionSender(ss, &ss->xtnData,
2803
22
                                                ssl_tls13_encrypted_client_hello_xtn,
2804
22
                                                tls13_ServerSendEchXtn);
2805
22
        }
2806
22
    }
2807
2808
0
    SSL_TRC(20, ("%d: TLS13[%d]: Successfully opened ECH inner CH",
2809
0
                 SSL_GETPID(), ss->fd));
2810
0
    PRINT_BUF(50, (ss, "Compressed CHInner", decryptedChInner->data,
2811
0
                   decryptedChInner->len));
2812
2813
0
    ss->ssl3.hs.echAccepted = PR_TRUE;
2814
2815
    /* Stash the CHOuter extensions. They're not yet handled (only parsed). If
2816
     * the CHInner contains outer_extensions_xtn, we'll need to reference them. */
2817
0
    ssl3_MoveRemoteExtensions(&ss->ssl3.hs.echOuterExtensions, &ss->ssl3.hs.remoteExtensions);
2818
2819
0
    rv = tls13_UnencodeChInner(ss, sidBytes, &decryptedChInner);
2820
0
    if (rv != SECSuccess) {
2821
0
        SECITEM_FreeItem(decryptedChInner, PR_TRUE);
2822
0
        return SECFailure; /* code set */
2823
0
    }
2824
0
    PRINT_BUF(50, (ss, "Uncompressed CHInner", decryptedChInner->data,
2825
0
                   decryptedChInner->len));
2826
0
    *chInner = decryptedChInner;
2827
0
    return SECSuccess;
2828
0
}
2829
2830
SECStatus
2831
tls13_WriteServerEchSignal(sslSocket *ss, PRUint8 *sh, unsigned int shLen)
2832
16
{
2833
16
    SECStatus rv;
2834
16
    PRUint8 signal[TLS13_ECH_SIGNAL_LEN];
2835
16
    PRUint8 *msg_random = &sh[sizeof(SSL3ProtocolVersion)];
2836
2837
16
    PORT_Assert(shLen > sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH);
2838
16
    PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
2839
2840
16
    rv = tls13_ComputeEchSignal(ss, PR_FALSE, sh, shLen, signal);
2841
16
    if (rv != SECSuccess) {
2842
0
        return SECFailure;
2843
0
    }
2844
16
    PRUint8 *dest = &msg_random[SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN];
2845
16
    PORT_Memcpy(dest, signal, TLS13_ECH_SIGNAL_LEN);
2846
2847
    /* Keep the socket copy consistent. */
2848
16
    PORT_Assert(0 == memcmp(msg_random, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN));
2849
16
    dest = &ss->ssl3.hs.server_random[SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN];
2850
16
    PORT_Memcpy(dest, signal, TLS13_ECH_SIGNAL_LEN);
2851
2852
16
    return SECSuccess;
2853
16
}
2854
2855
SECStatus
2856
tls13_WriteServerEchHrrSignal(sslSocket *ss, PRUint8 *sh, unsigned int shLen)
2857
20
{
2858
20
    SECStatus rv;
2859
20
    PR_ASSERT(shLen >= 4 + TLS13_ECH_SIGNAL_LEN);
2860
    /* We put the HRR ECH extension last. */
2861
20
    PRUint8 *placeholder_location = sh + shLen - TLS13_ECH_SIGNAL_LEN;
2862
    /* Defensive check that we are overwriting the contents of the right extension */
2863
20
    PR_ASSERT(tls13_Debug_CheckXtnBegins(placeholder_location - 4, ssl_tls13_encrypted_client_hello_xtn));
2864
    /* Calculate signal and overwrite */
2865
20
    rv = tls13_ComputeEchSignal(ss, PR_TRUE, sh, shLen, placeholder_location);
2866
20
    if (rv != SECSuccess) {
2867
0
        return SECFailure;
2868
0
    }
2869
    /* Free HRR GREASE/accept_confirmation value, it MUST be restored from
2870
     * cookie when handling CH2 after HRR. */
2871
20
    sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
2872
20
    return SECSuccess;
2873
20
}