Coverage Report

Created: 2025-07-01 06:26

/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
28
{
37
28
#ifdef DEBUG
38
28
    SECStatus rv;
39
28
    sslReader ext_reader = SSL_READER(start, 2);
40
28
    PRUint64 extension_number;
41
28
    rv = sslRead_ReadNumber(&ext_reader, 2, &extension_number);
42
28
    return ((rv == SECSuccess) && (extension_number == xtnType));
43
#else
44
    return PR_TRUE;
45
#endif
46
28
}
47
48
void
49
tls13_DestroyEchConfig(sslEchConfig *config)
50
3.50k
{
51
3.50k
    if (!config) {
52
0
        return;
53
0
    }
54
3.50k
    SECITEM_FreeItem(&config->contents.publicKey, PR_FALSE);
55
3.50k
    SECITEM_FreeItem(&config->contents.suites, PR_FALSE);
56
3.50k
    SECITEM_FreeItem(&config->raw, PR_FALSE);
57
3.50k
    PORT_Free(config->contents.publicName);
58
3.50k
    config->contents.publicName = NULL;
59
3.50k
    PORT_ZFree(config, sizeof(*config));
60
3.50k
}
61
62
void
63
tls13_DestroyEchConfigs(PRCList *list)
64
34.2k
{
65
34.2k
    PRCList *cur_p;
66
37.8k
    while (!PR_CLIST_IS_EMPTY(list)) {
67
3.50k
        cur_p = PR_LIST_TAIL(list);
68
3.50k
        PR_REMOVE_LINK(cur_p);
69
3.50k
        tls13_DestroyEchConfig((sslEchConfig *)cur_p);
70
3.50k
    }
71
34.2k
}
72
73
void
74
tls13_DestroyEchXtnState(sslEchXtnState *state)
75
183k
{
76
183k
    if (!state) {
77
183k
        return;
78
183k
    }
79
183
    SECITEM_FreeItem(&state->innerCh, PR_FALSE);
80
183
    SECITEM_FreeItem(&state->senderPubKey, PR_FALSE);
81
183
    SECITEM_FreeItem(&state->retryConfigs, PR_FALSE);
82
183
    PORT_ZFree(state, sizeof(*state));
83
183
}
84
85
SECStatus
86
tls13_CopyEchConfigs(PRCList *oConfigs, PRCList *configs)
87
23.7k
{
88
23.7k
    SECStatus rv;
89
23.7k
    sslEchConfig *config;
90
23.7k
    sslEchConfig *newConfig = NULL;
91
92
23.7k
    for (PRCList *cur_p = PR_LIST_HEAD(oConfigs);
93
23.7k
         cur_p != oConfigs;
94
23.7k
         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
23.7k
    return SECSuccess;
128
129
0
loser:
130
0
    tls13_DestroyEchConfig(newConfig);
131
0
    tls13_DestroyEchConfigs(configs);
132
0
    return SECFailure;
133
23.7k
}
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
3.50k
{
167
3.50k
    SECStatus rv;
168
3.50k
    sslEchConfigContents contents = { 0 };
169
3.50k
    sslEchConfig *decodedConfig;
170
3.50k
    PRUint64 tmpn;
171
3.50k
    PRUint64 tmpn2;
172
3.50k
    sslReadBuffer tmpBuf;
173
3.50k
    PRUint16 *extensionTypes = NULL;
174
3.50k
    unsigned int extensionIndex = 0;
175
3.50k
    sslReader configReader = SSL_READER(rawConfig->buf, rawConfig->len);
176
3.50k
    sslReader suiteReader;
177
3.50k
    sslReader extensionReader;
178
3.50k
    PRBool hasValidSuite = PR_FALSE;
179
3.50k
    PRBool unsupportedMandatoryXtn = PR_FALSE;
180
181
    /* HpkeKeyConfig key_config */
182
    /* uint8 config_id */
183
3.50k
    rv = sslRead_ReadNumber(&configReader, 1, &tmpn);
184
3.50k
    if (rv != SECSuccess) {
185
0
        goto loser;
186
0
    }
187
3.50k
    contents.configId = tmpn;
188
189
    /* HpkeKemId kem_id */
190
3.50k
    rv = sslRead_ReadNumber(&configReader, 2, &tmpn);
191
3.50k
    if (rv != SECSuccess) {
192
0
        goto loser;
193
0
    }
194
3.50k
    contents.kemId = tmpn;
195
196
    /* HpkePublicKey public_key */
197
3.50k
    rv = sslRead_ReadVariable(&configReader, 2, &tmpBuf);
198
3.50k
    if (rv != SECSuccess) {
199
0
        goto loser;
200
0
    }
201
3.50k
    rv = SECITEM_MakeItem(NULL, &contents.publicKey, (PRUint8 *)tmpBuf.buf, tmpBuf.len);
202
3.50k
    if (rv != SECSuccess) {
203
0
        goto loser;
204
0
    }
205
206
    /* HpkeSymmetricCipherSuite cipher_suites<4..2^16-4> */
207
3.50k
    rv = sslRead_ReadVariable(&configReader, 2, &tmpBuf);
208
3.50k
    if (rv != SECSuccess) {
209
0
        goto loser;
210
0
    }
211
3.50k
    if (tmpBuf.len & 1) {
212
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_CONFIG);
213
0
        goto loser;
214
0
    }
215
3.50k
    suiteReader = (sslReader)SSL_READER(tmpBuf.buf, tmpBuf.len);
216
3.50k
    while (SSL_READER_REMAINING(&suiteReader)) {
217
        /* HpkeKdfId kdf_id */
218
3.50k
        rv = sslRead_ReadNumber(&suiteReader, 2, &tmpn);
219
3.50k
        if (rv != SECSuccess) {
220
0
            goto loser;
221
0
        }
222
        /* HpkeAeadId aead_id */
223
3.50k
        rv = sslRead_ReadNumber(&suiteReader, 2, &tmpn2);
224
3.50k
        if (rv != SECSuccess) {
225
0
            goto loser;
226
0
        }
227
3.50k
        if (!hasValidSuite) {
228
            /* Use the first compatible ciphersuite. */
229
3.50k
            rv = PK11_HPKE_ValidateParameters(contents.kemId, tmpn, tmpn2);
230
3.50k
            if (rv == SECSuccess) {
231
3.50k
                hasValidSuite = PR_TRUE;
232
3.50k
                contents.kdfId = tmpn;
233
3.50k
                contents.aeadId = tmpn2;
234
3.50k
                break;
235
3.50k
            }
236
3.50k
        }
237
3.50k
    }
238
239
3.50k
    rv = SECITEM_MakeItem(NULL, &contents.suites, (PRUint8 *)tmpBuf.buf, tmpBuf.len);
240
3.50k
    if (rv != SECSuccess) {
241
0
        goto loser;
242
0
    }
243
244
    /* uint8 maximum_name_length */
245
3.50k
    rv = sslRead_ReadNumber(&configReader, 1, &tmpn);
246
3.50k
    if (rv != SECSuccess) {
247
0
        goto loser;
248
0
    }
249
3.50k
    contents.maxNameLen = (PRUint8)tmpn;
250
251
    /* opaque public_name<1..2^16-1> */
252
3.50k
    rv = sslRead_ReadVariable(&configReader, 1, &tmpBuf);
253
3.50k
    if (rv != SECSuccess) {
254
0
        goto loser;
255
0
    }
256
257
3.50k
    if (tmpBuf.len == 0) {
258
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_CONFIG);
259
0
        goto loser;
260
0
    }
261
3.50k
    if (!tls13_IsLDH(tmpBuf.buf, tmpBuf.len) ||
262
3.50k
        tls13_IsIp(tmpBuf.buf, tmpBuf.len)) {
263
0
        PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_CONFIG);
264
0
        goto loser;
265
0
    }
266
267
3.50k
    contents.publicName = PORT_ZAlloc(tmpBuf.len + 1);
268
3.50k
    if (!contents.publicName) {
269
0
        goto loser;
270
0
    }
271
3.50k
    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
3.50k
    rv = sslRead_ReadVariable(&configReader, 2, &tmpBuf);
276
3.50k
    if (rv != SECSuccess) {
277
0
        goto loser;
278
0
    }
279
280
3.50k
    extensionReader = (sslReader)SSL_READER(tmpBuf.buf, tmpBuf.len);
281
3.50k
    extensionTypes = PORT_NewArray(PRUint16, tmpBuf.len / 2 * sizeof(PRUint16));
282
3.50k
    if (!extensionTypes) {
283
0
        goto loser;
284
0
    }
285
286
3.50k
    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
3.50k
    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
3.50k
    if (hasValidSuite && !unsupportedMandatoryXtn) {
326
3.50k
        decodedConfig = PORT_ZNew(sslEchConfig);
327
3.50k
        if (!decodedConfig) {
328
0
            goto loser;
329
0
        }
330
3.50k
        decodedConfig->contents = contents;
331
3.50k
        *outConfig = decodedConfig;
332
3.50k
    } 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
3.50k
    PORT_Free(extensionTypes);
338
3.50k
    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
3.50k
}
347
348
/* Decode an ECHConfigList struct and store each ECHConfig
349
 * into |configs|.  */
