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