tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

tls13ech.c (99852B)


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