350
SECStatus
351
tls13_DecodeEchConfigs(const SECItem *data, PRCList *configs)
352
3.50k
{
353
3.50k
    SECStatus rv;
354
3.50k
    sslEchConfig *decodedConfig = NULL;
355
3.50k
    sslReader rdr = SSL_READER(data->data, data->len);
356
3.50k
    sslReadBuffer tmp;
357
3.50k
    sslReadBuffer singleConfig;
358
3.50k
    PRUint64 version;
359
3.50k
    PRUint64 length;
360
3.50k
    PORT_Assert(PR_CLIST_IS_EMPTY(configs));
361
362
3.50k
    rv = sslRead_ReadVariable(&rdr, 2, &tmp);
363
3.50k
    if (rv != SECSuccess) {
364
0
        return SECFailure;
365
0
    }
366
3.50k
    SSL_TRC(100, ("Read EchConfig list of size %u", SSL_READER_REMAINING(&rdr)));
367
3.50k
    if (SSL_READER_REMAINING(&rdr)) {
368
0
        PORT_SetError(SEC_ERROR_BAD_DATA);
369
0
        return SECFailure;
370
0
    }
371
372
3.50k
    sslReader configsReader = SSL_READER(tmp.buf, tmp.len);
373
374
3.50k
    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
7.00k
    while (SSL_READER_REMAINING(&configsReader)) {
381
3.50k
        singleConfig.buf = SSL_READER_CURRENT(&configsReader);
382
        /* uint16 version */
383
3.50k
        rv = sslRead_ReadNumber(&configsReader, 2, &version);
384
3.50k
        if (rv != SECSuccess) {
385
0
            goto loser;
386
0
        }
387
        /* uint16 length */
388
3.50k
        rv = sslRead_ReadNumber(&configsReader, 2, &length);
389
3.50k
        if (rv != SECSuccess) {
390
0
            goto loser;
391
0
        }
392
3.50k
        singleConfig.len = 4 + length;
393
394
3.50k
        rv = sslRead_Read(&configsReader, length, &tmp);
395
3.50k
        if (rv != SECSuccess) {
396
0
            goto loser;
397
0
        }
398
399
3.50k
        if (version == TLS13_ECH_VERSION) {
400
3.50k
            rv = tls13_DecodeEchConfigContents(&tmp, &decodedConfig);
401
3.50k
            if (rv != SECSuccess) {
402
0
                goto loser; /* code set */
403
0
            }
404
405
3.50k
            if (decodedConfig) {
406
3.50k
                decodedConfig->version = version;
407
3.50k
                rv = SECITEM_MakeItem(NULL, &decodedConfig->raw, singleConfig.buf,
408
3.50k
                                      singleConfig.len);
409
3.50k
                if (rv != SECSuccess) {
410
0
                    goto loser;
411
0
                }
412
413
3.50k
                PR_APPEND_LINK(&decodedConfig->link, configs);
414
3.50k
                decodedConfig = NULL;
415
3.50k
            }
416
3.50k
        }
417
3.50k
    }
418
3.50k
    return SECSuccess;
419
420
0
loser:
421
0
    tls13_DestroyEchConfigs(configs);
422
0
    return SECFailure;
423
3.50k
}
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
3.50k
{
607
3.50k
    sslSocket *ss;
608
609
3.50k
    if (!fd) {
610
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
611
0
        return SECFailure;
612
0
    }
613
614
3.50k
    ss = ssl_FindSocket(fd);
615
3.50k
    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
3.50k
    SECKEY_DestroyPrivateKey(ss->echPrivKey);
623
3.50k
    ss->echPrivKey = NULL;
624
3.50k
    SECKEY_DestroyPublicKey(ss->echPubKey);
625
3.50k
    ss->echPubKey = NULL;
626
3.50k
    tls13_DestroyEchConfigs(&ss->echConfigs);
627
628
    /* Also remove any retry_configs and handshake context. */
629
3.50k
    if (ss->xtnData.ech && ss->xtnData.ech->retryConfigs.len) {
630
0
        SECITEM_FreeItem(&ss->xtnData.ech->retryConfigs, PR_FALSE);
631
0
    }
632
633
3.50k
    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
3.50k
    PORT_Free(CONST_CAST(char, ss->ssl3.hs.echPublicName));
638
3.50k
    ss->ssl3.hs.echPublicName = NULL;
639
640
3.50k
    return SECSuccess;
641
3.50k
}
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
3.50k
{
712
3.50k
    SECStatus rv;
713
3.50k
    sslSocket *ss;
714
3.50k
    SECItem data = { siBuffer, CONST_CAST(PRUint8, echConfigs), echConfigsLen };
715
716
3.50k
    if (!fd || !echConfigs || echConfigsLen == 0) {
717
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
718
0
        return SECFailure;
719
0
    }
720
721
3.50k
    ss = ssl_FindSocket(fd);
722
3.50k
    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
3.50k
    if (IS_DTLS(ss)) {
730
0
        return SECFailure;
731
0
    }
732
733
    /* Overwrite if we're already configured. */
734
3.50k
    rv = SSLExp_RemoveEchConfigs(fd);
735
3.50k
    if (rv != SECSuccess) {
736
0
        return SECFailure;
737
0
    }
738
739
3.50k
    rv = tls13_DecodeEchConfigs(&data, &ss->echConfigs);
740
3.50k
    if (rv != SECSuccess) {
741
0
        return SECFailure;
742
0
    }
743
3.50k
    if (PR_CLIST_IS_EMPTY(&ss->echConfigs)) {
744
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
745
0
        return SECFailure;
746
0
    }
747
748
3.50k
    return SECSuccess;
749
3.50k
}
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
69
{
756
69
    SECStatus rv;
757
69
    HpkeContext *cx = NULL;
758
69
    SECKEYPublicKey *pkR = NULL;
759
69
    SECItem hpkeInfo = { siBuffer, NULL, 0 };
760
69
    sslEchConfig *cfg = NULL;
761
762
69
    if (PR_CLIST_IS_EMPTY(&ss->echConfigs) ||
763
69
        !ssl_ShouldSendSNIExtension(ss, ss->url) ||
764
69
        IS_DTLS(ss)) {
765
35
        return SECSuccess;
766
35
    }
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
34
    cfg = (sslEchConfig *)PR_LIST_HEAD(&ss->echConfigs);
772
773
34
    SSL_TRC(50, ("%d: TLS13[%d]: Setup client ECH",
774
34
                 SSL_GETPID(), ss->fd));
775
776
34
    switch (type) {
777
34
        case client_hello_initial:
778
34
            PORT_Assert(!ss->ssl3.hs.echHpkeCtx && !ss->ssl3.hs.echPublicName);
779
34
            cx = PK11_HPKE_NewContext(cfg->contents.kemId, cfg->contents.kdfId,
780
34
                                      cfg->contents.aeadId, NULL, NULL);
781
34
            break;
782
0
        case client_hello_retry:
783
0
            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
0
            return SECSuccess;
789
0
        default:
790
0
            PORT_Assert(0);
791
0
            goto loser;
792
34
    }
793
34
    if (!cx) {
794
0
        goto loser;
795
0
    }
796
797
34
    rv = PK11_HPKE_Deserialize(cx, cfg->contents.publicKey.data, cfg->contents.publicKey.len, &pkR);
798
34
    if (rv != SECSuccess) {
799
0
        goto loser;
800
0
    }
801
802
34
    if (!SECITEM_AllocItem(NULL, &hpkeInfo, strlen(kHpkeInfoEch) + 1 + cfg->raw.len)) {
803
0
        goto loser;
804
0
    }
805
34
    PORT_Memcpy(&hpkeInfo.data[0], kHpkeInfoEch, strlen(kHpkeInfoEch));
806
34
    PORT_Memset(&hpkeInfo.data[strlen(kHpkeInfoEch)], 0, 1);
807
34
    PORT_Memcpy(&hpkeInfo.data[strlen(kHpkeInfoEch) + 1], cfg->raw.data, cfg->raw.len);
808
809
34
    PRINT_BUF(50, (ss, "Info", hpkeInfo.data, hpkeInfo.len));
810
811
    /* Setup with an ephemeral sender keypair. */
812
34
    rv = PK11_HPKE_SetupS(cx, NULL, NULL, pkR, &hpkeInfo);
813
34
    if (rv != SECSuccess) {
814
34
        goto loser;
815
34
    }
816
817
0
    rv = ssl3_GetNewRandom(ss->ssl3.hs.client_inner_random);
818
0
    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
0
    ss->ssl3.hs.echPublicName = PORT_Strdup(cfg->contents.publicName);
825
0
    if (!ss->ssl3.hs.echPublicName) {
826
0
        goto loser;
827
0
    }
828
829
0
    ss->ssl3.hs.echHpkeCtx = cx;
830
0
    SECKEY_DestroyPublicKey(pkR);
831
0
    SECITEM_FreeItem(&hpkeInfo, PR_FALSE);
832
0
    return SECSuccess;
833
834
34
loser:
835
34
    PK11_HPKE_DestroyContext(cx, PR_TRUE);
836
34
    SECKEY_DestroyPublicKey(pkR);
837
34
    SECITEM_FreeItem(&hpkeInfo, PR_FALSE);
838
34
    PORT_Assert(PORT_GetError() != 0);
839
34
    return SECFailure;
840
0
}
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
0
{
852
0
    SECStatus rv;
853
0
    SECItem chPt = { siBuffer, chInner->buf, chInner->len };
854
0
    SECItem *chCt = NULL;
855
856
0
    PRINT_BUF(50, (ss, "aad for ECH Encrypt", aadItem->data, aadItem->len));
857
0
    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
0
    if (rv != SECSuccess) {
862
0
        goto loser;
863
0
    }
864
0
    PRINT_BUF(50, (ss, "ciphertext from ECH Encrypt", chCt->data, chCt->len));
865
#else
866
    /* Fake a tag. */
867
0
    chCt = SECITEM_AllocItem(NULL, NULL, chPt.len + TLS13_ECH_AEAD_TAG_LEN);
868
0
    if (!chCt) {
869
0
        goto loser;
870
0
    }
871
0
    PORT_Memcpy(chCt->data, chPt.data, chPt.len);
872
0
#endif
873
874
0
#ifdef DEBUG
875
    /* When encrypting in-place, the payload is part of the AAD and must be zeroed. */
876
0
    PRUint8 val = 0;
877
0
    for (int i = 0; i < chCt->len; i++) {
878
0
        val |= *(echPayload + i);
879
0
    }
880
0
    PRINT_BUF(100, (ss, "Empty Placeholder for output of ECH Encryption", echPayload, chCt->len));
881
0
    PR_ASSERT(val == 0);
882
0
#endif
883
884
0
    PORT_Memcpy(echPayload, chCt->data, chCt->len);
885
0
    SECITEM_FreeItem(chCt, PR_TRUE);
886
0
    return SECSuccess;
887
888
0
loser:
889
0
    SECITEM_FreeItem(chCt, PR_TRUE);
890
0
    return SECFailure;
891
0
}
Unexecuted instantiation: tls13ech.c:tls13_EncryptClientHello
Unexecuted instantiation: tls13ech.c:tls13_EncryptClientHello
892
893
SECStatus
894
tls13_GetMatchingEchConfigs(const sslSocket *ss, HpkeKdfId kdf, HpkeAeadId aead,
895
                            const PRUint8 configId, const sslEchConfig *cur, sslEchConfig **next)
