tor-browser

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

tls13con.c (258885B)


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