Coverage Report

Created: 2025-04-22 06:18

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