896
32
{
897
32
    SSL_TRC(50, ("%d: TLS13[%d]: GetMatchingEchConfig %d",
898
32
                 SSL_GETPID(), ss->fd, configId));
899
900
    /* If |cur|, resume the search at that node, else the list head. */
901
32
    for (PRCList *cur_p = cur ? ((PRCList *)cur)->next : PR_LIST_HEAD(&ss->echConfigs);
902
32
         cur_p != &ss->echConfigs;
903
32
         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
32
    *next = NULL;
914
32
    return SECSuccess;
915
32
}
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
0
{
1119
0
    SECStatus rv;
1120
0
    if (compressing && SSL_BUFFER_LEN(dupXtns) > 0) {
1121
0
        rv = sslBuffer_AppendNumber(chInnerXtns, ssl_tls13_outer_extensions_xtn, 2);
1122
0
        if (rv != SECSuccess) {
1123
0
            return SECFailure;
1124
0
        }
1125
0
        rv = sslBuffer_AppendNumber(chInnerXtns, dupXtns->len + 1, 2);
1126
0
        if (rv != SECSuccess) {
1127
0
            return SECFailure;
1128
0
        }
1129
0
        rv = sslBuffer_AppendBufferVariable(chInnerXtns, dupXtns, 1);
1130
0
        if (rv != SECSuccess) {
1131
0
            return SECFailure;
1132
0
        }
1133
0
    } else {
1134
        /* dupXtns carries whole extensions with lengths on each. */
1135
0
        rv = sslBuffer_AppendBuffer(chInnerXtns, dupXtns);
1136
0
        if (rv != SECSuccess) {
1137
0
            return SECFailure;
1138
0
        }
1139
0
    }
1140
0
    sslBuffer_Clear(dupXtns);
1141
0
    return SECSuccess;
1142
0
}
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
0
{
1164
0
    PRUint8 buf[1024] = { 0 };
1165
0
    const PRUint8 *p;
1166
0
    unsigned int len = 0;
1167
0
    PRBool willCompress;
1168
1169
0
    PORT_Assert(extensionType != ssl_tls13_encrypted_client_hello_xtn);
1170
0
    sslCustomExtensionHooks *hook = ss->opt.callExtensionWriterOnEchInner
1171
0
                                        ? ssl_FindCustomExtensionHooks(ss, extensionType)
1172
0
                                        : NULL;
1173
0
    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
0
    } else {
1196
        /* Non-custom extensions are duplicated when compressing. */
1197
0
        willCompress = PR_TRUE;
1198
0
        p = extensionData->buf;
1199
0
        len = extensionData->len;
1200
0
    }
1201
1202
    /* Duplicated extensions all need to go together. */
1203
0
    sslBuffer *dst = willCompress ? dupXtns : chInnerXtns;
1204
0
    SECStatus rv = sslBuffer_AppendNumber(dst, extensionType, 2);
1205
0
    if (rv != SECSuccess) {
1206
0
        return SECFailure;
1207
0
    }
1208
0
    if (!willCompress || !compressing) {
1209
0
        rv = sslBuffer_AppendVariable(dst, p, len, 2);
1210
0
        if (rv != SECSuccess) {
1211
0
            return SECFailure;
1212
0
        }
1213
0
    }
1214
    /* As this function is called twice, we only want to update our state the second time. */
1215
0
    if (compressing) {
1216
0
        ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = extensionType;
1217
0
        SSL_TRC(50, ("Appending extension=%d to the Client Hello Inner. Compressed?=%d", extensionType, willCompress));
1218
0
    }
1219
0
    return SECSuccess;
1220
0
}
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
0
{
1227
0
    if (!ss->opt.callExtensionWriterOnEchInner) {
1228
0
        return SECSuccess;
1229
0
    }
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
0
{
1274
0
    sslReader rdr = SSL_READER(buf, len);
1275
1276
    /* Read the length of identities. */
1277
0
    PRUint64 outerLen = 0;
1278
0
    SECStatus rv = sslRead_ReadNumber(&rdr, 2, &outerLen);
1279
0
    if (rv != SECSuccess) {
1280
0
        return SECFailure;
1281
0
    }
1282
0
    PORT_Assert(outerLen < len + 2);
1283
1284
    /* Read the length of PskIdentity.identity */
1285
0
    PRUint64 innerLen = 0;
1286
0
    rv = sslRead_ReadNumber(&rdr, 2, &innerLen);
1287
0
    if (rv != SECSuccess) {
1288
0
        return SECFailure;
1289
0
    }
1290
    /* identities should contain just one identity. */
1291
0
    PORT_Assert(outerLen == innerLen + 6);
1292
1293
    /* Randomize PskIdentity.{identity,obfuscated_ticket_age}. */
1294
0
    rv = PK11_GenerateRandom(buf + rdr.offset, innerLen + 4);
1295
0
    if (rv != SECSuccess) {
1296
0
        return SECFailure;
1297
0
    }
1298
0
    rdr.offset += innerLen + 4;
1299
1300
    /* Read the length of binders. */
1301
0
    rv = sslRead_ReadNumber(&rdr, 2, &outerLen);
1302
0
    if (rv != SECSuccess) {
1303
0
        return SECFailure;
1304
0
    }
1305
0
    PORT_Assert(outerLen + rdr.offset == len);
1306
1307
    /* Read the length of the binder. */
1308
0
    rv = sslRead_ReadNumber(&rdr, 1, &innerLen);
1309
0
    if (rv != SECSuccess) {
1310
0
        return SECFailure;
1311
0
    }
1312
    /* binders should contain just one binder. */
1313
0
    PORT_Assert(outerLen == innerLen + 1);
1314
1315
    /* Randomize the binder. */
1316
0
    rv = PK11_GenerateRandom(buf + rdr.offset, innerLen);
1317
0
    if (rv != SECSuccess) {
1318
0
        return SECFailure;
1319
0
    }
1320
1321
0
    return SECSuccess;
1322
0
}
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
0
{
1349
0
    SECStatus rv;
1350
0
    PRUint64 extensionType;
1351
0
    sslReadBuffer extensionData;
1352
0
    sslBuffer pskXtn = SSL_BUFFER_EMPTY;
1353
0
    sslBuffer dupXtns = SSL_BUFFER_EMPTY; /* Duplicated extensions, types-only if |compress|. */
1354
0
    unsigned int tmpOffset;
1355
0
    unsigned int tmpLen;
1356
0
    unsigned int srcXtnBase; /* To truncate CHOuter and remove the PSK extension. */
1357
1358
0
    PRUint16 called[MAX_EXTENSION_WRITERS] = { 0 }; /* For tracking which has been called. */
1359
0
    unsigned int nCalled = 0;
1360
1361
0
    SSL_TRC(50, ("%d: TLS13[%d]: Constructing ECH inner extensions %s compression",
1362
0
                 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
0
    rv = sslBuffer_AppendNumber(chInnerXtns, ssl_tls13_encrypted_client_hello_xtn, 2);
1368
0
    if (rv != SECSuccess) {
1369
0
        goto loser;
1370
0
    }
1371
0
    rv = sslBuffer_AppendNumber(chInnerXtns, 1, 2);
1372
0
    if (rv != SECSuccess) {
1373
0
        goto loser;
1374
0
    }
1375
0
    rv = sslBuffer_AppendNumber(chInnerXtns, ech_xtn_type_inner, 1);
1376
0
    if (rv != SECSuccess) {
1377
0
        goto loser;
1378
0
    }
1379
1380
0
    sslReader rdr = SSL_READER(chOuterXtnsBuf->buf, chOuterXtnsBuf->len);
1381
0
    while (SSL_READER_REMAINING(&rdr)) {
1382
0
        srcXtnBase = rdr.offset;
1383
0
        rv = sslRead_ReadNumber(&rdr, 2, &extensionType);
1384
0
        if (rv != SECSuccess) {
1385
0
            goto loser;
1386
0
        }
1387
1388
        /* Get the extension data. */
1389
0
        rv = sslRead_ReadVariable(&rdr, 2, &extensionData);
1390
0
        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
0
        SSLExtensionSupport sslSupported;
1399
0
        (void)SSLExp_GetExtensionSupport(extensionType, &sslSupported);
1400
0
        if (sslSupported != ssl_ext_none &&
1401
0
            tls13_ExtensionStatus(extensionType, ssl_hs_client_hello) == tls13_extension_unknown) {
1402
0
            continue;
1403
0
        }
1404
1405
0
        switch (extensionType) {
1406
0
            case ssl_server_name_xtn:
1407
                /* Write the real (private) SNI value. */
1408
0
                rv = sslBuffer_AppendNumber(chInnerXtns, extensionType, 2);
1409
0
                if (rv != SECSuccess) {
1410
0
                    goto loser;
1411
0
                }
1412
0
                rv = sslBuffer_Skip(chInnerXtns, 2, &tmpOffset);
1413
0
                if (rv != SECSuccess) {
1414
0
                    goto loser;
1415
0
                }
1416
0
                tmpLen = SSL_BUFFER_LEN(chInnerXtns);
1417
0
                rv = ssl3_ClientFormatServerNameXtn(ss, ss->url,
1418
0
                                                    strlen(ss->url),
1419
0
                                                    NULL, chInnerXtns);
1420
0
                if (rv != SECSuccess) {
1421
0
                    goto loser;
1422
0
                }
1423
0
                tmpLen = SSL_BUFFER_LEN(chInnerXtns) - tmpLen;
1424
0
                rv = sslBuffer_InsertNumber(chInnerXtns, tmpOffset, tmpLen, 2);
1425
0
                if (rv != SECSuccess) {
1426
0
                    goto loser;
1427
0
                }
1428
                /* Only update state on second invocation of this function */
1429
0
                if (shouldCompress) {
1430
0
                    ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = extensionType;
1431
0
                }
1432
0
                break;
1433
0
            case ssl_tls13_supported_versions_xtn:
1434
                /* Only TLS 1.3 and GREASE on CHInner. */
1435
0
                rv = sslBuffer_AppendNumber(chInnerXtns, extensionType, 2);
1436
0
                if (rv != SECSuccess) {
1437
0
                    goto loser;
1438
0
                }
1439
                /* Extension length. */
1440
0
                tmpLen = (ss->opt.enableGrease) ? 5 : 3;
1441
0
                rv = sslBuffer_AppendNumber(chInnerXtns, tmpLen, 2);
1442
0
                if (rv != SECSuccess) {
1443
0
                    goto loser;
1444
0
                }
1445
                /* ProtocolVersion length */
1446
0
                rv = sslBuffer_AppendNumber(chInnerXtns, tmpLen - 1, 1);
1447
0
                if (rv != SECSuccess) {
1448
0
                    goto loser;
1449
0
                }
1450
                /* ProtocolVersion TLS 1.3 */
1451
0
                rv = sslBuffer_AppendNumber(chInnerXtns, SSL_LIBRARY_VERSION_TLS_1_3, 2);
1452
0
                if (rv != SECSuccess) {
1453
0
                    goto loser;
1454
0
                }
1455
                /* ProtocolVersion GREASE */
1456
0
                if (ss->opt.enableGrease) {
1457
0
                    rv = sslBuffer_AppendNumber(chInnerXtns, ss->ssl3.hs.grease->idx[grease_version], 2);
1458
0
                    if (rv != SECSuccess) {
1459
0
                        goto loser;
1460
0
                    }
1461
0
                }
1462
                /* Only update state on second invocation of this function */
1463
0
                if (shouldCompress) {
1464
0
                    ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = extensionType;
1465
0
                }
1466
0
                break;
1467
0
            case ssl_tls13_pre_shared_key_xtn:
1468
0
                if (inOutPskXtn && !shouldCompress) {
1469
0
                    rv = sslBuffer_AppendNumber(&pskXtn, extensionType, 2);
1470
0
                    if (rv != SECSuccess) {
1471
0
                        goto loser;
1472
0
                    }
1473
0
                    rv = sslBuffer_AppendVariable(&pskXtn, extensionData.buf,
1474
0
                                                  extensionData.len, 2);
1475
0
                    if (rv != SECSuccess) {
1476
0
                        goto loser;
1477
0
                    }
1478
                    /* This should be the last extension. */
1479
0
                    PORT_Assert(srcXtnBase == ss->xtnData.lastXtnOffset);
1480
0
                    PORT_Assert(chOuterXtnsBuf->len - srcXtnBase == extensionData.len + 4);
1481
0
                    rv = tls13_RandomizePsk(chOuterXtnsBuf->buf + srcXtnBase + 4,
1482
0
                                            chOuterXtnsBuf->len - srcXtnBase - 4);
1483
0
                    if (rv != SECSuccess) {
1484
0
                        goto loser;
1485
0
                    }
1486
0
                } else if (!inOutPskXtn) {
1487
                    /* When GREASEing, only the length is used.
1488
                     * Order doesn't matter, so just copy the extension. */
1489
0
                    rv = sslBuffer_AppendNumber(chInnerXtns, extensionType, 2);
1490
0
                    if (rv != SECSuccess) {
1491
0
                        goto loser;
1492
0
                    }
1493
0
                    rv = sslBuffer_AppendVariable(chInnerXtns, extensionData.buf,
1494
0
                                                  extensionData.len, 2);
1495
0
                    if (rv != SECSuccess) {
1496
0
                        goto loser;
1497
0
                    }
1498
0
                }
1499
                /* Only update state on second invocation of this function */
1500
0
                if (shouldCompress) {
1501
0
                    ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = extensionType;
1502
0
                }
1503
0
                break;
1504
0
            default: {
1505
                /* This is a regular extension.  We can maybe compress these. */
1506
0
                rv = tls13_ChInnerAppendExtension(ss, extensionType,
1507
0
                                                  &extensionData,
1508
0
                                                  &dupXtns, chInnerXtns,
1509
0
                                                  shouldCompress,
1510
0
                                                  called, &nCalled);
1511
0
                if (rv != SECSuccess) {
1512
0
                    goto loser;
1513
0
                }
1514
0
                break;
1515
0
            }
1516
0
        }
1517
0
    }
1518
1519
0
    rv = tls13_WriteDupXtnsToChInner(shouldCompress, &dupXtns, chInnerXtns);
1520
0
    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
0
    rv = tls13_ChInnerAdditionalExtensionWriters(ss, called, nCalled, chInnerXtns);
1527
0
    if (rv != SECSuccess) {
1528
0
        goto loser;
1529
0
    }
1530
1531
0
    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
0
        if (shouldCompress) {
1536
0
            rv = sslBuffer_AppendBuffer(chInnerXtns, inOutPskXtn);
1537
0
        } else {
1538
0
            rv = sslBuffer_AppendBuffer(chInnerXtns, &pskXtn);
1539
0
            *inOutPskXtn = pskXtn;
1540
0
        }
1541
0
        if (rv != SECSuccess) {
1542
0
            goto loser;
1543
0
        }
1544
0
    }
1545
1546
0
    return SECSuccess;
1547
1548
0
loser:
1549
0
    sslBuffer_Clear(&pskXtn);
1550
0
    sslBuffer_Clear(&dupXtns);
1551
0
    return SECFailure;
1552
0
}
1553
1554
static SECStatus
1555
tls13_EncodeClientHelloInner(sslSocket *ss, const sslBuffer *chInner, const sslBuffer *chInnerXtns, sslBuffer *out)
1556
0
{
1557
0
    PORT_Assert(ss && chInner && chInnerXtns && out);
1558
0
    SECStatus rv;
1559
0
    sslReadBuffer tmpReadBuf;
1560
0
    sslReader chReader = SSL_READER(chInner->buf, chInner->len);
1561
1562
0
    rv = sslRead_Read(&chReader, 4, &tmpReadBuf);
1563
0
    if (rv != SECSuccess) {
1564
0
        goto loser;
1565
0
    }
1566
1567
0
    rv = sslRead_Read(&chReader, 2 + SSL3_RANDOM_LENGTH, &tmpReadBuf);
1568
0
    if (rv != SECSuccess) {
1569
0
        goto loser;
1570
0
    }
1571
0
    rv = sslBuffer_Append(out, tmpReadBuf.buf, tmpReadBuf.len);
1572
0
    if (rv != SECSuccess) {
1573
0
        goto loser;
1574
0
    }
1575
1576
    /* Skip the legacy_session_id */
1577
0
    rv = sslRead_ReadVariable(&chReader, 1, &tmpReadBuf);
1578
0
    if (rv != SECSuccess) {
1579
0
        goto loser;
1580
0
    }
1581
0
    rv = sslBuffer_AppendNumber(out, 0, 1);
1582
0
    if (rv != SECSuccess) {
1583
0
        goto loser;
1584
0
    }
1585
1586
    /* cipher suites */
1587
0
    rv = sslRead_ReadVariable(&chReader, 2, &tmpReadBuf);
1588
0
    if (rv != SECSuccess) {
1589
0
        goto loser;
1590
0
    }
1591
0
    rv = sslBuffer_AppendVariable(out, tmpReadBuf.buf, tmpReadBuf.len, 2);
1592
0
    if (rv != SECSuccess) {
1593
0
        goto loser;
1594
0
    }
1595
1596
    /* compression methods */
1597
0
    rv = sslRead_ReadVariable(&chReader, 1, &tmpReadBuf);
1598
0
    if (rv != SECSuccess) {
1599
0
        goto loser;
1600
0
    }
1601
0
    rv = sslBuffer_AppendVariable(out, tmpReadBuf.buf, tmpReadBuf.len, 1);
1602
0
    if (rv != SECSuccess) {
1603
0
        goto loser;
1604
0
    }
1605
1606
    /* Append the extensions. */
1607
0
    rv = sslBuffer_AppendBufferVariable(out, chInnerXtns, 2);
1608
0
    if (rv != SECSuccess) {
1609
0
        goto loser;
1610
0
    }
1611
0
    return SECSuccess;
1612
1613
0
loser:
1614
0
    sslBuffer_Clear(out);
1615
0
    return SECFailure;
1616
0
}
1617
1618
SECStatus
1619
tls13_PadChInner(sslBuffer *chInner, uint8_t maxNameLen, uint8_t serverNameLen)
1620
0
{
1621
0
    SECStatus rv;
1622
0
    PORT_Assert(chInner);
1623
0
    PORT_Assert(serverNameLen > 0);
1624
0
    static unsigned char padding[256 + 32] = { 0 };
1625
0
    int16_t name_padding = (int16_t)maxNameLen - (int16_t)serverNameLen;
1626
0
    if (name_padding < 0) {
1627
0
        name_padding = 0;
1628
0
    }
1629
0
    unsigned int rounding_padding = 31 - ((SSL_BUFFER_LEN(chInner) + name_padding) % 32);
1630
0
    unsigned int total_padding = name_padding + rounding_padding;
1631
0
    PORT_Assert(total_padding < sizeof(padding));
1632
0
    SSL_TRC(100, ("computed ECH Inner Client Hello padding of size %u", total_padding));
1633
0
    rv = sslBuffer_Append(chInner, padding, total_padding);
1634
0
    if (rv != SECSuccess) {
1635
0
        sslBuffer_Clear(chInner);
1636
0
        return SECFailure;
1637
0
    }
1638
0
    return SECSuccess;
1639
0
}
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
0
{
1665
0
    SECStatus rv;
1666
    /* Format the encrypted_client_hello extension. */
1667
0
    rv = sslBuffer_AppendNumber(echXtn, ech_xtn_type_outer, 1);
1668
0
    if (rv != SECSuccess) {
1669
0
        goto loser;
1670
0
    }
1671
0
    rv = sslBuffer_AppendNumber(echXtn, cfg->contents.kdfId, 2);
1672
0
    if (rv != SECSuccess) {
1673
0
        goto loser;
1674
0
    }
1675
0
    rv = sslBuffer_AppendNumber(echXtn, cfg->contents.aeadId, 2);
1676
0
    if (rv != SECSuccess) {
1677
0
        goto loser;
1678
0
    }
1679
1680
0
    rv = sslBuffer_AppendNumber(echXtn, cfg->contents.configId, 1);
1681
0
    if (rv != SECSuccess) {
1682
0
        goto loser;
1683
0
    }
1684
0
    if (hpkeEnc) {
1685
        /* Public Key */
1686
0
        rv = sslBuffer_AppendVariable(echXtn, hpkeEnc->data, hpkeEnc->len, 2);
1687
0
        if (rv != SECSuccess) {
1688
0
            goto loser;
1689
0
        }
1690
0
    } else {
1691
        /* |enc| is empty. */
1692
0
        rv = sslBuffer_AppendNumber(echXtn, 0, 2);
1693
0
        if (rv != SECSuccess) {
1694
0
            goto loser;
1695
0
        }
1696
0
    }
1697
0
    payloadLen += TLS13_ECH_AEAD_TAG_LEN;
1698
0
    rv = sslBuffer_AppendNumber(echXtn, payloadLen, 2);
1699
0
    if (rv != SECSuccess) {
1700
0
        goto loser;
1701
0
    }
1702
0
    *payloadOffset = echXtn->len;
1703
0
    rv = sslBuffer_Fill(echXtn, 0, payloadLen);
1704
0
    if (rv != SECSuccess) {
1705
0
        goto loser;
1706
0
    }
1707
0
    PRINT_BUF(100, (NULL, "ECH Xtn with Placeholder:", echXtn->buf, echXtn->len));
1708
0
    return SECSuccess;
1709
0
loser:
1710
0
    sslBuffer_Clear(echXtn);
1711
0
    return SECFailure;
1712
0
}
1713
1714
SECStatus
1715
tls13_ConstructClientHelloWithEch(sslSocket *ss, const sslSessionID *sid, PRBool freshSid,
1716
                                  sslBuffer *chOuter, sslBuffer *chOuterXtnsBuf)
1717
0
{
1718
0
    SECStatus rv;
1719
0
    sslBuffer chInner = SSL_BUFFER_EMPTY;
1720
0
    sslBuffer encodedChInner = SSL_BUFFER_EMPTY;
1721
0
    sslBuffer paddingChInner = SSL_BUFFER_EMPTY;
1722
0
    sslBuffer chInnerXtns = SSL_BUFFER_EMPTY;
1723
0
    sslBuffer pskXtn = SSL_BUFFER_EMPTY;
1724
0
    unsigned int preambleLen;
1725
1726
0
    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
0
    rv = tls13_ConstructInnerExtensionsFromOuter(ss, chOuterXtnsBuf, &chInnerXtns,
1731
0
                                                 &pskXtn, PR_FALSE);
1732
0
    if (rv != SECSuccess) {
1733
0
        goto loser; /* code set */
1734
0
    }
1735
1736
0
    rv = ssl3_CreateClientHelloPreamble(ss, sid, PR_FALSE, SSL_LIBRARY_VERSION_TLS_1_3,
1737
0
                                        PR_TRUE, &chInnerXtns, &chInner);
1738
0
    if (rv != SECSuccess) {
1739
0
        goto loser; /* code set */
1740
0
    }
1741
0
    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
0
    PORT_Assert(!IS_DTLS(ss));
1747
0
    rv = sslBuffer_InsertNumber(&chInner, 1,
1748
0
                                chInner.len + 2 + chInnerXtns.len - 4, 3);
1749
0
    if (rv != SECSuccess) {
1750
0
        goto loser;
1751
0
    }
1752
1753
0
    if (pskXtn.len) {
1754
0
        PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn));
1755
0
        rv = tls13_WriteExtensionsWithBinder(ss, &chInnerXtns, &chInner);
1756
        /* Update the stolen PSK extension with the binder value. */
1757
0
        PORT_Memcpy(pskXtn.buf, &chInnerXtns.buf[chInnerXtns.len - pskXtn.len], pskXtn.len);
1758
0
    } else {
1759
0
        rv = sslBuffer_AppendBufferVariable(&chInner, &chInnerXtns, 2);
1760
0
    }
1761
0
    if (rv != SECSuccess) {
1762
0
        goto loser;
1763
0
    }
1764
1765
0
    PRINT_BUF(50, (ss, "Uncompressed CHInner", chInner.buf, chInner.len));
1766
0
    rv = ssl3_UpdateHandshakeHashesInt(ss, chInner.buf, chInner.len,
1767
0
                                       &ss->ssl3.hs.echInnerMessages);
1768
0
    if (rv != SECSuccess) {
1769
0
        goto loser; /* code set */
1770
0
    }
1771
1772
    /* Un-append the extensions, then append compressed via Encoded. */
1773
0
    SSL_BUFFER_LEN(&chInner) = preambleLen;
1774
0
    sslBuffer_Clear(&chInnerXtns);
1775
0
    rv = tls13_ConstructInnerExtensionsFromOuter(ss, chOuterXtnsBuf,
1776
0
                                                 &chInnerXtns, &pskXtn, PR_TRUE);
1777
0
    if (rv != SECSuccess) {
1778
0
        goto loser;
1779
0
    }
1780
1781
0
    rv = tls13_EncodeClientHelloInner(ss, &chInner, &chInnerXtns, &encodedChInner);
1782
0
    if (rv != SECSuccess) {
1783
0
        goto loser;
1784
0
    }
1785
0
    PRINT_BUF(50, (ss, "Compressed CHInner", encodedChInner.buf, encodedChInner.len));
1786
1787
0
    PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->echConfigs));
1788
0
    sslEchConfig *cfg = (sslEchConfig *)PR_LIST_HEAD(&ss->echConfigs);
1789
1790
    /* We are using ECH so SNI must have been included */
1791
0
    rv = tls13_PadChInner(&encodedChInner, cfg->contents.maxNameLen, strlen(ss->url));
1792
0
    if (rv != SECSuccess) {
1793
0
        goto loser;
1794
0
    }
1795
1796
    /* Build the ECH Xtn with placeholder and put it in chOuterXtnsBuf */
1797
0
    sslBuffer echXtn = SSL_BUFFER_EMPTY;
1798
0
    const SECItem *hpkeEnc = NULL;
1799
0
    if (!ss->ssl3.hs.helloRetry) {
1800
0
        hpkeEnc = PK11_HPKE_GetEncapPubKey(ss->ssl3.hs.echHpkeCtx);
1801
0
        if (!hpkeEnc) {
1802
0
            FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
1803
0
            goto loser;
1804
0
        }
1805
0
    }
1806
0
    PRUint16 echXtnPayloadOffset; /* Offset from start of ECH Xtn to ECH Payload */
1807
0
    rv = tls13_BuildEchXtn(cfg, hpkeEnc, encodedChInner.len, &echXtnPayloadOffset, &echXtn);
1808
0
    if (rv != SECSuccess) {
1809
0
        goto loser;
1810
0
    }
1811
0
    ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = ssl_tls13_encrypted_client_hello_xtn;
1812
0
    rv = ssl3_EmplaceExtension(ss, chOuterXtnsBuf, ssl_tls13_encrypted_client_hello_xtn,
1813
0
                               echXtn.buf, echXtn.len, PR_TRUE);
1814
0
    if (rv != SECSuccess) {
1815
0
        goto loser;
1816
0
    }
1817
1818
    /* Add the padding */
1819
0
    rv = ssl_InsertPaddingExtension(ss, chOuter->len, chOuterXtnsBuf);
1820
0
    if (rv != SECSuccess) {
1821
0
        goto loser;
1822
0
    }
1823
1824
    /* Finish the CHO with the ECH Xtn payload zeroed */
1825
0
    rv = ssl3_InsertChHeaderSize(ss, chOuter, chOuterXtnsBuf);
1826
0
    if (rv != SECSuccess) {
1827
0
        goto loser;
1828
0
    }
1829
0
    unsigned int chOuterXtnsOffset = chOuter->len + 2; /* From Start of CHO to Extensions list */
1830
0
    rv = sslBuffer_AppendBufferVariable(chOuter, chOuterXtnsBuf, 2);
1831
0
    if (rv != SECSuccess) {
1832
0
        goto loser;
1833
0
    }
1834
1835
    /* AAD consists of entire CHO, minus the 4 byte handshake header */
1836
0
    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
0
    PRUint8 *echPayload = chOuter->buf + chOuterXtnsOffset + ss->xtnData.echXtnOffset + 4 + echXtnPayloadOffset;
1839
    /* Insert the encrypted_client_hello xtn and coalesce. */
1840
0
    rv = tls13_EncryptClientHello(ss, &aadItem, &encodedChInner, echPayload);
1841
0
    if (rv != SECSuccess) {
1842
0
        goto loser;
1843
0
    }
1844
1845
0
    sslBuffer_Clear(&echXtn);
1846
0
    sslBuffer_Clear(&chInner);
1847
0
    sslBuffer_Clear(&encodedChInner);
1848
0
    sslBuffer_Clear(&paddingChInner);
1849
0
    sslBuffer_Clear(&chInnerXtns);
1850
0
    sslBuffer_Clear(&pskXtn);
1851
0
    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
0
}
1862
1863
static SECStatus
1864
tls13_ComputeEchHelloRetryTranscript(sslSocket *ss, const PRUint8 *sh, unsigned int shLen, sslBuffer *out)
1865
14
{
1866
14
    SECStatus rv;
1867
14
    PRUint8 zeroedEchSignal[TLS13_ECH_SIGNAL_LEN] = { 0 };
1868
14
    sslBuffer *previousTranscript;
1869
1870
14
    if (ss->sec.isServer) {
1871
14
        previousTranscript = &(ss->ssl3.hs.messages);
1872
14
    } else {
1873
0
        previousTranscript = &(ss->ssl3.hs.echInnerMessages);
1874
0
    }
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
14
    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
14
        SSL3Hashes hashes;
1892
14
        rv = tls13_ComputeHash(ss, &hashes, previousTranscript->buf, previousTranscript->len, tls13_GetHash(ss));
1893
14
        if (rv != SECSuccess) {
1894
0
            goto loser;
1895
0
        }
1896
14
        rv = sslBuffer_AppendNumber(out, ssl_hs_message_hash, 1);
1897
14
        if (rv != SECSuccess) {
1898
0
            goto loser;
1899
0
        }
1900
14
        rv = sslBuffer_AppendNumber(out, hashes.len, 3);
1901
14
        if (rv != SECSuccess) {
1902
0
            goto loser;
1903
0
        }
1904
14
        rv = sslBuffer_Append(out, hashes.u.raw, hashes.len);
1905
14
        if (rv != SECSuccess) {
1906
0
            goto loser;
1907
0
        }
1908
14
    } 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
14
    PR_ASSERT(out->len == tls13_GetHashSize(ss) + 4);
1916
14
    PRINT_BUF(100, (ss, "ECH Client Hello Message Hash", out->buf, out->len));
1917
    /* Message Header */
1918
14
    rv = sslBuffer_AppendNumber(out, ssl_hs_server_hello, 1);
1919
14
    if (rv != SECSuccess) {
1920
0
        goto loser;
1921
0
    }
1922
    /* Message Size */
1923
14
    rv = sslBuffer_AppendNumber(out, shLen, 3);
1924
14
    if (rv != SECSuccess) {
1925
0
        goto loser;
1926
0
    }
1927
    /* Calculate where the HRR ECH Xtn Signal begins */
1928
14
    unsigned int absEchOffset;
1929
14
    if (ss->sec.isServer) {
1930
        /* We know the ECH HRR Xtn is last */
1931
14
        PORT_Assert(shLen >= TLS13_ECH_SIGNAL_LEN);
1932
14
        absEchOffset = shLen - TLS13_ECH_SIGNAL_LEN;
1933
14
    } 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
0
        PORT_Assert(ss->xtnData.ech->hrrConfirmation > sh);
1942
0
        PORT_Assert(ss->xtnData.ech->hrrConfirmation < sh + shLen);
1943
0
        absEchOffset = ss->xtnData.ech->hrrConfirmation - sh;
1944
0
    }
1945
14
    PR_ASSERT(tls13_Debug_CheckXtnBegins(sh + absEchOffset - 4, ssl_tls13_encrypted_client_hello_xtn));
1946
    /* The HRR up to the ECH Xtn signal */
1947
14
    rv = sslBuffer_Append(out, sh, absEchOffset);
1948
14
    if (rv != SECSuccess) {
1949
0
        goto loser;
1950
0
    }
1951
14
    rv = sslBuffer_Append(out, zeroedEchSignal, sizeof(zeroedEchSignal));
1952
14
    if (rv != SECSuccess) {
1953
0
        goto loser;
1954
0
    }
1955
14
    PR_ASSERT(absEchOffset + TLS13_ECH_SIGNAL_LEN <= shLen);
1956
    /* The remainder of the HRR */
1957
14
    rv = sslBuffer_Append(out, sh + absEchOffset + TLS13_ECH_SIGNAL_LEN, shLen - absEchOffset - TLS13_ECH_SIGNAL_LEN);
1958
14
    if (rv != SECSuccess) {
1959
0
        goto loser;
1960
0
    }
1961
14
    PR_ASSERT(out->len == tls13_GetHashSize(ss) + 4 + shLen + 4);
1962
14
    return SECSuccess;
1963
0
loser:
1964
0
    sslBuffer_Clear(out);
1965
0
    return SECFailure;
1966
14
}
1967
1968
static SECStatus
1969
tls13_ComputeEchServerHelloTranscript(sslSocket *ss, const PRUint8 *sh, unsigned int shLen, sslBuffer *out)
1970
13
{
1971
13
    SECStatus rv;
1972
13
    sslBuffer *chSource = ss->sec.isServer ? &ss->ssl3.hs.messages : &ss->ssl3.hs.echInnerMessages;
1973
13
    unsigned int offset = sizeof(SSL3ProtocolVersion) +
1974
13
                          SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN;
1975
13
    PORT_Assert(sh && shLen > offset);
1976
13
    PORT_Assert(TLS13_ECH_SIGNAL_LEN <= SSL3_RANDOM_LENGTH);
1977
1978
    /* TODO(djackson@mozilla.com) - Replace with streaming version */
1979
1980
13
    rv = sslBuffer_AppendBuffer(out, chSource);
1981
13
    if (rv != SECSuccess) {
1982
0
        goto loser;
1983
0
    }
1984
1985
    /* Re-create the message header. */
1986
13
    rv = sslBuffer_AppendNumber(out, ssl_hs_server_hello, 1);
1987
13
    if (rv != SECSuccess) {
1988
0
        goto loser;
1989
0
    }
1990
1991
13
    rv = sslBuffer_AppendNumber(out, shLen, 3);
1992
13
    if (rv != SECSuccess) {
1993
0
        goto loser;
1994
0
    }
1995
1996
    /* Copy the version and 24B of server_random. */
1997
13
    rv = sslBuffer_Append(out, sh, offset);
1998
13
    if (rv != SECSuccess) {
1999
0
        goto loser;
2000
0
    }
2001
2002
    /* Zero the signal placeholder. */
2003
13
    rv = sslBuffer_AppendNumber(out, 0, TLS13_ECH_SIGNAL_LEN);
2004
13
    if (rv != SECSuccess) {
2005
0
        goto loser;
2006
0
    }
2007
13
    offset += TLS13_ECH_SIGNAL_LEN;
2008
2009
    /* Use the remainder of SH. */
2010
13
    rv = sslBuffer_Append(out, &sh[offset], shLen - offset);
2011
13
    if (rv != SECSuccess) {
2012
0
        goto loser;
2013
0
    }
2014
13
    sslBuffer_Clear(&ss->ssl3.hs.messages);
2015
13
    sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
2016
13
    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
13
}
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
27
{
2031
27
    SECStatus rv;
2032
27
    sslBuffer confMsgs = SSL_BUFFER_EMPTY;
2033
27
    SSL3Hashes hashes;
2034
27
    PK11SymKey *echSecret = NULL;
2035
2036
27
    const char *hkdfInfo = isHrr ? kHkdfInfoEchHrrConfirm : kHkdfInfoEchConfirm;
2037
27
    const size_t hkdfInfoLen = strlen(hkdfInfo);
2038
2039
27
    PRINT_BUF(100, (ss, "ECH Server Hello", sh, shLen));
2040
2041
27
    if (isHrr) {
2042
14
        rv = tls13_ComputeEchHelloRetryTranscript(ss, sh, shLen, &confMsgs);
2043
14
    } else {
2044
13
        rv = tls13_ComputeEchServerHelloTranscript(ss, sh, shLen, &confMsgs);
2045
13
    }
2046
27
    if (rv != SECSuccess) {
2047
0
        goto loser;
2048
0
    }
2049
27
    PRINT_BUF(100, (ss, "ECH Transcript", confMsgs.buf, confMsgs.len));
2050
27
    rv = tls13_ComputeHash(ss, &hashes, confMsgs.buf, confMsgs.len,
2051
27
                           tls13_GetHash(ss));
2052
27
    if (rv != SECSuccess) {
2053
0
        goto loser;
2054
0
    }
2055
27
    PRINT_BUF(100, (ss, "ECH Transcript Hash", &hashes.u, hashes.len));
2056
27
    rv = tls13_DeriveEchSecret(ss, &echSecret);
2057
27
    if (rv != SECSuccess) {
2058
0
        return SECFailure;
2059
0
    }
2060
27
    rv = tls13_HkdfExpandLabelRaw(echSecret, tls13_GetHash(ss), hashes.u.raw,
2061
27
                                  hashes.len, hkdfInfo, hkdfInfoLen, ss->protocolVariant,
2062
27
                                  out, TLS13_ECH_SIGNAL_LEN);
2063
27
    if (rv != SECSuccess) {
2064
0
        return SECFailure;
2065
0
    }
2066
27
    SSL_TRC(50, ("%d: TLS13[%d]: %s computed ECH signal", SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
2067
27
    PRINT_BUF(50, (ss, "Computed ECH Signal", out, TLS13_ECH_SIGNAL_LEN));
2068
27
    PK11_FreeSymKey(echSecret);
2069
27
    sslBuffer_Clear(&confMsgs);
2070
27
    return SECSuccess;
2071
2072
0
loser:
2073
0
    PK11_FreeSymKey(echSecret);
2074
0
    sslBuffer_Clear(&confMsgs);
2075
0
    return SECFailure;
2076
27
}
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
27
{
2083
27
    SECStatus rv;
2084
27
    PK11SlotInfo *slot = NULL;
2085
27
    PK11SymKey *crKey = NULL;
2086
27
    SECItem rawKey;
2087
27
    const unsigned char *client_random = ss->sec.isServer ? ss->ssl3.hs.client_random : ss->ssl3.hs.client_inner_random;
2088
27
    PRINT_BUF(50, (ss, "Client Random for ECH", client_random, SSL3_RANDOM_LENGTH));
2089
    /* We need a SECItem */
2090
27
    rv = SECITEM_MakeItem(NULL, &rawKey, client_random, SSL3_RANDOM_LENGTH);
2091
27
    if (rv != SECSuccess) {
2092
0
        goto cleanup;
2093
0
    }
2094
    /* We need a slot*/
2095
27
    slot = PK11_GetBestSlot(CKM_HKDF_DERIVE, NULL);
2096
27
    if (!slot) {
2097
0
        rv = SECFailure;
2098
0
        goto cleanup;
2099
0
    }
2100
    /* We import the key */
2101
27
    crKey = PK11_ImportDataKey(slot, CKM_HKDF_DERIVE, PK11_OriginUnwrap,
2102
27
                               CKA_DERIVE, &rawKey, NULL);
2103
27
    if (crKey == NULL) {
2104
0
        rv = SECFailure;
2105
0
        goto cleanup;
2106
0
    }
2107
    /* NULL will be expanded to 0s of hash length */
2108
27
    rv = tls13_HkdfExtract(NULL, crKey, tls13_GetHash(ss), output);
2109
27
    if (rv != SECSuccess) {
2110
0
        goto cleanup;
2111
0
    }
2112
27
    SSL_TRC(50, ("%d: TLS13[%d]: ECH Confirmation Key Derived.",
2113
27
                 SSL_GETPID(), ss->fd));
2114
27
    PRINT_KEY(50, (NULL, "ECH Confirmation Key", *output));
2115
27
cleanup:
2116
27
    SECITEM_ZfreeItem(&rawKey, PR_FALSE);
2117
27
    if (slot) {
2118
27
        PK11_FreeSlot(slot);
2119
27
    }
2120
27
    if (crKey) {
2121
27
        PK11_FreeSymKey(crKey);
2122
27
    }
2123
27
    if (rv != SECSuccess && *output) {
2124
0
        PK11_FreeSymKey(*output);
2125
0
        *output = NULL;
2126
0
    }
2127
27
    return rv;
2128
27
}
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
35.5k
{
2135
35.5k
    SECStatus rv;
2136
35.5k
    sslBuffer chInnerXtns = SSL_BUFFER_EMPTY;
2137
35.5k
    sslBuffer encodedCh = SSL_BUFFER_EMPTY;
2138
35.5k
    sslBuffer greaseBuf = SSL_BUFFER_EMPTY;
2139
35.5k
    unsigned int payloadLen;
2140
35.5k
    HpkeAeadId aead;
2141
35.5k
    PK11SlotInfo *slot = NULL;
2142
35.5k
    PK11SymKey *hmacPrk = NULL;
2143
35.5k
    PK11SymKey *derivedData = NULL;
2144
35.5k
    SECItem *rawData;
2145
35.5k
    CK_HKDF_PARAMS params;
2146
35.5k
    SECItem paramsi;
2147
    /* 1B aead determinant (don't send), 1B config_id, 32B enc, payload */
2148
35.5k
    PR_ASSERT(!ss->sec.isServer);
2149
35.5k
    const int kNonPayloadLen = 34;
2150
2151
35.5k
    if (!ss->opt.enableTls13GreaseEch || ss->ssl3.hs.echHpkeCtx) {
2152
17.7k
        return SECSuccess;
2153
17.7k
    }
2154
2155
17.7k
    if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3 ||
2156
17.7k
        IS_DTLS(ss)) {
2157
17.7k
        return SECSuccess;
2158
17.7k
    }
2159
2160
0
    if (ss->firstHsDone) {
2161
0
        sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
2162
0
    }
2163
2164
    /* In draft-09, CH2 sends exactly the same GREASE ECH extension. */
2165
0
    if (ss->ssl3.hs.helloRetry) {
2166
0
        return ssl3_EmplaceExtension(ss, buf, ssl_tls13_encrypted_client_hello_xtn,
2167
0
                                     ss->ssl3.hs.greaseEchBuf.buf,
2168
0
                                     ss->ssl3.hs.greaseEchBuf.len, PR_TRUE);
2169
0
    }
2170
2171
    /* Compress the extensions for payload length. */
2172
0
    rv = tls13_ConstructInnerExtensionsFromOuter(ss, buf, &chInnerXtns,
2173
0
                                                 NULL, PR_TRUE);
2174
0
    if (rv != SECSuccess) {
2175
0
        goto loser; /* Code set */
2176
0
    }
2177
0
    rv = tls13_EncodeClientHelloInner(ss, preamble, &chInnerXtns, &encodedCh);
2178
0
    if (rv != SECSuccess) {
2179
0
        goto loser; /* Code set */
2180
0
    }
2181
0
    rv = tls13_PadChInner(&encodedCh, ss->ssl3.hs.greaseEchSize, strlen(ss->url));
2182
0
    if (rv != SECSuccess) {
2183
0
        goto loser; /* Code set */
2184
0
    }
2185
2186
0
    payloadLen = encodedCh.len;
2187
0
    payloadLen += TLS13_ECH_AEAD_TAG_LEN; /* Aead tag */
2188
2189
    /* HMAC-Expand to get something that will pass for ciphertext. */
2190
0
    slot = PK11_GetBestSlot(CKM_HKDF_DERIVE, NULL);
2191
0
    if (!slot) {
2192
0
        goto loser;
2193
0
    }
2194
2195
0
    hmacPrk = PK11_KeyGen(slot, CKM_HKDF_DATA, NULL, SHA256_LENGTH, NULL);
2196
0
    if (!hmacPrk) {
2197
0
        goto loser;
2198
0
    }
2199
2200
0
    params.bExtract = CK_FALSE;
2201
0
    params.bExpand = CK_TRUE;
2202
0
    params.prfHashMechanism = CKM_SHA256;
2203
0
    params.pInfo = NULL;
2204
0
    params.ulInfoLen = 0;
2205
0
    paramsi.data = (unsigned char *)&params;
2206
0
    paramsi.len = sizeof(params);
2207
0
    derivedData = PK11_DeriveWithFlags(hmacPrk, CKM_HKDF_DATA,
2208
0
                                       &paramsi, CKM_HKDF_DATA,
2209
0
                                       CKA_DERIVE, kNonPayloadLen + payloadLen,
2210
0
                                       CKF_VERIFY);
2211
0
    if (!derivedData) {
2212
0
        goto loser;
2213
0
    }
2214
2215
0
    rv = PK11_ExtractKeyValue(derivedData);
2216
0
    if (rv != SECSuccess) {
2217
0
        goto loser;
2218
0
    }
2219
2220
0
    rawData = PK11_GetKeyData(derivedData);
2221
0
    if (!rawData) {
2222
0
        goto loser;
2223
0
    }
2224
0
    PORT_Assert(rawData->len == kNonPayloadLen + payloadLen);
2225
2226
    /* struct {
2227
       HpkeSymmetricCipherSuite cipher_suite; // kdf_id, aead_id
2228
       PRUint8 config_id;
2229
       opaque enc<1..2^16-1>;
2230
       opaque payload<1..2^16-1>;
2231
    } ClientECH; */
2232
2233
0
    rv = sslBuffer_AppendNumber(&greaseBuf, ech_xtn_type_outer, 1);
2234
0
    if (rv != SECSuccess) {
2235
0
        goto loser;
2236
0
    }
2237
    /* Only support SHA256. */
2238
0
    rv = sslBuffer_AppendNumber(&greaseBuf, HpkeKdfHkdfSha256, 2);
2239
0
    if (rv != SECSuccess) {
2240
0
        goto loser;
2241
0
    }
2242
2243
    /* HpkeAeadAes128Gcm = 1, HpkeAeadChaCha20Poly1305 = 3, */
2244
0
    aead = (rawData->data[0] & 1) ? HpkeAeadAes128Gcm : HpkeAeadChaCha20Poly1305;
2245
0
    rv = sslBuffer_AppendNumber(&greaseBuf, aead, 2);
2246
0
    if (rv != SECSuccess) {
2247
0
        goto loser;
2248
0
    }
2249
2250
    /* config_id */
2251
0
    rv = sslBuffer_AppendNumber(&greaseBuf, rawData->data[1], 1);
2252
0
    if (rv != SECSuccess) {
2253
0
        goto loser;
2254
0
    }
2255
2256
    /* enc len is fixed 32B for X25519. */
2257
0
    rv = sslBuffer_AppendVariable(&greaseBuf, &rawData->data[2], 32, 2);
2258
0
    if (rv != SECSuccess) {
2259
0
        goto loser;
2260
0
    }
2261
2262
0
    rv = sslBuffer_AppendVariable(&greaseBuf, &rawData->data[kNonPayloadLen], payloadLen, 2);
2263
0
    if (rv != SECSuccess) {
2264
0
        goto loser;
2265
0
    }
2266
2267
    /* Mark ECH as advertised so that we can validate any response.
2268
     * We'll use echHpkeCtx to determine if we sent real or GREASE ECH. */
2269
0
    rv = ssl3_EmplaceExtension(ss, buf, ssl_tls13_encrypted_client_hello_xtn,
2270
0
                               greaseBuf.buf, greaseBuf.len, PR_TRUE);
2271
0
    if (rv != SECSuccess) {
2272
0
        goto loser;
2273
0
    }
2274
2275
    /* Stash the GREASE ECH extension - in the case of HRR, CH2 must echo it. */
2276
0
    PORT_Assert(ss->ssl3.hs.greaseEchBuf.len == 0);
2277
0
    ss->ssl3.hs.greaseEchBuf = greaseBuf;
2278
2279
0
    sslBuffer_Clear(&chInnerXtns);
2280
0
    sslBuffer_Clear(&encodedCh);
2281
0
    PK11_FreeSymKey(hmacPrk);
2282
0
    PK11_FreeSymKey(derivedData);
2283
0
    PK11_FreeSlot(slot);
2284
0
    return SECSuccess;
2285
2286
0
loser:
2287
0
    sslBuffer_Clear(&chInnerXtns);
2288
0
    sslBuffer_Clear(&encodedCh);
2289
0
    PK11_FreeSymKey(hmacPrk);
2290
0
    PK11_FreeSymKey(derivedData);
2291
0
    if (slot) {
2292
0
        PK11_FreeSlot(slot);
2293
0
    }
2294
0
    return SECFailure;
2295
0
}
2296
2297
SECStatus
2298
tls13_MaybeHandleEch(sslSocket *ss, const PRUint8 *msg, PRUint32 msgLen, SECItem *sidBytes,
2299
                     SECItem *comps, SECItem *cookieBytes, SECItem *suites, SECItem **echInner)
2300
3.61k
{
2301
3.61k
    SECStatus rv;
2302
3.61k
    SECItem *tmpEchInner = NULL;
2303
3.61k
    PRUint8 *b;
2304
3.61k
    PRUint32 length;
2305
3.61k
    TLSExtension *echExtension;
2306
3.61k
    TLSExtension *versionExtension;
2307
3.61k
    PORT_Assert(!ss->ssl3.hs.echAccepted);
2308
3.61k
    SECItem tmpSid = { siBuffer, NULL, 0 };
2309
3.61k
    SECItem tmpCookie = { siBuffer, NULL, 0 };
2310
3.61k
    SECItem tmpSuites = { siBuffer, NULL, 0 };
2311
3.61k
    SECItem tmpComps = { siBuffer, NULL, 0 };
2312
2313
3.61k
    echExtension = ssl3_FindExtension(ss, ssl_tls13_encrypted_client_hello_xtn);
2314
3.61k
    if (echExtension) {
2315
201
        rv = tls13_ServerHandleOuterEchXtn(ss, &ss->xtnData, &echExtension->data);
2316
201
        if (rv != SECSuccess) {
2317
59
            goto loser; /* code set, alert sent. */
2318
59
        }
2319
142
        rv = tls13_MaybeAcceptEch(ss, sidBytes, msg, msgLen, &tmpEchInner);
2320
142
        if (rv != SECSuccess) {
2321
18
            goto loser; /* code set, alert sent. */
2322
18
        }
2323
142
    }
2324
3.54k
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
2325
2326
3.54k
    if (ss->ssl3.hs.echAccepted) {
2327
0
        PORT_Assert(tmpEchInner);
2328
0
        PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.remoteExtensions));
2329
2330
        /* Start over on ECHInner */
2331
0
        b = tmpEchInner->data;
2332
0
        length = tmpEchInner->len;
2333
0
        rv = ssl3_HandleClientHelloPreamble(ss, &b, &length, &tmpSid,
2334
0
                                            &tmpCookie, &tmpSuites, &tmpComps);
2335
0
        if (rv != SECSuccess) {
2336
0
            goto loser; /* code set, alert sent. */
2337
0
        }
2338
2339
0
        versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
2340
0
        if (!versionExtension) {
2341
0
            FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, illegal_parameter);
2342
0
            goto loser;
2343
0
        }
2344
0
        rv = tls13_NegotiateVersion(ss, versionExtension);
2345
0
        if (rv != SECSuccess) {
2346
            /* code and alert set by tls13_NegotiateVersion */
2347
0
            goto loser;
2348
0
        }
2349
2350
0
        *comps = tmpComps;
2351
0
        *cookieBytes = tmpCookie;
2352
0
        *sidBytes = tmpSid;
2353
0
        *suites = tmpSuites;
2354
0
        *echInner = tmpEchInner;
2355
0
    }
2356
3.54k
    return SECSuccess;
2357
2358
77
loser:
2359
77
    SECITEM_FreeItem(tmpEchInner, PR_TRUE);
2360
77
    PORT_Assert(PORT_GetError() != 0);
2361
77
    return SECFailure;
2362
3.54k
}
2363
2364
SECStatus
2365
tls13_MaybeHandleEchSignal(sslSocket *ss, const PRUint8 *sh, PRUint32 shLen, PRBool isHrr)
2366
0
{
2367
0
    SECStatus rv;
2368
0
    PRUint8 computed[TLS13_ECH_SIGNAL_LEN];
2369
0
    const PRUint8 *signal;
2370
0
    PORT_Assert(!ss->sec.isServer);
2371
2372
    /* If !echHpkeCtx, we either didn't advertise or sent GREASE ECH. */
2373
0
    if (!ss->ssl3.hs.echHpkeCtx) {
2374
0
        SSL_TRC(50, ("%d: TLS13[%d]: client only sent GREASE ECH",
2375
0
                     SSL_GETPID(), ss->fd));
2376
0
        ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
2377
0
        return SECSuccess;
2378
0
    }
2379
2380
0
    PORT_Assert(!IS_DTLS(ss));
2381
2382
0
    if (isHrr) {
2383
0
        if (ss->xtnData.ech) {
2384
0
            signal = ss->xtnData.ech->hrrConfirmation;
2385
0
        } else {
2386
0
            SSL_TRC(50, ("%d: TLS13[%d]: client did not receive ECH Xtn from Server HRR",
2387
0
                         SSL_GETPID(), ss->fd));
2388
0
            signal = NULL;
2389
0
            ss->ssl3.hs.echAccepted = PR_FALSE;
2390
0
            ss->ssl3.hs.echDecided = PR_TRUE;
2391
0
        }
2392
0
    } else {
2393
0
        signal = &ss->ssl3.hs.server_random[SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN];
2394
0
    }
2395
2396
0
    PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn));
2397
2398
    /* Check ECH Confirmation for HRR ECH Xtn or ServerHello Random */
2399
0
    if (signal) {
2400
0
        rv = tls13_ComputeEchSignal(ss, isHrr, sh, shLen, computed);
2401
0
        if (rv != SECSuccess) {
2402
0
            return SECFailure;
2403
0
        }
2404
0
        PRINT_BUF(100, (ss, "Server Signal", signal, TLS13_ECH_SIGNAL_LEN));
2405
0
        PRBool new_decision = !NSS_SecureMemcmp(computed, signal, TLS13_ECH_SIGNAL_LEN);
2406
        /* Server can't change its mind on whether to accept ECH */
2407
0
        if (ss->ssl3.hs.echDecided && new_decision != ss->ssl3.hs.echAccepted) {
2408
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
2409
0
            return SECFailure;
2410
0
        }
2411
0
        ss->ssl3.hs.echAccepted = new_decision;
2412
0
        ss->ssl3.hs.echDecided = PR_TRUE;
2413
0
    }
2414
2415
0
    ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
2416
0
    if (ss->ssl3.hs.echAccepted) {
2417
0
        if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
2418
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
2419
0
            return SECFailure;
2420
0
        }
2421
        /* Server accepted, but sent an extension which was only advertised in the ClientHelloOuter */
2422
0
        if (ss->ssl3.hs.echInvalidExtension) {
2423
0
            (void)SSL3_SendAlert(ss, alert_fatal, unsupported_extension);
2424
0
            PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
2425
0
            return SECFailure;
2426
0
        }
2427
2428
        /* Swap the advertised lists as we've accepted ECH. */
2429
0
        PRUint16 *tempArray = ss->xtnData.advertised;
2430
0
        PRUint16 tempNum = ss->xtnData.numAdvertised;
2431
2432
0
        ss->xtnData.advertised = ss->xtnData.echAdvertised;
2433
0
        ss->xtnData.numAdvertised = ss->xtnData.echNumAdvertised;
2434
2435
0
        ss->xtnData.echAdvertised = tempArray;
2436
0
        ss->xtnData.echNumAdvertised = tempNum;
2437
2438
        /* |enc| must not be included in CH2.ClientECH. */
2439
0
        if (ss->ssl3.hs.helloRetry && ss->sec.isServer &&
2440
0
            ss->xtnData.ech->senderPubKey.len) {
2441
0
            ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
2442
0
            PORT_SetError(SSL_ERROR_BAD_2ND_CLIENT_HELLO);
2443
0
            return SECFailure;
2444
0
        }
2445
0
        ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_tls13_encrypted_client_hello_xtn;
2446
2447
        /* Only overwrite client_random with client_inner_random if CHInner was
2448
         *  succesfully used for handshake (NOT if HRR is received). */
2449
0
        if (!isHrr) {
2450
0
            PORT_Memcpy(ss->ssl3.hs.client_random, ss->ssl3.hs.client_inner_random, SSL3_RANDOM_LENGTH);
2451
0
        }
2452
0
    }
2453
    /* If rejected, leave echHpkeCtx and echPublicName for rejection paths. */
2454
0
    ssl3_CoalesceEchHandshakeHashes(ss);
2455
0
    SSL_TRC(3, ("%d: TLS13[%d]: ECH %s accepted by server",
2456
0
                SSL_GETPID(), ss->fd, ss->ssl3.hs.echAccepted ? "is" : "is not"));
2457
0
    return SECSuccess;
2458
0
}
2459
2460
static SECStatus
2461
tls13_UnencodeChInner(sslSocket *ss, const SECItem *sidBytes, SECItem **echInner)
2462
0
{
2463
0
    SECStatus rv;
2464
0
    sslReadBuffer outerExtensionsList;
2465
0
    sslReadBuffer tmpReadBuf;
2466
0
    sslBuffer unencodedChInner = SSL_BUFFER_EMPTY;
2467
0
    PRCList *outerCursor;
2468
0
    PRCList *innerCursor;
2469
0
    PRBool outerFound;
2470
0
    PRUint32 xtnsOffset;
2471
0
    PRUint64 tmp;
2472
0
    PRUint8 *tmpB;
2473
0
    PRUint32 tmpLength;
2474
0
    sslReader chReader = SSL_READER((*echInner)->data, (*echInner)->len);
2475
0
    PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.echOuterExtensions));
2476
0
    PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ssl3.hs.remoteExtensions));
2477
0
    TLSExtension *echExtension;
2478
0
    int error = SSL_ERROR_INTERNAL_ERROR_ALERT;
2479
0
    int errDesc = internal_error;
2480
2481
0
    PRINT_BUF(100, (ss, "ECH Inner", chReader.buf.buf, chReader.buf.len));
2482
2483
    /* unencodedChInner := preamble, tmpReadBuf := encoded extensions. */
2484
0
    rv = tls13_CopyChPreamble(ss, &chReader, sidBytes, &unencodedChInner, &tmpReadBuf);
2485
0
    if (rv != SECSuccess) {
2486
0
        goto loser; /* code set */
2487
0
    }
2488
2489
    /* Parse inner extensions into ss->ssl3.hs.remoteExtensions. */
2490
0
    tmpB = CONST_CAST(PRUint8, tmpReadBuf.buf);
2491
0
    rv = ssl3_ParseExtensions(ss, &tmpB, &tmpReadBuf.len);
2492
0
    if (rv != SECSuccess) {
2493
0
        goto loser; /* malformed, alert sent. */
2494
0
    }
2495
2496
0
    echExtension = ssl3_FindExtension(ss, ssl_tls13_encrypted_client_hello_xtn);
2497
0
    if (!echExtension) {
2498
0
        error = SSL_ERROR_MISSING_ECH_EXTENSION;
2499
0
        errDesc = illegal_parameter;
2500
0
        goto alert_loser; /* Must have an inner Extension */
2501
0
    }
2502
0
    rv = tls13_ServerHandleInnerEchXtn(ss, &ss->xtnData, &echExtension->data);
2503
0
    if (rv != SECSuccess) {
2504
0
        goto loser; /* code set, alert sent. */
2505
0
    }
2506
2507
    /* Exit early if there are no outer_extensions to decompress. */
2508
0
    if (!ssl3_FindExtension(ss, ssl_tls13_outer_extensions_xtn)) {
2509
0
        rv = sslBuffer_AppendVariable(&unencodedChInner, tmpReadBuf.buf, tmpReadBuf.len, 2);
2510
0
        if (rv != SECSuccess) {
2511
0
            goto loser;
2512
0
        }
2513
0
        sslBuffer_Clear(&unencodedChInner);
2514
0
        return SECSuccess;
2515
0
    }
2516
2517
    /* Save room for uncompressed length. */
2518
0
    rv = sslBuffer_Skip(&unencodedChInner, 2, &xtnsOffset);
2519
0
    if (rv != SECSuccess) {
2520
0
        goto loser;
2521
0
    }
2522
2523
    /* For each inner extension: If not outer_extensions, copy it to the output.
2524
     * Else if outer_extensions, iterate the compressed extension list and append
2525
     * each full extension as contained in CHOuter. Compressed extensions must be
2526
     * contiguous, so decompress at the point at which outer_extensions appears. */
2527
0
    for (innerCursor = PR_NEXT_LINK(&ss->ssl3.hs.remoteExtensions);
2528
0
         innerCursor != &ss->ssl3.hs.remoteExtensions;
2529
0
         innerCursor = PR_NEXT_LINK(innerCursor)) {
2530
0
        TLSExtension *innerExtension = (TLSExtension *)innerCursor;
2531
0
        if (innerExtension->type != ssl_tls13_outer_extensions_xtn) {
2532
0
            SSL_TRC(10, ("%d: SSL3[%d]: copying inner extension of type %d and size %d directly", SSL_GETPID(),
2533
0
                         ss->fd, innerExtension->type, innerExtension->data.len));
2534
0
            rv = sslBuffer_AppendNumber(&unencodedChInner,
2535
0
                                        innerExtension->type, 2);
2536
0
            if (rv != SECSuccess) {
2537
0
                goto loser;
2538
0
            }
2539
0
            rv = sslBuffer_AppendVariable(&unencodedChInner,
2540
0
                                          innerExtension->data.data,
2541
0
                                          innerExtension->data.len, 2);
2542
0
            if (rv != SECSuccess) {
2543
0
                goto loser;
2544
0
            }
2545
0
            continue;
2546
0
        }
2547
2548
        /* Decompress */
2549
0
        sslReader extensionRdr = SSL_READER(innerExtension->data.data,
2550
0
                                            innerExtension->data.len);
2551
0
        rv = sslRead_ReadVariable(&extensionRdr, 1, &outerExtensionsList);
2552
0
        if (rv != SECSuccess) {
2553
0
            SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions has invalid size.",
2554
0
                         SSL_GETPID(), ss->fd));
2555
0
            error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
2556
0
            errDesc = illegal_parameter;
2557
0
            goto alert_loser;
2558
0
        }
2559
0
        if (SSL_READER_REMAINING(&extensionRdr) || (outerExtensionsList.len % 2) != 0 || !outerExtensionsList.len) {
2560
0
            SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions has invalid size.",
2561
0
                         SSL_GETPID(), ss->fd));
2562
0
            error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
2563
0
            errDesc = illegal_parameter;
2564
0
            goto alert_loser;
2565
0
        }
2566
2567
0
        outerCursor = &ss->ssl3.hs.echOuterExtensions;
2568
0
        sslReader compressedTypes = SSL_READER(outerExtensionsList.buf, outerExtensionsList.len);
2569
0
        while (SSL_READER_REMAINING(&compressedTypes)) {
2570
0
            outerFound = PR_FALSE;
2571
0
            rv = sslRead_ReadNumber(&compressedTypes, 2, &tmp);
2572
0
            if (rv != SECSuccess) {
2573
0
                SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions has invalid contents.",
2574
0
                             SSL_GETPID(), ss->fd));
2575
0
                error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
2576
0
                errDesc = illegal_parameter;
2577
0
                goto alert_loser;
2578
0
            }
2579
0
            if (tmp == ssl_tls13_encrypted_client_hello_xtn ||
2580
0
                tmp == ssl_tls13_outer_extensions_xtn) {
2581
0
                SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions contains an invalid reference.",
2582
0
                             SSL_GETPID(), ss->fd));
2583
0
                error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
2584
0
                errDesc = illegal_parameter;
2585
0
                goto alert_loser;
2586
0
            }
2587
0
            do {
2588
0
                const TLSExtension *candidate = (TLSExtension *)outerCursor;
2589
                /* Advance the outerCursor, we never consider the same xtn twice. */
2590
0
                outerCursor = PR_NEXT_LINK(outerCursor);
2591
0
                if (candidate->type == tmp) {
2592
0
                    outerFound = PR_TRUE;
2593
0
                    SSL_TRC(100, ("%d: SSL3[%d]: Decompressing ECH Inner Extension of type %d",
2594
0
                                  SSL_GETPID(), ss->fd, tmp));
2595
0
                    rv = sslBuffer_AppendNumber(&unencodedChInner,
2596
0
                                                candidate->type, 2);
2597
0
                    if (rv != SECSuccess) {
2598
0
                        goto loser;
2599
0
                    }
2600
0
                    rv = sslBuffer_AppendVariable(&unencodedChInner,
2601
0
                                                  candidate->data.data,
2602
0
                                                  candidate->data.len, 2);
2603
0
                    if (rv != SECSuccess) {
2604
0
                        goto loser;
2605
0
                    }
2606
0
                    break;
2607
0
                }
2608
0
            } while (outerCursor != &ss->ssl3.hs.echOuterExtensions);
2609
0
            if (!outerFound) {
2610
0
                SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions has missing,"
2611
0
                             " out of order or duplicate references.",
2612
0
                             SSL_GETPID(), ss->fd));
2613
0
                error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
2614
0
                errDesc = illegal_parameter;
2615
0
                goto alert_loser;
2616
0
            }
2617
0
        }
2618
0
    }
2619
0
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.echOuterExtensions);
2620
0
    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
2621
2622
    /* Correct the message and extensions sizes. */
2623
0
    rv = sslBuffer_InsertNumber(&unencodedChInner, xtnsOffset,
2624
0
                                unencodedChInner.len - xtnsOffset - 2, 2);
2625
0
    if (rv != SECSuccess) {
2626
0
        goto loser;
2627
0
    }
2628
2629
0
    tmpB = &unencodedChInner.buf[xtnsOffset];
2630
0
    tmpLength = unencodedChInner.len - xtnsOffset;
2631
0
    rv = ssl3_ConsumeHandshakeNumber64(ss, &tmp, 2, &tmpB, &tmpLength);
2632
0
    if (rv != SECSuccess || tmpLength != tmp) {
2633
0
        error = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
2634
0
        errDesc = internal_error;
2635
0
        goto alert_loser;
2636
0
    }
2637
2638
0
    rv = ssl3_ParseExtensions(ss, &tmpB, &tmpLength);
2639
0
    if (rv != SECSuccess) {
2640
0
        goto loser; /* Error set and alert already sent */
2641
0
    }
2642
2643
0
    SECITEM_FreeItem(*echInner, PR_FALSE);
2644
0
    (*echInner)->data = unencodedChInner.buf;
2645
0
    (*echInner)->len = unencodedChInner.len;
2646
0
    return SECSuccess;
2647
0
alert_loser:
2648
0
    FATAL_ERROR(ss, error, errDesc);
2649
0
loser:
2650
0
    sslBuffer_Clear(&unencodedChInner);
2651
0
    return SECFailure;
2652
0
}
2653
2654
SECStatus
2655
tls13_MaybeAcceptEch(sslSocket *ss, const SECItem *sidBytes, const PRUint8 *chOuter,
2656
                     unsigned int chOuterLen, SECItem **chInner)
2657
142
{
2658
142
    SECStatus rv;
2659
142
    SECItem outer = { siBuffer, CONST_CAST(PRUint8, chOuter), chOuterLen };
2660
142
    SECItem *decryptedChInner = NULL;
2661
142
    SECItem outerAAD = { siBuffer, NULL, 0 };
2662
142
    SECItem cookieData = { siBuffer, NULL, 0 };
2663
142
    sslEchCookieData echData;
2664
142
    sslEchConfig *candidate = NULL; /* non-owning */
2665
142
    TLSExtension *hrrXtn;
2666
142
    PRBool previouslyOfferedEch;
2667
2668
142
    if (!ss->xtnData.ech || ss->xtnData.ech->receivedInnerXtn || IS_DTLS(ss)) {
2669
36
        ss->ssl3.hs.echDecided = PR_TRUE;
2670
36
        return SECSuccess;
2671
36
    }
2672
2673
106
    PORT_Assert(ss->xtnData.ech->innerCh.data);
2674
2675
106
    if (ss->ssl3.hs.helloRetry) {
2676
74
        ss->ssl3.hs.echDecided = PR_TRUE;
2677
74
        PORT_Assert(!ss->ssl3.hs.echHpkeCtx);
2678
74
        hrrXtn = ssl3_FindExtension(ss, ssl_tls13_cookie_xtn);
2679
74
        if (!hrrXtn) {
2680
            /* If the client doesn't echo cookie, we can't decrypt. */
2681
6
            return SECSuccess;
2682
6
        }
2683
2684
68
        PORT_Assert(!ss->ssl3.hs.echHpkeCtx);
2685
2686
68
        PRUint8 *tmp = hrrXtn->data.data;
2687
68
        PRUint32 len = hrrXtn->data.len;
2688
68
        rv = ssl3_ExtConsumeHandshakeVariable(ss, &cookieData, 2,
2689
68
                                              &tmp, &len);
2690
68
        if (rv != SECSuccess) {
2691
2
            return SECFailure;
2692
2
        }
2693
2694
        /* Extract ECH info without restoring hash state. If there's
2695
         * something wrong with the cookie, continue without ECH
2696
         * and let HRR code handle the problem. */
2697
66
        rv = tls13_HandleHrrCookie(ss, cookieData.data, cookieData.len,
2698
66
                                   NULL, NULL, &previouslyOfferedEch, &echData, PR_FALSE);
2699
66
        if (rv != SECSuccess) {
2700
46
            return SECSuccess;
2701
46
        }
2702
2703
20
        ss->ssl3.hs.echHpkeCtx = echData.hpkeCtx;
2704
2705
20
        const PRUint8 greaseConstant[TLS13_ECH_SIGNAL_LEN] = { 0 };
2706
20
        ss->ssl3.hs.echAccepted = previouslyOfferedEch &&
2707
20
                                  !NSS_SecureMemcmp(greaseConstant, echData.signal, TLS13_ECH_SIGNAL_LEN);
2708
2709
20
        if (echData.configId != ss->xtnData.ech->configId ||
2710
20
            echData.kdfId != ss->xtnData.ech->kdfId ||
2711
20
            echData.aeadId != ss->xtnData.ech->aeadId) {
2712
16
            FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
2713
16
                        illegal_parameter);
2714
16
            return SECFailure;
2715
16
        }
2716
2717
4
        if (!ss->ssl3.hs.echHpkeCtx) {
2718
4
            return SECSuccess;
2719
4
        }
2720
4
    }
2721
2722
32
    if (ss->ssl3.hs.echDecided && !ss->ssl3.hs.echAccepted) {
2723
        /* We don't change our mind */
2724
0
        return SECSuccess;
2725
0
    }
2726
    /* Regardless of where we return, the outcome is decided */
2727
32
    ss->ssl3.hs.echDecided = PR_TRUE;
2728
2729
    /* Cookie data was good, proceed with ECH. */
2730
32
    rv = tls13_GetMatchingEchConfigs(ss, ss->xtnData.ech->kdfId, ss->xtnData.ech->aeadId,
2731
32
                                     ss->xtnData.ech->configId, candidate, &candidate);
2732
32
    if (rv != SECSuccess) {
2733
0
        FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2734
0
        return SECFailure;
2735
0
    }
2736
2737
32
    if (candidate) {
2738
0
        rv = tls13_ServerMakeChOuterAAD(ss, chOuter, chOuterLen, &outerAAD);
2739
0
        if (rv != SECSuccess) {
2740
0
            return SECFailure;
2741
0
        }
2742
0
    }
2743
2744
32
    while (candidate) {
2745
0
        rv = tls13_OpenClientHelloInner(ss, &outer, &outerAAD, candidate, &decryptedChInner);
2746
0
        if (rv != SECSuccess) {
2747
            /* Get the next matching config */
2748
0
            rv = tls13_GetMatchingEchConfigs(ss, ss->xtnData.ech->kdfId, ss->xtnData.ech->aeadId,
2749
0
                                             ss->xtnData.ech->configId, candidate, &candidate);
2750
0
            if (rv != SECSuccess) {
2751
0
                FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2752
0
                SECITEM_FreeItem(&outerAAD, PR_FALSE);
2753
0
                return SECFailure;
2754
0
            }
2755
0
            continue;
2756
0
        }
2757
0
        break;
2758
0
    }
2759
32
    SECITEM_FreeItem(&outerAAD, PR_FALSE);
2760
2761
32
    if (rv != SECSuccess || !decryptedChInner) {
2762
32
        if (ss->ssl3.hs.helloRetry) {
2763
0
            FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ECH_EXTENSION, decrypt_error);
2764
0
            return SECFailure;
2765
32
        } else {
2766
            /* Send retry_configs (if we have any) when we fail to decrypt or
2767
             * found no candidates. This does *not* count as negotiating ECH. */
2768
32
            return ssl3_RegisterExtensionSender(ss, &ss->xtnData,
2769
32
                                                ssl_tls13_encrypted_client_hello_xtn,
2770
32
                                                tls13_ServerSendEchXtn);
2771
32
        }
2772
32
    }
2773
2774
0
    SSL_TRC(20, ("%d: TLS13[%d]: Successfully opened ECH inner CH",
2775
0
                 SSL_GETPID(), ss->fd));
2776
0
    PRINT_BUF(50, (ss, "Compressed CHInner", decryptedChInner->data,
2777
0
                   decryptedChInner->len));
2778
2779
0
    ss->ssl3.hs.echAccepted = PR_TRUE;
2780
2781
    /* Stash the CHOuter extensions. They're not yet handled (only parsed). If
2782
     * the CHInner contains outer_extensions_xtn, we'll need to reference them. */
2783
0
    ssl3_MoveRemoteExtensions(&ss->ssl3.hs.echOuterExtensions, &ss->ssl3.hs.remoteExtensions);
2784
2785
0
    rv = tls13_UnencodeChInner(ss, sidBytes, &decryptedChInner);
2786
0
    if (rv != SECSuccess) {
2787
0
        SECITEM_FreeItem(decryptedChInner, PR_TRUE);
2788
0
        return SECFailure; /* code set */
2789
0
    }
2790
0
    PRINT_BUF(50, (ss, "Uncompressed CHInner", decryptedChInner->data,
2791
0
                   decryptedChInner->len));
2792
0
    *chInner = decryptedChInner;
2793
0
    return SECSuccess;
2794
0
}
2795
2796
SECStatus
2797
tls13_WriteServerEchSignal(sslSocket *ss, PRUint8 *sh, unsigned int shLen)
2798
13
{
2799
13
    SECStatus rv;
2800
13
    PRUint8 signal[TLS13_ECH_SIGNAL_LEN];
2801
13
    PRUint8 *msg_random = &sh[sizeof(SSL3ProtocolVersion)];
2802
2803
13
    PORT_Assert(shLen > sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH);
2804
13
    PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
2805
2806
13
    rv = tls13_ComputeEchSignal(ss, PR_FALSE, sh, shLen, signal);
2807
13
    if (rv != SECSuccess) {
2808
0
        return SECFailure;
2809
0
    }
2810
13
    PRUint8 *dest = &msg_random[SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN];
2811
13
    PORT_Memcpy(dest, signal, TLS13_ECH_SIGNAL_LEN);
2812
2813
    /* Keep the socket copy consistent. */
2814
13
    PORT_Assert(0 == memcmp(msg_random, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN));
2815
13
    dest = &ss->ssl3.hs.server_random[SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN];
2816
13
    PORT_Memcpy(dest, signal, TLS13_ECH_SIGNAL_LEN);
2817
2818
13
    return SECSuccess;
2819
13
}
2820
2821
SECStatus
2822
tls13_WriteServerEchHrrSignal(sslSocket *ss, PRUint8 *sh, unsigned int shLen)
2823
14
{
2824
14
    SECStatus rv;
2825
14
    PR_ASSERT(shLen >= 4 + TLS13_ECH_SIGNAL_LEN);
2826
    /* We put the HRR ECH extension last. */
2827
14
    PRUint8 *placeholder_location = sh + shLen - TLS13_ECH_SIGNAL_LEN;
2828
    /* Defensive check that we are overwriting the contents of the right extension */
2829
14
    PR_ASSERT(tls13_Debug_CheckXtnBegins(placeholder_location - 4, ssl_tls13_encrypted_client_hello_xtn));
2830
    /* Calculate signal and overwrite */
2831
14
    rv = tls13_ComputeEchSignal(ss, PR_TRUE, sh, shLen, placeholder_location);
2832
14
    if (rv != SECSuccess) {
2833
0
        return SECFailure;
2834
0
    }
2835
    /* Free HRR GREASE/accept_confirmation value, it MUST be restored from
2836
     * cookie when handling CH2 after HRR. */
2837
14
    sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
2838
14
    return SECSuccess;
2839
14
}