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
tls13_FatalError(sslSocket * ss,PRErrorCode prError,SSL3AlertDescription desc)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 *
tls13_HandshakeState(SSL3WaitState st)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
tls13_SetHsState(sslSocket * ss,SSL3WaitState ws,const char * func,const char * file,int line)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
tls13_InHsStateV(sslSocket * ss,va_list ap)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
tls13_InHsState(sslSocket * ss,...)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
tls13_CheckHsState(sslSocket * ss,int err,const char * error_name,const char * func,const char * file,int line,...)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
tls13_IsPostHandshake(const sslSocket * ss)251 tls13_IsPostHandshake(const sslSocket *ss)
252 {
253     return ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 && ss->firstHsDone;
254 }
255 
256 SSLHashType
tls13_GetHashForCipherSuite(ssl3CipherSuite suite)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
tls13_GetHash(const sslSocket * ss)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
tls13_GetHashAndCipher(PRUint16 version,PRUint16 cipherSuite,SSLHashType * hash,const ssl3BulkCipherDef ** cipher)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
tls13_GetHashSizeForHash(SSLHashType hash)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
tls13_GetHashSize(const sslSocket * ss)329 tls13_GetHashSize(const sslSocket *ss)
330 {
331     return tls13_GetHashSizeForHash(tls13_GetHash(ss));
332 }
333 
334 static CK_MECHANISM_TYPE
tls13_GetHmacMechanismFromHash(SSLHashType hashType)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
tls13_GetHmacMechanism(const sslSocket * ss)349 tls13_GetHmacMechanism(const sslSocket *ss)
350 {
351     return tls13_GetHmacMechanismFromHash(tls13_GetHash(ss));
352 }
353 
354 SECStatus
tls13_ComputeHash(sslSocket * ss,SSL3Hashes * hashes,const PRUint8 * buf,unsigned int len,SSLHashType hash)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
tls13_CreateKeyShare(sslSocket * ss,const sslNamedGroupDef * groupDef,sslEphemeralKeyPair ** keyPair)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
tls13_AddKeyShare(sslSocket * ss,const sslNamedGroupDef * groupDef)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
SSL_SendAdditionalKeyShares(PRFileDesc * fd,unsigned int count)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
tls13_SetupClientHello(sslSocket * ss,sslClientHelloType chType)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
tls13_ImportDHEKeyShare(SECKEYPublicKey * peerKey,PRUint8 * b,PRUint32 length,SECKEYPublicKey * pubKey)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
tls13_HandleKeyShare(sslSocket * ss,TLS13KeyShareEntry * entry,sslKeyPair * keyPair,SSLHashType hash,PK11SymKey ** out)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
tls13_UseServerSecret(sslSocket * ss,SSLSecretDirection direction)633 tls13_UseServerSecret(sslSocket *ss, SSLSecretDirection direction)
634 {
635     return ss->sec.isServer == (direction == ssl_secret_write);
636 }
637 
638 static PK11SymKey **
tls13_TrafficSecretRef(sslSocket * ss,SSLSecretDirection direction)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
tls13_UpdateTrafficKeys(sslSocket * ss,SSLSecretDirection direction)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
tls13_SendKeyUpdate(sslSocket * ss,tls13KeyUpdateRequest request,PRBool buffer)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
SSLExp_KeyUpdate(PRFileDesc * fd,PRBool requestUpdate)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
tls13_HandleKeyUpdate(sslSocket * ss,PRUint8 * b,unsigned int length)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
SSLExp_SendCertificateRequest(PRFileDesc * fd)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
tls13_HandlePostHelloHandshakeMessage(sslSocket * ss,PRUint8 * b,PRUint32 length)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
tls13_RecoverWrappedSharedSecret(sslSocket * ss,sslSessionID * sid)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
tls13_ComputeEarlySecretsWithPsk(sslSocket * ss)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
tls13_DeriveEarlySecrets(sslSocket * ss)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
tls13_ComputeHandshakeSecret(sslSocket * ss)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
tls13_ComputeHandshakeSecrets(sslSocket * ss)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
tls13_ComputeApplicationSecrets(sslSocket * ss)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
tls13_ComputeFinalSecrets(sslSocket * ss)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
tls13_RestoreCipherInfo(sslSocket * ss,sslSessionID * sid)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
tls13_CanResume(sslSocket * ss,const sslSessionID * sid)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 hrr = PR_FALSE;
1833     PRBool previousOfferedEch;
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                                    &previousOfferedEch, NULL, PR_TRUE);
1886 
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 (previousOfferedEch != (ss->xtnData.ech != NULL)) {
1948             FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
1949                         previousOfferedEch ? 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     if (ss->xtnData.ech) {
2225         PRUint8 echGreaseRaw[TLS13_ECH_SIGNAL_LEN] = { 0 };
2226         if (!ss->ssl3.hs.echAccepted) {
2227             rv = PK11_GenerateRandom(echGreaseRaw, TLS13_ECH_SIGNAL_LEN);
2228             if (rv != SECSuccess) {
2229                 return SECFailure;
2230             }
2231         }
2232         sslBuffer echGreaseBuffer = SSL_BUFFER_EMPTY;
2233         rv = sslBuffer_Append(&echGreaseBuffer, echGreaseRaw, sizeof(echGreaseRaw));
2234         if (rv != SECSuccess) {
2235             return SECFailure;
2236         }
2237         /* Store the GREASE signal so we can later include it in the cookie and HRR extension */
2238         SSL_TRC(100, ("Generating and storing a random value for ECH HRR Grease value."));
2239         ss->ssl3.hs.greaseEchBuf = echGreaseBuffer;
2240     }
2241 
2242     /* Compute the cookie we are going to need. */
2243     rv = tls13_MakeHrrCookie(ss, requestedGroup,
2244                              appToken, appTokenLen,
2245                              cookie, &cookieLen, sizeof(cookie));
2246     if (rv != SECSuccess) {
2247         FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2248         return SECFailure;
2249     }
2250 
2251     /* Now build the body of the message. */
2252     rv = tls13_ConstructHelloRetryRequest(ss, ss->ssl3.hs.cipher_suite,
2253                                           requestedGroup,
2254                                           cookie, cookieLen, &messageBuf);
2255     if (rv != SECSuccess) {
2256         FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2257         return SECFailure;
2258     }
2259 
2260     /* And send it. */
2261     ssl_GetXmitBufLock(ss);
2262     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello,
2263                                     SSL_BUFFER_LEN(&messageBuf));
2264     if (rv != SECSuccess) {
2265         goto loser;
2266     }
2267     rv = ssl3_AppendBufferToHandshake(ss, &messageBuf);
2268     if (rv != SECSuccess) {
2269         goto loser;
2270     }
2271     sslBuffer_Clear(&messageBuf); /* Done with messageBuf */
2272 
2273     if (ss->ssl3.hs.fakeSid.len) {
2274         PRInt32 sent;
2275 
2276         PORT_Assert(!IS_DTLS(ss));
2277         rv = ssl3_SendChangeCipherSpecsInt(ss);
2278         if (rv != SECSuccess) {
2279             goto loser;
2280         }
2281         /* ssl3_SendChangeCipherSpecsInt() only flushes to the output buffer, so we
2282          * have to force a send. */
2283         sent = ssl_SendSavedWriteData(ss);
2284         if (sent < 0 && PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
2285             PORT_SetError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2286             goto loser;
2287         }
2288     } else {
2289         rv = ssl3_FlushHandshake(ss, 0);
2290         if (rv != SECSuccess) {
2291             goto loser; /* error code set by ssl3_FlushHandshake */
2292         }
2293     }
2294 
2295     /* We depend on this being exactly one record and one message. */
2296     PORT_Assert(!IS_DTLS(ss) || (ss->ssl3.hs.sendMessageSeq == 1 &&
2297                                  ss->ssl3.cwSpec->nextSeqNum == 1));
2298     ssl_ReleaseXmitBufLock(ss);
2299 
2300     ss->ssl3.hs.helloRetry = PR_TRUE;
2301 
2302     /* We received early data but have to ignore it because we sent a retry. */
2303     if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
2304         ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
2305         ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_hrr;
2306     }
2307 
2308     return SECSuccess;
2309 
2310 loser:
2311     sslBuffer_Clear(&messageBuf);
2312     ssl_ReleaseXmitBufLock(ss);
2313     return SECFailure;
2314 }
2315 
2316 /* Called from tls13_HandleClientHello.
2317  *
2318  * Caller must hold Handshake and RecvBuf locks.
2319  */
2320 
2321 static SECStatus
2322 tls13_HandleClientKeyShare(sslSocket *ss, TLS13KeyShareEntry *peerShare)
2323 {
2324     SECStatus rv;
2325     sslEphemeralKeyPair *keyPair; /* ours */
2326 
2327     SSL_TRC(3, ("%d: TLS13[%d]: handle client_key_share handshake",
2328                 SSL_GETPID(), ss->fd));
2329 
2330     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
2331     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2332     PORT_Assert(peerShare);
2333 
2334     tls13_SetKeyExchangeType(ss, peerShare->group);
2335 
2336     /* Generate our key */
2337     rv = tls13_AddKeyShare(ss, peerShare->group);
2338     if (rv != SECSuccess) {
2339         return rv;
2340     }
2341 
2342     /* We should have exactly one key share. */
2343     PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
2344     PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==
2345                 PR_NEXT_LINK(&ss->ephemeralKeyPairs));
2346 
2347     keyPair = ((sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs));
2348     ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->keys->pubKey);
2349 
2350     /* Register the sender */
2351     rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_tls13_key_share_xtn,
2352                                       tls13_ServerSendKeyShareXtn);
2353     if (rv != SECSuccess) {
2354         return SECFailure; /* Error code set already. */
2355     }
2356 
2357     rv = tls13_HandleKeyShare(ss, peerShare, keyPair->keys,
2358                               tls13_GetHash(ss),
2359                               &ss->ssl3.hs.dheSecret);
2360     return rv; /* Error code set already. */
2361 }
2362 
2363 /*
2364  *     [draft-ietf-tls-tls13-11] Section 6.3.3.2
2365  *
2366  *     opaque DistinguishedName<1..2^16-1>;
2367  *
2368  *     struct {
2369  *         opaque certificate_extension_oid<1..2^8-1>;
2370  *         opaque certificate_extension_values<0..2^16-1>;
2371  *     } CertificateExtension;
2372  *
2373  *     struct {
2374  *         opaque certificate_request_context<0..2^8-1>;
2375  *         SignatureAndHashAlgorithm
2376  *           supported_signature_algorithms<2..2^16-2>;
2377  *         DistinguishedName certificate_authorities<0..2^16-1>;
2378  *         CertificateExtension certificate_extensions<0..2^16-1>;
2379  *     } CertificateRequest;
2380  */
2381 static SECStatus
2382 tls13_SendCertificateRequest(sslSocket *ss)
2383 {
2384     SECStatus rv;
2385     sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
2386     unsigned int offset = 0;
2387 
2388     SSL_TRC(3, ("%d: TLS13[%d]: begin send certificate_request",
2389                 SSL_GETPID(), ss->fd));
2390 
2391     if (ss->firstHsDone) {
2392         PORT_Assert(ss->ssl3.hs.shaPostHandshake == NULL);
2393         ss->ssl3.hs.shaPostHandshake = PK11_CloneContext(ss->ssl3.hs.sha);
2394         if (ss->ssl3.hs.shaPostHandshake == NULL) {
2395             ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
2396             return SECFailure;
2397         }
2398     }
2399 
2400     rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_certificate_request);
2401     if (rv != SECSuccess) {
2402         return SECFailure; /* Code already set. */
2403     }
2404     /* We should always have at least one of these. */
2405     PORT_Assert(SSL_BUFFER_LEN(&extensionBuf) > 0);
2406 
2407     /* Create a new request context for post-handshake authentication */
2408     if (ss->firstHsDone) {
2409         PRUint8 context[16];
2410         SECItem contextItem = { siBuffer, context, sizeof(context) };
2411 
2412         rv = PK11_GenerateRandom(context, sizeof(context));
2413         if (rv != SECSuccess) {
2414             goto loser;
2415         }
2416 
2417         SECITEM_FreeItem(&ss->xtnData.certReqContext, PR_FALSE);
2418         rv = SECITEM_CopyItem(NULL, &ss->xtnData.certReqContext, &contextItem);
2419         if (rv != SECSuccess) {
2420             FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
2421             goto loser;
2422         }
2423 
2424         offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf);
2425     }
2426 
2427     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request,
2428                                     1 + /* request context length */
2429                                         ss->xtnData.certReqContext.len +
2430                                         2 + /* extension length */
2431                                         SSL_BUFFER_LEN(&extensionBuf));
2432     if (rv != SECSuccess) {
2433         goto loser; /* err set by AppendHandshake. */
2434     }
2435 
2436     /* Context. */
2437     rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.certReqContext.data,
2438                                       ss->xtnData.certReqContext.len, 1);
2439     if (rv != SECSuccess) {
2440         goto loser; /* err set by AppendHandshake. */
2441     }
2442     /* Extensions. */
2443     rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensionBuf, 2);
2444     if (rv != SECSuccess) {
2445         goto loser; /* err set by AppendHandshake. */
2446     }
2447 
2448     if (ss->firstHsDone) {
2449         rv = ssl3_UpdatePostHandshakeHashes(ss,
2450                                             SSL_BUFFER_BASE(&ss->sec.ci.sendBuf) + offset,
2451                                             SSL_BUFFER_LEN(&ss->sec.ci.sendBuf) - offset);
2452         if (rv != SECSuccess) {
2453             goto loser;
2454         }
2455     }
2456 
2457     sslBuffer_Clear(&extensionBuf);
2458     return SECSuccess;
2459 
2460 loser:
2461     sslBuffer_Clear(&extensionBuf);
2462     return SECFailure;
2463 }
2464 
2465 /* [draft-ietf-tls-tls13; S 4.4.1] says:
2466  *
2467  *     Transcript-Hash(ClientHello1, HelloRetryRequest, ... MN) =
2468  *      Hash(message_hash ||        // Handshake type
2469  *           00 00 Hash.length ||   // Handshake message length
2470  *           Hash(ClientHello1) ||  // Hash of ClientHello1
2471  *           HelloRetryRequest ... MN)
2472  *
2473  *  For an ECH handshake, the process occurs for the outer
2474  *  transcript in |ss->ssl3.hs.messages| and the inner
2475  *  transcript in |ss->ssl3.hs.echInnerMessages|.
2476  */
2477 static SECStatus
2478 tls13_ReinjectHandshakeTranscript(sslSocket *ss)
2479 {
2480     SSL3Hashes hashes;
2481     SSL3Hashes echInnerHashes;
2482     SECStatus rv;
2483 
2484     /* First compute the hash. */
2485     rv = tls13_ComputeHash(ss, &hashes,
2486                            ss->ssl3.hs.messages.buf,
2487                            ss->ssl3.hs.messages.len,
2488                            tls13_GetHash(ss));
2489     if (rv != SECSuccess) {
2490         return SECFailure;
2491     }
2492 
2493     if (ss->ssl3.hs.echHpkeCtx) {
2494         rv = tls13_ComputeHash(ss, &echInnerHashes,
2495                                ss->ssl3.hs.echInnerMessages.buf,
2496                                ss->ssl3.hs.echInnerMessages.len,
2497                                tls13_GetHash(ss));
2498         if (rv != SECSuccess) {
2499             return SECFailure;
2500         }
2501     }
2502 
2503     ssl3_RestartHandshakeHashes(ss);
2504 
2505     /* Reinject the message. The Default context variant updates
2506      * the default hash state. Use it for both non-ECH and ECH Outer. */
2507     rv = ssl_HashHandshakeMessageDefault(ss, ssl_hs_message_hash,
2508                                          hashes.u.raw, hashes.len);
2509     if (rv != SECSuccess) {
2510         return SECFailure;
2511     }
2512 
2513     if (ss->ssl3.hs.echHpkeCtx) {
2514         rv = ssl_HashHandshakeMessageEchInner(ss, ssl_hs_message_hash,
2515                                               echInnerHashes.u.raw,
2516                                               echInnerHashes.len);
2517         if (rv != SECSuccess) {
2518             return SECFailure;
2519         }
2520     }
2521 
2522     return SECSuccess;
2523 }
2524 static unsigned int
2525 ssl_ListCount(PRCList *list)
2526 {
2527     unsigned int c = 0;
2528     PRCList *cur;
2529     for (cur = PR_NEXT_LINK(list); cur != list; cur = PR_NEXT_LINK(cur)) {
2530         ++c;
2531     }
2532     return c;
2533 }
2534 
2535 /*
2536  * savedMsg contains the HelloRetryRequest message. When its extensions are parsed
2537  * in ssl3_HandleParsedExtensions, the handler for ECH HRR extensions (tls13_ClientHandleHrrEchXtn)
2538  * will take a reference into the message buffer.
2539  *
2540  * This reference is then used in tls13_MaybeHandleEchSignal in order to compute
2541  * the transcript for the ECH signal calculation. This was felt to be preferable
2542  * to re-parsing the HelloRetryRequest message in order to create the transcript.
2543  *
2544  * Consequently, savedMsg should not be moved or mutated between these
2545  * function calls.
2546  */
2547 SECStatus
2548 tls13_HandleHelloRetryRequest(sslSocket *ss, const PRUint8 *savedMsg,
2549                               PRUint32 savedLength)
2550 {
2551     SECStatus rv;
2552 
2553     SSL_TRC(3, ("%d: TLS13[%d]: handle hello retry request",
2554                 SSL_GETPID(), ss->fd));
2555 
2556     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
2557     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2558 
2559     if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
2560         FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST,
2561                     unexpected_message);
2562         return SECFailure;
2563     }
2564     PORT_Assert(ss->ssl3.hs.ws == wait_server_hello);
2565 
2566     if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
2567         ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
2568         /* Restore the null cipher spec for writing. */
2569         ssl_GetSpecWriteLock(ss);
2570         ssl_CipherSpecRelease(ss->ssl3.cwSpec);
2571         ss->ssl3.cwSpec = ssl_FindCipherSpecByEpoch(ss, ssl_secret_write,
2572                                                     TrafficKeyClearText);
2573         PORT_Assert(ss->ssl3.cwSpec);
2574         ssl_ReleaseSpecWriteLock(ss);
2575     } else {
2576         PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none);
2577     }
2578     /* Set the spec version, because we want to send CH now with 0303 */
2579     tls13_SetSpecRecordVersion(ss, ss->ssl3.cwSpec);
2580 
2581     /* Extensions must contain more than just supported_versions.  This will
2582      * ensure that a HelloRetryRequest isn't a no-op: we must have at least two
2583      * extensions, supported_versions plus one other.  That other must be one
2584      * that we understand and recognize as being valid for HelloRetryRequest,
2585      * and should alter our next Client Hello. */
2586     unsigned int requiredExtensions = 1;
2587     /* The ECH HRR extension is a no-op from the client's perspective. */
2588     if (ss->xtnData.ech) {
2589         requiredExtensions++;
2590     }
2591     if (ssl_ListCount(&ss->ssl3.hs.remoteExtensions) <= requiredExtensions) {
2592         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST,
2593                     decode_error);
2594         return SECFailure;
2595     }
2596 
2597     rv = ssl3_HandleParsedExtensions(ss, ssl_hs_hello_retry_request);
2598     ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
2599     if (rv != SECSuccess) {
2600         return SECFailure; /* Error code set below */
2601     }
2602     rv = tls13_MaybeHandleEchSignal(ss, savedMsg, savedLength, PR_TRUE);
2603     if (rv != SECSuccess) {
2604         return SECFailure;
2605     }
2606     ss->ssl3.hs.helloRetry = PR_TRUE;
2607     rv = tls13_ReinjectHandshakeTranscript(ss);
2608     if (rv != SECSuccess) {
2609         return rv;
2610     }
2611 
2612     rv = ssl_HashHandshakeMessage(ss, ssl_hs_server_hello,
2613                                   savedMsg, savedLength);
2614     if (rv != SECSuccess) {
2615         return SECFailure;
2616     }
2617 
2618     ssl_GetXmitBufLock(ss);
2619     if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss) &&
2620         ss->ssl3.hs.zeroRttState == ssl_0rtt_none) {
2621         rv = ssl3_SendChangeCipherSpecsInt(ss);
2622         if (rv != SECSuccess) {
2623             goto loser;
2624         }
2625     }
2626 
2627     rv = ssl3_SendClientHello(ss, client_hello_retry);
2628     if (rv != SECSuccess) {
2629         goto loser;
2630     }
2631 
2632     ssl_ReleaseXmitBufLock(ss);
2633     return SECSuccess;
2634 
2635 loser:
2636     ssl_ReleaseXmitBufLock(ss);
2637     return SECFailure;
2638 }
2639 
2640 static SECStatus
2641 tls13_HandleCertificateRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
2642 {
2643     SECStatus rv;
2644     SECItem context = { siBuffer, NULL, 0 };
2645     SECItem extensionsData = { siBuffer, NULL, 0 };
2646 
2647     SSL_TRC(3, ("%d: TLS13[%d]: handle certificate_request sequence",
2648                 SSL_GETPID(), ss->fd));
2649 
2650     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
2651     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2652 
2653     /* Client */
2654     if (ss->opt.enablePostHandshakeAuth) {
2655         rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST,
2656                                   wait_cert_request, idle_handshake);
2657     } else {
2658         rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST,
2659                                   wait_cert_request);
2660     }
2661     if (rv != SECSuccess) {
2662         return SECFailure;
2663     }
2664 
2665     /*  MUST NOT combine external PSKs with certificate authentication. */
2666     if (ss->sec.authType == ssl_auth_psk) {
2667         FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST, unexpected_message);
2668         return SECFailure;
2669     }
2670 
2671     if (tls13_IsPostHandshake(ss)) {
2672         PORT_Assert(ss->ssl3.hs.shaPostHandshake == NULL);
2673         ss->ssl3.hs.shaPostHandshake = PK11_CloneContext(ss->ssl3.hs.sha);
2674         if (ss->ssl3.hs.shaPostHandshake == NULL) {
2675             ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
2676             return SECFailure;
2677         }
2678         rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate_request, b, length);
2679         if (rv != SECSuccess) {
2680             FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2681             return SECFailure;
2682         }
2683 
2684         /* clean up anything left from previous handshake. */
2685         if (ss->ssl3.clientCertChain != NULL) {
2686             CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
2687             ss->ssl3.clientCertChain = NULL;
2688         }
2689         if (ss->ssl3.clientCertificate != NULL) {
2690             CERT_DestroyCertificate(ss->ssl3.clientCertificate);
2691             ss->ssl3.clientCertificate = NULL;
2692         }
2693         if (ss->ssl3.clientPrivateKey != NULL) {
2694             SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
2695             ss->ssl3.clientPrivateKey = NULL;
2696         }
2697         SECITEM_FreeItem(&ss->xtnData.certReqContext, PR_FALSE);
2698         ss->xtnData.certReqContext.data = NULL;
2699     } else {
2700         PORT_Assert(ss->ssl3.clientCertChain == NULL);
2701         PORT_Assert(ss->ssl3.clientCertificate == NULL);
2702         PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
2703         PORT_Assert(!ss->ssl3.hs.clientCertRequested);
2704         PORT_Assert(ss->xtnData.certReqContext.data == NULL);
2705     }
2706 
2707     rv = ssl3_ConsumeHandshakeVariable(ss, &context, 1, &b, &length);
2708     if (rv != SECSuccess) {
2709         return SECFailure;
2710     }
2711 
2712     /* Unless it is a post-handshake client auth, the certificate
2713      * request context must be empty. */
2714     if (!tls13_IsPostHandshake(ss) && context.len > 0) {
2715         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST, illegal_parameter);
2716         return SECFailure;
2717     }
2718 
2719     rv = ssl3_ConsumeHandshakeVariable(ss, &extensionsData, 2, &b, &length);
2720     if (rv != SECSuccess) {
2721         return SECFailure;
2722     }
2723 
2724     if (length) {
2725         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST, decode_error);
2726         return SECFailure;
2727     }
2728 
2729     /* Process all the extensions. */
2730     rv = ssl3_HandleExtensions(ss, &extensionsData.data, &extensionsData.len,
2731                                ssl_hs_certificate_request);
2732     if (rv != SECSuccess) {
2733         return SECFailure;
2734     }
2735 
2736     if (!ss->xtnData.numSigSchemes) {
2737         FATAL_ERROR(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION,
2738                     missing_extension);
2739         return SECFailure;
2740     }
2741 
2742     rv = SECITEM_CopyItem(NULL, &ss->xtnData.certReqContext, &context);
2743     if (rv != SECSuccess) {
2744         return SECFailure;
2745     }
2746 
2747     ss->ssl3.hs.clientCertRequested = PR_TRUE;
2748 
2749     if (ss->firstHsDone) {
2750         SSL3AlertDescription sendAlert = no_alert;
2751 
2752         /* Request a client certificate. */
2753         rv = ssl3_CompleteHandleCertificateRequest(
2754             ss, ss->xtnData.sigSchemes, ss->xtnData.numSigSchemes,
2755             &ss->xtnData.certReqAuthorities);
2756         if (rv != SECSuccess) {
2757             FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
2758             return rv;
2759         }
2760 
2761         ssl_GetXmitBufLock(ss);
2762         rv = tls13_SendClientSecondFlight(ss, !ss->ssl3.sendEmptyCert,
2763                                           &sendAlert);
2764         ssl_ReleaseXmitBufLock(ss);
2765         if (rv != SECSuccess) {
2766             if (sendAlert != no_alert) {
2767                 FATAL_ERROR(ss, PORT_GetError(), sendAlert);
2768             } else {
2769                 LOG_ERROR(ss, PORT_GetError());
2770             }
2771             return SECFailure;
2772         }
2773         PORT_Assert(ss->ssl3.hs.ws == idle_handshake);
2774         PORT_Assert(ss->ssl3.hs.shaPostHandshake != NULL);
2775         PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
2776         ss->ssl3.hs.shaPostHandshake = NULL;
2777     } else {
2778         TLS13_SET_HS_STATE(ss, wait_server_cert);
2779     }
2780     return SECSuccess;
2781 }
2782 
2783 PRBool
2784 tls13_ShouldRequestClientAuth(sslSocket *ss)
2785 {
2786     /* Even if we are configured to request a certificate, we can't
2787      * if this handshake used a PSK, even when we are resuming. */
2788     return ss->opt.requestCertificate &&
2789            ss->ssl3.hs.kea_def->authKeyType != ssl_auth_psk;
2790 }
2791 
2792 static SECStatus
2793 tls13_SendEncryptedServerSequence(sslSocket *ss)
2794 {
2795     SECStatus rv;
2796 
2797     rv = tls13_ComputeHandshakeSecrets(ss);
2798     if (rv != SECSuccess) {
2799         return SECFailure; /* error code is set. */
2800     }
2801 
2802     rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
2803                              ssl_secret_write, PR_FALSE);
2804     if (rv != SECSuccess) {
2805         LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
2806         return SECFailure;
2807     }
2808 
2809     if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
2810         rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData,
2811                                           ssl_tls13_early_data_xtn,
2812                                           ssl_SendEmptyExtension);
2813         if (rv != SECSuccess) {
2814             return SECFailure; /* Error code set already. */
2815         }
2816     }
2817 
2818     rv = tls13_SendEncryptedExtensions(ss);
2819     if (rv != SECSuccess) {
2820         return SECFailure; /* error code is set. */
2821     }
2822 
2823     if (tls13_ShouldRequestClientAuth(ss)) {
2824         rv = tls13_SendCertificateRequest(ss);
2825         if (rv != SECSuccess) {
2826             return SECFailure; /* error code is set. */
2827         }
2828     }
2829     if (ss->ssl3.hs.signatureScheme != ssl_sig_none) {
2830         SECKEYPrivateKey *svrPrivKey;
2831 
2832         rv = tls13_SendCertificate(ss);
2833         if (rv != SECSuccess) {
2834             return SECFailure; /* error code is set. */
2835         }
2836 
2837         if (tls13_IsSigningWithDelegatedCredential(ss)) {
2838             SSL_TRC(3, ("%d: TLS13[%d]: Signing with delegated credential",
2839                         SSL_GETPID(), ss->fd));
2840             svrPrivKey = ss->sec.serverCert->delegCredKeyPair->privKey;
2841         } else {
2842             svrPrivKey = ss->sec.serverCert->serverKeyPair->privKey;
2843         }
2844 
2845         rv = tls13_SendCertificateVerify(ss, svrPrivKey);
2846         if (rv != SECSuccess) {
2847             return SECFailure; /* err code is set. */
2848         }
2849     }
2850 
2851     rv = tls13_SendFinished(ss, ss->ssl3.hs.serverHsTrafficSecret);
2852     if (rv != SECSuccess) {
2853         return SECFailure; /* error code is set. */
2854     }
2855 
2856     return SECSuccess;
2857 }
2858 
2859 /* Called from:  ssl3_HandleClientHello */
2860 static SECStatus
2861 tls13_SendServerHelloSequence(sslSocket *ss)
2862 {
2863     SECStatus rv;
2864     PRErrorCode err = 0;
2865 
2866     SSL_TRC(3, ("%d: TLS13[%d]: begin send server_hello sequence",
2867                 SSL_GETPID(), ss->fd));
2868 
2869     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2870     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2871 
2872     rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData,
2873                                       ssl_tls13_supported_versions_xtn,
2874                                       tls13_ServerSendSupportedVersionsXtn);
2875     if (rv != SECSuccess) {
2876         return SECFailure;
2877     }
2878 
2879     rv = tls13_ComputeHandshakeSecret(ss);
2880     if (rv != SECSuccess) {
2881         return SECFailure; /* error code is set. */
2882     }
2883 
2884     rv = ssl3_SendServerHello(ss);
2885     if (rv != SECSuccess) {
2886         return rv; /* err code is set. */
2887     }
2888 
2889     if (ss->ssl3.hs.fakeSid.len) {
2890         PORT_Assert(!IS_DTLS(ss));
2891         SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
2892         if (!ss->ssl3.hs.helloRetry) {
2893             rv = ssl3_SendChangeCipherSpecsInt(ss);
2894             if (rv != SECSuccess) {
2895                 return rv;
2896             }
2897         }
2898     }
2899 
2900     rv = tls13_SendEncryptedServerSequence(ss);
2901     if (rv != SECSuccess) {
2902         err = PORT_GetError();
2903     }
2904     /* Even if we get an error, since the ServerHello was successfully
2905      * serialized, we should give it a chance to reach the network.  This gives
2906      * the client a chance to perform the key exchange and decrypt the alert
2907      * we're about to send. */
2908     rv |= ssl3_FlushHandshake(ss, 0);
2909     if (rv != SECSuccess) {
2910         if (err) {
2911             PORT_SetError(err);
2912         }
2913         return SECFailure;
2914     }
2915 
2916     /* Compute the rest of the secrets except for the resumption
2917      * and exporter secret. */
2918     rv = tls13_ComputeApplicationSecrets(ss);
2919     if (rv != SECSuccess) {
2920         LOG_ERROR(ss, PORT_GetError());
2921         return SECFailure;
2922     }
2923 
2924     rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
2925                              ssl_secret_write, PR_FALSE);
2926     if (rv != SECSuccess) {
2927         LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
2928         return SECFailure;
2929     }
2930 
2931     if (IS_DTLS(ss)) {
2932         /* We need this for reading ACKs. */
2933         ssl_CipherSpecAddRef(ss->ssl3.crSpec);
2934     }
2935     if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
2936         rv = tls13_SetCipherSpec(ss, TrafficKeyEarlyApplicationData,
2937                                  ssl_secret_read, PR_TRUE);
2938         if (rv != SECSuccess) {
2939             LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
2940             return SECFailure;
2941         }
2942         TLS13_SET_HS_STATE(ss, wait_end_of_early_data);
2943     } else {
2944         PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none ||
2945                     ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored);
2946 
2947         rv = tls13_SetCipherSpec(ss,
2948                                  TrafficKeyHandshake,
2949                                  ssl_secret_read, PR_FALSE);
2950         if (rv != SECSuccess) {
2951             LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
2952             return SECFailure;
2953         }
2954         if (tls13_ShouldRequestClientAuth(ss)) {
2955             TLS13_SET_HS_STATE(ss, wait_client_cert);
2956         } else {
2957             TLS13_SET_HS_STATE(ss, wait_finished);
2958         }
2959     }
2960 
2961     /* Here we set a baseline value for our RTT estimation.
2962      * This value is updated when we get a response from the client. */
2963     ss->ssl3.hs.rttEstimate = ssl_Time(ss);
2964     return SECSuccess;
2965 }
2966 
2967 SECStatus
2968 tls13_HandleServerHelloPart2(sslSocket *ss, const PRUint8 *savedMsg, PRUint32 savedLength)
2969 {
2970     SECStatus rv;
2971     sslSessionID *sid = ss->sec.ci.sid;
2972     SSL3Statistics *ssl3stats = SSL_GetStatistics();
2973 
2974     if (ssl3_ExtensionNegotiated(ss, ssl_tls13_pre_shared_key_xtn)) {
2975         PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
2976         PORT_Assert(ss->xtnData.selectedPsk);
2977 
2978         if (ss->xtnData.selectedPsk->type != ssl_psk_resume) {
2979             ss->statelessResume = PR_FALSE;
2980         }
2981     } else {
2982         /* We may have offered a PSK. If the server didn't negotiate
2983          * it, clear this state to re-extract the Early Secret. */
2984         if (ss->ssl3.hs.currentSecret) {
2985             PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn));
2986             PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
2987             ss->ssl3.hs.currentSecret = NULL;
2988         }
2989         ss->statelessResume = PR_FALSE;
2990         ss->xtnData.selectedPsk = NULL;
2991     }
2992 
2993     if (ss->statelessResume) {
2994         PORT_Assert(sid->version >= SSL_LIBRARY_VERSION_TLS_1_3);
2995         if (tls13_GetHash(ss) !=
2996             tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite)) {
2997             FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO,
2998                         illegal_parameter);
2999             return SECFailure;
3000         }
3001     }
3002 
3003     /* Now create a synthetic kea_def that we can tweak. */
3004     ss->ssl3.hs.kea_def_mutable = *ss->ssl3.hs.kea_def;
3005     ss->ssl3.hs.kea_def = &ss->ssl3.hs.kea_def_mutable;
3006 
3007     if (ss->xtnData.selectedPsk) {
3008         ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk;
3009         if (ss->statelessResume) {
3010             tls13_RestoreCipherInfo(ss, sid);
3011             if (sid->peerCert) {
3012                 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
3013             }
3014 
3015             SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_cache_hits);
3016             SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_stateless_resumes);
3017         } else {
3018             ss->sec.authType = ssl_auth_psk;
3019         }
3020     } else {
3021         if (ss->statelessResume &&
3022             ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)) {
3023             SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_cache_misses);
3024         }
3025         if (sid->cached == in_client_cache) {
3026             /* If we tried to resume and failed, let's not try again. */
3027             ssl_UncacheSessionID(ss);
3028         }
3029     }
3030 
3031     /* Discard current SID and make a new one, though it may eventually
3032      * end up looking a lot like the old one.
3033      */
3034     ssl_FreeSID(sid);
3035     ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
3036     if (sid == NULL) {
3037         FATAL_ERROR(ss, PORT_GetError(), internal_error);
3038         return SECFailure;
3039     }
3040     if (ss->statelessResume) {
3041         PORT_Assert(ss->sec.peerCert);
3042         sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
3043     }
3044     sid->version = ss->version;
3045 
3046     rv = tls13_HandleServerKeyShare(ss);
3047     if (rv != SECSuccess) {
3048         return SECFailure;
3049     }
3050 
3051     rv = tls13_ComputeHandshakeSecret(ss);
3052     if (rv != SECSuccess) {
3053         return SECFailure; /* error code is set. */
3054     }
3055 
3056     rv = tls13_MaybeHandleEchSignal(ss, savedMsg, savedLength, PR_FALSE);
3057     if (rv != SECSuccess) {
3058         return SECFailure; /* error code is set. */
3059     }
3060 
3061     rv = tls13_ComputeHandshakeSecrets(ss);
3062     if (rv != SECSuccess) {
3063         return SECFailure; /* error code is set. */
3064     }
3065 
3066     if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
3067         /* When we send 0-RTT, we saved the null spec in case we needed it to
3068          * send another ClientHello in response to a HelloRetryRequest.  Now
3069          * that we won't be receiving a HelloRetryRequest, release the spec. */
3070         ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_write, TrafficKeyClearText);
3071     }
3072 
3073     rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
3074                              ssl_secret_read, PR_FALSE);
3075     if (rv != SECSuccess) {
3076         FATAL_ERROR(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, internal_error);
3077         return SECFailure;
3078     }
3079     TLS13_SET_HS_STATE(ss, wait_encrypted_extensions);
3080 
3081     return SECSuccess;
3082 }
3083 
3084 static void
3085 tls13_SetKeyExchangeType(sslSocket *ss, const sslNamedGroupDef *group)
3086 {
3087     ss->sec.keaGroup = group;
3088     switch (group->keaType) {
3089         /* Note: These overwrite on resumption.... so if you start with ECDH
3090          * and resume with DH, we report DH. That's fine, since no answer
3091          * is really right. */
3092         case ssl_kea_ecdh:
3093             ss->ssl3.hs.kea_def_mutable.exchKeyType =
3094                 ss->statelessResume ? ssl_kea_ecdh_psk : ssl_kea_ecdh;
3095             ss->sec.keaType = ssl_kea_ecdh;
3096             break;
3097         case ssl_kea_dh:
3098             ss->ssl3.hs.kea_def_mutable.exchKeyType =
3099                 ss->statelessResume ? ssl_kea_dh_psk : ssl_kea_dh;
3100             ss->sec.keaType = ssl_kea_dh;
3101             break;
3102         default:
3103             PORT_Assert(0);
3104     }
3105 }
3106 
3107 /*
3108  * Called from ssl3_HandleServerHello.
3109  *
3110  * Caller must hold Handshake and RecvBuf locks.
3111  */
3112 static SECStatus
3113 tls13_HandleServerKeyShare(sslSocket *ss)
3114 {
3115     SECStatus rv;
3116     TLS13KeyShareEntry *entry;
3117     sslEphemeralKeyPair *keyPair;
3118 
3119     SSL_TRC(3, ("%d: TLS13[%d]: handle server_key_share handshake",
3120                 SSL_GETPID(), ss->fd));
3121     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3122     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3123 
3124     /* This list should have one entry. */
3125     if (PR_CLIST_IS_EMPTY(&ss->xtnData.remoteKeyShares)) {
3126         FATAL_ERROR(ss, SSL_ERROR_MISSING_KEY_SHARE, missing_extension);
3127         return SECFailure;
3128     }
3129 
3130     entry = (TLS13KeyShareEntry *)PR_NEXT_LINK(&ss->xtnData.remoteKeyShares);
3131     PORT_Assert(PR_NEXT_LINK(&entry->link) == &ss->xtnData.remoteKeyShares);
3132 
3133     /* Now get our matching key. */
3134     keyPair = ssl_LookupEphemeralKeyPair(ss, entry->group);
3135     if (!keyPair) {
3136         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_SHARE, illegal_parameter);
3137         return SECFailure;
3138     }
3139 
3140     PORT_Assert(ssl_NamedGroupEnabled(ss, entry->group));
3141 
3142     rv = tls13_HandleKeyShare(ss, entry, keyPair->keys,
3143                               tls13_GetHash(ss),
3144                               &ss->ssl3.hs.dheSecret);
3145     if (rv != SECSuccess)
3146         return SECFailure; /* Error code set by caller. */
3147 
3148     tls13_SetKeyExchangeType(ss, entry->group);
3149     ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->keys->pubKey);
3150 
3151     return SECSuccess;
3152 }
3153 
3154 /*
3155  *    opaque ASN1Cert<1..2^24-1>;
3156  *
3157  *    struct {
3158  *        ASN1Cert cert_data;
3159  *        Extension extensions<0..2^16-1>;
3160  *    } CertificateEntry;
3161  *
3162  *    struct {
3163  *        opaque certificate_request_context<0..2^8-1>;
3164  *        CertificateEntry certificate_list<0..2^24-1>;
3165  *    } Certificate;
3166  */
3167 static SECStatus
3168 tls13_SendCertificate(sslSocket *ss)
3169 {
3170     SECStatus rv;
3171     CERTCertificateList *certChain;
3172     int certChainLen = 0;
3173     int i;
3174     SECItem context = { siBuffer, NULL, 0 };
3175     sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
3176 
3177     SSL_TRC(3, ("%d: TLS1.3[%d]: send certificate handshake",
3178                 SSL_GETPID(), ss->fd));
3179 
3180     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3181     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3182 
3183     if (ss->sec.isServer) {
3184         PORT_Assert(!ss->sec.localCert);
3185         /* A server certificate is selected in tls13_SelectServerCert(). */
3186         PORT_Assert(ss->sec.serverCert);
3187 
3188         certChain = ss->sec.serverCert->serverCertChain;
3189         ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
3190     } else {
3191         if (ss->sec.localCert)
3192             CERT_DestroyCertificate(ss->sec.localCert);
3193 
3194         certChain = ss->ssl3.clientCertChain;
3195         ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
3196     }
3197 
3198     if (!ss->sec.isServer) {
3199         PORT_Assert(ss->ssl3.hs.clientCertRequested);
3200         context = ss->xtnData.certReqContext;
3201     }
3202     if (certChain) {
3203         for (i = 0; i < certChain->len; i++) {
3204             /* Each cert is 3 octet length, cert, and extensions */
3205             certChainLen += 3 + certChain->certs[i].len + 2;
3206         }
3207 
3208         /* Build the extensions. This only applies to the leaf cert, because we
3209          * don't yet send extensions for non-leaf certs. */
3210         rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_certificate);
3211         if (rv != SECSuccess) {
3212             return SECFailure; /* code already set */
3213         }
3214         /* extensionBuf.len is only added once, for the leaf cert. */
3215         certChainLen += SSL_BUFFER_LEN(&extensionBuf);
3216     }
3217 
3218     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate,
3219                                     1 + context.len + 3 + certChainLen);
3220     if (rv != SECSuccess) {
3221         return SECFailure; /* err set by AppendHandshake. */
3222     }
3223 
3224     rv = ssl3_AppendHandshakeVariable(ss, context.data,
3225                                       context.len, 1);
3226     if (rv != SECSuccess) {
3227         goto loser; /* err set by AppendHandshake. */
3228     }
3229 
3230     rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3);
3231     if (rv != SECSuccess) {
3232         goto loser; /* err set by AppendHandshake. */
3233     }
3234     if (certChain) {
3235         for (i = 0; i < certChain->len; i++) {
3236             rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
3237                                               certChain->certs[i].len, 3);
3238             if (rv != SECSuccess) {
3239                 goto loser; /* err set by AppendHandshake. */
3240             }
3241 
3242             if (i) {
3243                 /* Not end-entity. */
3244                 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
3245                 if (rv != SECSuccess) {
3246                     goto loser; /* err set by AppendHandshake. */
3247                 }
3248                 continue;
3249             }
3250 
3251             /* End-entity, send extensions. */
3252             rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensionBuf, 2);
3253             if (rv != SECSuccess) {
3254                 goto loser; /* err set by AppendHandshake. */
3255             }
3256         }
3257     }
3258 
3259     sslBuffer_Clear(&extensionBuf);
3260     return SECSuccess;
3261 
3262 loser:
3263     sslBuffer_Clear(&extensionBuf);
3264     return SECFailure;
3265 }
3266 
3267 static SECStatus
3268 tls13_HandleCertificateEntry(sslSocket *ss, SECItem *data, PRBool first,
3269                              CERTCertificate **certp)
3270 {
3271     SECStatus rv;
3272     SECItem certData;
3273     SECItem extensionsData;
3274     CERTCertificate *cert = NULL;
3275 
3276     rv = ssl3_ConsumeHandshakeVariable(ss, &certData,
3277                                        3, &data->data, &data->len);
3278     if (rv != SECSuccess) {
3279         return SECFailure;
3280     }
3281 
3282     rv = ssl3_ConsumeHandshakeVariable(ss, &extensionsData,
3283                                        2, &data->data, &data->len);
3284     if (rv != SECSuccess) {
3285         return SECFailure;
3286     }
3287 
3288     /* Parse all the extensions. */
3289     if (first && !ss->sec.isServer) {
3290         rv = ssl3_HandleExtensions(ss, &extensionsData.data,
3291                                    &extensionsData.len,
3292                                    ssl_hs_certificate);
3293         if (rv != SECSuccess) {
3294             return SECFailure;
3295         }
3296 
3297         /* TODO(ekr@rtfm.com): Copy out SCTs. Bug 1315727. */
3298     }
3299 
3300     cert = CERT_NewTempCertificate(ss->dbHandle, &certData, NULL,
3301                                    PR_FALSE, PR_TRUE);
3302 
3303     if (!cert) {
3304         PRErrorCode errCode = PORT_GetError();
3305         switch (errCode) {
3306             case PR_OUT_OF_MEMORY_ERROR:
3307             case SEC_ERROR_BAD_DATABASE:
3308             case SEC_ERROR_NO_MEMORY:
3309                 FATAL_ERROR(ss, errCode, internal_error);
3310                 return SECFailure;
3311             default:
3312                 ssl3_SendAlertForCertError(ss, errCode);
3313                 return SECFailure;
3314         }
3315     }
3316 
3317     *certp = cert;
3318 
3319     return SECSuccess;
3320 }
3321 
3322 /* Called from tls13_CompleteHandleHandshakeMessage() when it has deciphered a complete
3323  * tls13 Certificate message.
3324  * Caller must hold Handshake and RecvBuf locks.
3325  */
3326 static SECStatus
3327 tls13_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
3328 {
3329     SECStatus rv;
3330     SECItem context = { siBuffer, NULL, 0 };
3331     SECItem certList;
3332     PRBool first = PR_TRUE;
3333     ssl3CertNode *lastCert = NULL;
3334 
3335     SSL_TRC(3, ("%d: TLS13[%d]: handle certificate handshake",
3336                 SSL_GETPID(), ss->fd));
3337     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3338     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3339 
3340     if (ss->sec.isServer) {
3341         /* Receiving this message might be the first sign we have that
3342          * early data is over, so pretend we received EOED. */
3343         rv = tls13_MaybeHandleSuppressedEndOfEarlyData(ss);
3344         if (rv != SECSuccess) {
3345             return SECFailure; /* Code already set. */
3346         }
3347 
3348         if (ss->ssl3.clientCertRequested) {
3349             rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,
3350                                       idle_handshake);
3351         } else {
3352             rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,
3353                                       wait_client_cert);
3354         }
3355     } else {
3356         rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,
3357                                   wait_cert_request, wait_server_cert);
3358     }
3359     if (rv != SECSuccess) {
3360         return SECFailure;
3361     }
3362 
3363     /* We can ignore any other cleartext from the client. */
3364     if (ss->sec.isServer && IS_DTLS(ss)) {
3365         ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read, TrafficKeyClearText);
3366         dtls_ReceivedFirstMessageInFlight(ss);
3367     }
3368 
3369     if (ss->firstHsDone) {
3370         rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate, b, length);
3371         if (rv != SECSuccess) {
3372             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3373             return SECFailure;
3374         }
3375     } else if (ss->sec.isServer) {
3376         /* Our first shot an getting an RTT estimate.  If the client took extra
3377          * time to fetch a certificate, this will be bad, but we can't do much
3378          * about that. */
3379         ss->ssl3.hs.rttEstimate = ssl_Time(ss) - ss->ssl3.hs.rttEstimate;
3380     }
3381 
3382     /* Process the context string */
3383     rv = ssl3_ConsumeHandshakeVariable(ss, &context, 1, &b, &length);
3384     if (rv != SECSuccess)
3385         return SECFailure;
3386 
3387     if (ss->ssl3.clientCertRequested) {
3388         PORT_Assert(ss->sec.isServer);
3389         if (SECITEM_CompareItem(&context, &ss->xtnData.certReqContext) != 0) {
3390             FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, illegal_parameter);
3391             return SECFailure;
3392         }
3393     }
3394 
3395     rv = ssl3_ConsumeHandshakeVariable(ss, &certList, 3, &b, &length);
3396     if (rv != SECSuccess) {
3397         return SECFailure;
3398     }
3399     if (length) {
3400         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, illegal_parameter);
3401         return SECFailure;
3402     }
3403 
3404     if (!certList.len) {
3405         if (!ss->sec.isServer) {
3406             /* Servers always need to send some cert. */
3407             FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate);
3408             return SECFailure;
3409         } else {
3410             /* This is TLS's version of a no_certificate alert. */
3411             /* I'm a server. I've requested a client cert. He hasn't got one. */
3412             rv = ssl3_HandleNoCertificate(ss);
3413             if (rv != SECSuccess) {
3414                 return SECFailure;
3415             }
3416 
3417             TLS13_SET_HS_STATE(ss, wait_finished);
3418             return SECSuccess;
3419         }
3420     }
3421 
3422     /* Now clean up. */
3423     ssl3_CleanupPeerCerts(ss);
3424     ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
3425     if (ss->ssl3.peerCertArena == NULL) {
3426         FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
3427         return SECFailure;
3428     }
3429 
3430     while (certList.len) {
3431         CERTCertificate *cert;
3432 
3433         rv = tls13_HandleCertificateEntry(ss, &certList, first,
3434                                           &cert);
3435         if (rv != SECSuccess) {
3436             ss->xtnData.signedCertTimestamps.len = 0;
3437             return SECFailure;
3438         }
3439 
3440         if (first) {
3441             ss->sec.peerCert = cert;
3442 
3443             if (ss->xtnData.signedCertTimestamps.len) {
3444                 sslSessionID *sid = ss->sec.ci.sid;
3445                 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps,
3446                                       &ss->xtnData.signedCertTimestamps);
3447                 ss->xtnData.signedCertTimestamps.len = 0;
3448                 if (rv != SECSuccess) {
3449                     FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
3450                     return SECFailure;
3451                 }
3452             }
3453         } else {
3454             ssl3CertNode *c = PORT_ArenaNew(ss->ssl3.peerCertArena,
3455                                             ssl3CertNode);
3456             if (!c) {
3457                 FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
3458                 return SECFailure;
3459             }
3460             c->cert = cert;
3461             c->next = NULL;
3462 
3463             if (lastCert) {
3464                 lastCert->next = c;
3465             } else {
3466                 ss->ssl3.peerCertChain = c;
3467             }
3468             lastCert = c;
3469         }
3470 
3471         first = PR_FALSE;
3472     }
3473     SECKEY_UpdateCertPQG(ss->sec.peerCert);
3474 
3475     return ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
3476 }
3477 
3478 /* Add context to the hash functions as described in
3479    [draft-ietf-tls-tls13; Section 4.9.1] */
3480 SECStatus
3481 tls13_AddContextToHashes(sslSocket *ss, const SSL3Hashes *hashes,
3482                          SSLHashType algorithm, PRBool sending,
3483                          SSL3Hashes *tbsHash)
3484 {
3485     SECStatus rv = SECSuccess;
3486     PK11Context *ctx;
3487     const unsigned char context_padding[] = {
3488         0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
3489         0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
3490         0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
3491         0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
3492         0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
3493         0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
3494         0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
3495         0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
3496     };
3497 
3498     const char *client_cert_verify_string = "TLS 1.3, client CertificateVerify";
3499     const char *server_cert_verify_string = "TLS 1.3, server CertificateVerify";
3500     const char *context_string = (sending ^ ss->sec.isServer) ? client_cert_verify_string
3501                                                               : server_cert_verify_string;
3502     unsigned int hashlength;
3503 
3504     /* Double check that we are doing the same hash.*/
3505     PORT_Assert(hashes->len == tls13_GetHashSize(ss));
3506 
3507     ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(algorithm));
3508     if (!ctx) {
3509         PORT_SetError(SEC_ERROR_NO_MEMORY);
3510         goto loser;
3511     }
3512 
3513     PORT_Assert(SECFailure);
3514     PORT_Assert(!SECSuccess);
3515 
3516     PRINT_BUF(50, (ss, "TLS 1.3 hash without context", hashes->u.raw, hashes->len));
3517     PRINT_BUF(50, (ss, "Context string", context_string, strlen(context_string)));
3518     rv |= PK11_DigestBegin(ctx);
3519     rv |= PK11_DigestOp(ctx, context_padding, sizeof(context_padding));
3520     rv |= PK11_DigestOp(ctx, (unsigned char *)context_string,
3521                         strlen(context_string) + 1); /* +1 includes the terminating 0 */
3522     rv |= PK11_DigestOp(ctx, hashes->u.raw, hashes->len);
3523     /* Update the hash in-place */
3524     rv |= PK11_DigestFinal(ctx, tbsHash->u.raw, &hashlength, sizeof(tbsHash->u.raw));
3525     PK11_DestroyContext(ctx, PR_TRUE);
3526     PRINT_BUF(50, (ss, "TLS 1.3 hash with context", tbsHash->u.raw, hashlength));
3527 
3528     tbsHash->len = hashlength;
3529     tbsHash->hashAlg = algorithm;
3530 
3531     if (rv) {
3532         ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3533         goto loser;
3534     }
3535     return SECSuccess;
3536 
3537 loser:
3538     return SECFailure;
3539 }
3540 
3541 /*
3542  *    Derive-Secret(Secret, Label, Messages) =
3543  *       HKDF-Expand-Label(Secret, Label,
3544  *                         Hash(Messages) + Hash(resumption_context), L))
3545  */
3546 SECStatus
3547 tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key,
3548                    const char *label,
3549                    unsigned int labelLen,
3550                    const SSL3Hashes *hashes,
3551                    PK11SymKey **dest,
3552                    SSLHashType hash)
3553 {
3554     SECStatus rv;
3555 
3556     rv = tls13_HkdfExpandLabel(key, hash, hashes->u.raw, hashes->len,
3557                                label, labelLen, CKM_HKDF_DERIVE,
3558                                tls13_GetHashSizeForHash(hash),
3559                                ss->protocolVariant, dest);
3560     if (rv != SECSuccess) {
3561         LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
3562         return SECFailure;
3563     }
3564     return SECSuccess;
3565 }
3566 
3567 /* Convenience wrapper for the empty hash. */
3568 SECStatus
3569 tls13_DeriveSecretNullHash(sslSocket *ss, PK11SymKey *key,
3570                            const char *label,
3571                            unsigned int labelLen,
3572                            PK11SymKey **dest,
3573                            SSLHashType hash)
3574 {
3575     SSL3Hashes hashes;
3576     SECStatus rv;
3577     PRUint8 buf[] = { 0 };
3578 
3579     rv = tls13_ComputeHash(ss, &hashes, buf, 0, hash);
3580     if (rv != SECSuccess) {
3581         return SECFailure;
3582     }
3583 
3584     return tls13_DeriveSecret(ss, key, label, labelLen, &hashes, dest, hash);
3585 }
3586 
3587 /* Convenience wrapper that lets us supply a separate prefix and suffix. */
3588 static SECStatus
3589 tls13_DeriveSecretWrap(sslSocket *ss, PK11SymKey *key,
3590                        const char *prefix,
3591                        const char *suffix,
3592                        const char *keylogLabel,
3593                        PK11SymKey **dest)
3594 {
3595     SECStatus rv;
3596     SSL3Hashes hashes;
3597     char buf[100];
3598     const char *label;
3599 
3600     if (prefix) {
3601         if ((strlen(prefix) + strlen(suffix) + 2) > sizeof(buf)) {
3602             PORT_Assert(0);
3603             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3604             return SECFailure;
3605         }
3606         (void)PR_snprintf(buf, sizeof(buf), "%s %s",
3607                           prefix, suffix);
3608         label = buf;
3609     } else {
3610         label = suffix;
3611     }
3612 
3613     SSL_TRC(3, ("%d: TLS13[%d]: deriving secret '%s'",
3614                 SSL_GETPID(), ss->fd, label));
3615     rv = tls13_ComputeHandshakeHashes(ss, &hashes);
3616     if (rv != SECSuccess) {
3617         PORT_Assert(0); /* Should never fail */
3618         ssl_MapLowLevelError(SEC_ERROR_LIBRARY_FAILURE);
3619         return SECFailure;
3620     }
3621 
3622     rv = tls13_DeriveSecret(ss, key, label, strlen(label),
3623                             &hashes, dest, tls13_GetHash(ss));
3624     if (rv != SECSuccess) {
3625         return SECFailure;
3626     }
3627 
3628     if (keylogLabel) {
3629         ssl3_RecordKeyLog(ss, keylogLabel, *dest);
3630     }
3631     return SECSuccess;
3632 }
3633 
3634 SECStatus
3635 SSLExp_SecretCallback(PRFileDesc *fd, SSLSecretCallback cb, void *arg)
3636 {
3637     sslSocket *ss = ssl_FindSocket(fd);
3638     if (!ss) {
3639         SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SecretCallback",
3640                  SSL_GETPID(), fd));
3641         return SECFailure;
3642     }
3643 
3644     ssl_Get1stHandshakeLock(ss);
3645     ssl_GetSSL3HandshakeLock(ss);
3646     ss->secretCallback = cb;
3647     ss->secretCallbackArg = arg;
3648     ssl_ReleaseSSL3HandshakeLock(ss);
3649     ssl_Release1stHandshakeLock(ss);
3650     return SECSuccess;
3651 }
3652 
3653 /* Derive traffic keys for the next cipher spec in the queue. */
3654 static SECStatus
3655 tls13_DeriveTrafficKeys(sslSocket *ss, ssl3CipherSpec *spec,
3656                         TrafficKeyType type,
3657                         PRBool deleteSecret)
3658 {
3659     size_t keySize = spec->cipherDef->key_size;
3660     size_t ivSize = spec->cipherDef->iv_size +
3661                     spec->cipherDef->explicit_nonce_size; /* This isn't always going to
3662                                                            * work, but it does for
3663                                                            * AES-GCM */
3664     CK_MECHANISM_TYPE bulkAlgorithm = ssl3_Alg2Mech(spec->cipherDef->calg);
3665     PK11SymKey **prkp = NULL;
3666     PK11SymKey *prk = NULL;
3667     PRBool clientSecret;
3668     SECStatus rv;
3669     /* These labels are just used for debugging. */
3670     static const char kHkdfPhaseEarlyApplicationDataKeys[] = "early application data";
3671     static const char kHkdfPhaseHandshakeKeys[] = "handshake data";
3672     static const char kHkdfPhaseApplicationDataKeys[] = "application data";
3673 
3674     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3675 
3676     clientSecret = !tls13_UseServerSecret(ss, spec->direction);
3677     switch (type) {
3678         case TrafficKeyEarlyApplicationData:
3679             PORT_Assert(clientSecret);
3680             prkp = &ss->ssl3.hs.clientEarlyTrafficSecret;
3681             spec->phase = kHkdfPhaseEarlyApplicationDataKeys;
3682             break;
3683         case TrafficKeyHandshake:
3684             prkp = clientSecret ? &ss->ssl3.hs.clientHsTrafficSecret
3685                                 : &ss->ssl3.hs.serverHsTrafficSecret;
3686             spec->phase = kHkdfPhaseHandshakeKeys;
3687             break;
3688         case TrafficKeyApplicationData:
3689             prkp = clientSecret ? &ss->ssl3.hs.clientTrafficSecret
3690                                 : &ss->ssl3.hs.serverTrafficSecret;
3691             spec->phase = kHkdfPhaseApplicationDataKeys;
3692             break;
3693         default:
3694             LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
3695             PORT_Assert(0);
3696             return SECFailure;
3697     }
3698     PORT_Assert(prkp != NULL);
3699     prk = *prkp;
3700 
3701     SSL_TRC(3, ("%d: TLS13[%d]: deriving %s traffic keys epoch=%d (%s)",
3702                 SSL_GETPID(), ss->fd, SPEC_DIR(spec),
3703                 spec->epoch, spec->phase));
3704 
3705     rv = tls13_HkdfExpandLabel(prk, tls13_GetHash(ss),
3706                                NULL, 0,
3707                                kHkdfPurposeKey, strlen(kHkdfPurposeKey),
3708                                bulkAlgorithm, keySize,
3709                                ss->protocolVariant,
3710                                &spec->keyMaterial.key);
3711     if (rv != SECSuccess) {
3712         LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
3713         PORT_Assert(0);
3714         goto loser;
3715     }
3716 
3717     if (IS_DTLS(ss) && spec->epoch > 0) {
3718         rv = ssl_CreateMaskingContextInner(spec->version, ss->ssl3.hs.cipher_suite,
3719                                            ss->protocolVariant, prk, kHkdfPurposeSn,
3720                                            strlen(kHkdfPurposeSn), &spec->maskContext);
3721         if (rv != SECSuccess) {
3722             LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
3723             PORT_Assert(0);
3724             goto loser;
3725         }
3726     }
3727 
3728     rv = tls13_HkdfExpandLabelRaw(prk, tls13_GetHash(ss),
3729                                   NULL, 0,
3730                                   kHkdfPurposeIv, strlen(kHkdfPurposeIv),
3731                                   ss->protocolVariant,
3732                                   spec->keyMaterial.iv, ivSize);
3733     if (rv != SECSuccess) {
3734         LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
3735         PORT_Assert(0);
3736         goto loser;
3737     }
3738 
3739     if (deleteSecret) {
3740         PK11_FreeSymKey(prk);
3741         *prkp = NULL;
3742     }
3743     return SECSuccess;
3744 
3745 loser:
3746     return SECFailure;
3747 }
3748 
3749 void
3750 tls13_SetSpecRecordVersion(sslSocket *ss, ssl3CipherSpec *spec)
3751 {
3752     /* Set the record version to pretend to be (D)TLS 1.2. */
3753     if (IS_DTLS(ss)) {
3754         spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_2_WIRE;
3755     } else {
3756         spec->recordVersion = SSL_LIBRARY_VERSION_TLS_1_2;
3757     }
3758     SSL_TRC(10, ("%d: TLS13[%d]: set spec=%d record version to 0x%04x",
3759                  SSL_GETPID(), ss->fd, spec, spec->recordVersion));
3760 }
3761 
3762 static SECStatus
3763 tls13_SetupPendingCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
3764 {
3765     ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
3766 
3767     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3768     PORT_Assert(spec->epoch);
3769 
3770     /* Version isn't set when we send 0-RTT data. */
3771     spec->version = PR_MAX(SSL_LIBRARY_VERSION_TLS_1_3, ss->version);
3772 
3773     ssl_SaveCipherSpec(ss, spec);
3774     /* We want to keep read cipher specs around longer because
3775      * there are cases where we might get either epoch N or
3776      * epoch N+1. */
3777     if (IS_DTLS(ss) && spec->direction == ssl_secret_read) {
3778         ssl_CipherSpecAddRef(spec);
3779     }
3780 
3781     SSL_TRC(3, ("%d: TLS13[%d]: Set Pending Cipher Suite to 0x%04x",
3782                 SSL_GETPID(), ss->fd, suite));
3783 
3784     spec->cipherDef = ssl_GetBulkCipherDef(ssl_LookupCipherSuiteDef(suite));
3785 
3786     if (spec->epoch == TrafficKeyEarlyApplicationData) {
3787         if (ss->xtnData.selectedPsk &&
3788             ss->xtnData.selectedPsk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL) {
3789             spec->earlyDataRemaining = ss->xtnData.selectedPsk->maxEarlyData;
3790         }
3791     }
3792 
3793     tls13_SetSpecRecordVersion(ss, spec);
3794 
3795     /* The record size limit is reduced by one so that the remainder of the
3796      * record handling code can use the same checks for all versions. */
3797     if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) {
3798         spec->recordSizeLimit = ((spec->direction == ssl_secret_read)
3799                                      ? ss->opt.recordSizeLimit
3800                                      : ss->xtnData.recordSizeLimit) -
3801                                 1;
3802     } else {
3803         spec->recordSizeLimit = MAX_FRAGMENT_LENGTH;
3804     }
3805     return SECSuccess;
3806 }
3807 
3808 /*
3809  * Initialize the cipher context. All TLS 1.3 operations are AEAD,
3810  * so they are all message contexts.
3811  */
3812 static SECStatus
3813 tls13_InitPendingContext(sslSocket *ss, ssl3CipherSpec *spec)
3814 {
3815     CK_MECHANISM_TYPE encMechanism;
3816     CK_ATTRIBUTE_TYPE encMode;
3817     SECItem iv;
3818     SSLCipherAlgorithm calg;
3819 
3820     calg = spec->cipherDef->calg;
3821 
3822     encMechanism = ssl3_Alg2Mech(calg);
3823     encMode = CKA_NSS_MESSAGE | ((spec->direction == ssl_secret_write) ? CKA_ENCRYPT : CKA_DECRYPT);
3824     iv.data = NULL;
3825     iv.len = 0;
3826 
3827     /*
3828      * build the context
3829      */
3830     spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode,
3831                                                      spec->keyMaterial.key,
3832                                                      &iv);
3833     if (!spec->cipherContext) {
3834         ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
3835         return SECFailure;
3836     }
3837     return SECSuccess;
3838 }
3839 
3840 /*
3841  * Called before sending alerts to set up the right key on the client.
3842  * We might encounter errors during the handshake where the current
3843  * key is ClearText or EarlyApplicationData. This
3844  * function switches to the Handshake key if possible.
3845  */
3846 SECStatus
3847 tls13_SetAlertCipherSpec(sslSocket *ss)
3848 {
3849     SECStatus rv;
3850 
3851     if (ss->sec.isServer) {
3852         return SECSuccess;
3853     }
3854     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
3855         return SECSuccess;
3856     }
3857     if (TLS13_IN_HS_STATE(ss, wait_server_hello)) {
3858         return SECSuccess;
3859     }
3860     if ((ss->ssl3.cwSpec->epoch != TrafficKeyClearText) &&
3861         (ss->ssl3.cwSpec->epoch != TrafficKeyEarlyApplicationData)) {
3862         return SECSuccess;
3863     }
3864 
3865     rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
3866                              ssl_secret_write, PR_FALSE);
3867     if (rv != SECSuccess) {
3868         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3869         return SECFailure;
3870     }
3871     return SECSuccess;
3872 }
3873 
3874 /* Install a new cipher spec for this direction.
3875  *
3876  * During the handshake, the values for |epoch| take values from the
3877  * TrafficKeyType enum.  Afterwards, key update increments them.
3878  */
3879 static SECStatus
3880 tls13_SetCipherSpec(sslSocket *ss, PRUint16 epoch,
3881                     SSLSecretDirection direction, PRBool deleteSecret)
3882 {
3883     TrafficKeyType type;
3884     SECStatus rv;
3885     ssl3CipherSpec *spec = NULL;
3886     ssl3CipherSpec **specp;
3887 
3888     /* Flush out old handshake data. */
3889     ssl_GetXmitBufLock(ss);
3890     rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3891     ssl_ReleaseXmitBufLock(ss);
3892     if (rv != SECSuccess) {
3893         return SECFailure;
3894     }
3895 
3896     /* Create the new spec. */
3897     spec = ssl_CreateCipherSpec(ss, direction);
3898     if (!spec) {
3899         return SECFailure;
3900     }
3901     spec->epoch = epoch;
3902     spec->nextSeqNum = 0;
3903     if (IS_DTLS(ss)) {
3904         dtls_InitRecvdRecords(&spec->recvdRecords);
3905     }
3906 
3907     /* This depends on spec having a valid direction and epoch. */
3908     rv = tls13_SetupPendingCipherSpec(ss, spec);
3909     if (rv != SECSuccess) {
3910         goto loser;
3911     }
3912 
3913     type = (TrafficKeyType)PR_MIN(TrafficKeyApplicationData, epoch);
3914     rv = tls13_DeriveTrafficKeys(ss, spec, type, deleteSecret);
3915     if (rv != SECSuccess) {
3916         goto loser;
3917     }
3918 
3919     rv = tls13_InitPendingContext(ss, spec);
3920     if (rv != SECSuccess) {
3921         goto loser;
3922     }
3923 
3924     /* Now that we've set almost everything up, finally cut over. */
3925     specp = (direction == ssl_secret_read) ? &ss->ssl3.crSpec : &ss->ssl3.cwSpec;
3926     ssl_GetSpecWriteLock(ss);
3927     ssl_CipherSpecRelease(*specp); /* May delete old cipher. */
3928     *specp = spec;                 /* Overwrite. */
3929     ssl_ReleaseSpecWriteLock(ss);
3930 
3931     SSL_TRC(3, ("%d: TLS13[%d]: %s installed key for epoch=%d (%s) dir=%s",
3932                 SSL_GETPID(), ss->fd, SSL_ROLE(ss), spec->epoch,
3933                 spec->phase, SPEC_DIR(spec)));
3934     return SECSuccess;
3935 
3936 loser:
3937     ssl_CipherSpecRelease(spec);
3938     return SECFailure;
3939 }
3940 
3941 SECStatus
3942 tls13_ComputeHandshakeHashes(sslSocket *ss, SSL3Hashes *hashes)
3943 {
3944     SECStatus rv;
3945     PK11Context *ctx = NULL;
3946     PRBool useEchInner;
3947     sslBuffer *transcript;
3948 
3949     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3950     if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
3951         /* Backup: if we haven't done any hashing, then hash now.
3952          * This happens when we are doing 0-RTT on the client. */
3953         ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(tls13_GetHash(ss)));
3954         if (!ctx) {
3955             ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3956             return SECFailure;
3957         }
3958 
3959         if (PK11_DigestBegin(ctx) != SECSuccess) {
3960             ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3961             goto loser;
3962         }
3963 
3964         /* One might expect this to use ss->ssl3.hs.echAccepted,
3965          * but with 0-RTT we don't know that yet. */
3966         useEchInner = ss->sec.isServer ? PR_FALSE : !!ss->ssl3.hs.echHpkeCtx;
3967         transcript = useEchInner ? &ss->ssl3.hs.echInnerMessages : &ss->ssl3.hs.messages;
3968 
3969         PRINT_BUF(10, (ss, "Handshake hash computed over saved messages",
3970                        transcript->buf,
3971                        transcript->len));
3972 
3973         if (PK11_DigestOp(ctx,
3974                           transcript->buf,
3975                           transcript->len) != SECSuccess) {
3976             ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3977             goto loser;
3978         }
3979     } else {
3980         if (ss->firstHsDone) {
3981             ctx = PK11_CloneContext(ss->ssl3.hs.shaPostHandshake);
3982         } else {
3983             ctx = PK11_CloneContext(ss->ssl3.hs.sha);
3984         }
3985         if (!ctx) {
3986             ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3987             return SECFailure;
3988         }
3989     }
3990 
3991     rv = PK11_DigestFinal(ctx, hashes->u.raw,
3992                           &hashes->len,
3993                           sizeof(hashes->u.raw));
3994     if (rv != SECSuccess) {
3995         ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3996         goto loser;
3997     }
3998 
3999     PRINT_BUF(10, (ss, "Handshake hash", hashes->u.raw, hashes->len));
4000     PORT_Assert(hashes->len == tls13_GetHashSize(ss));
4001     PK11_DestroyContext(ctx, PR_TRUE);
4002 
4003     return SECSuccess;
4004 
4005 loser:
4006     PK11_DestroyContext(ctx, PR_TRUE);
4007     return SECFailure;
4008 }
4009 
4010 TLS13KeyShareEntry *
4011 tls13_CopyKeyShareEntry(TLS13KeyShareEntry *o)
4012 {
4013     TLS13KeyShareEntry *n;
4014 
4015     PORT_Assert(o);
4016     n = PORT_ZNew(TLS13KeyShareEntry);
4017     if (!n) {
4018         return NULL;
4019     }
4020 
4021     if (SECSuccess != SECITEM_CopyItem(NULL, &n->key_exchange, &o->key_exchange)) {
4022         PORT_Free(n);
4023         return NULL;
4024     }
4025     n->group = o->group;
4026     return n;
4027 }
4028 
4029 void
4030 tls13_DestroyKeyShareEntry(TLS13KeyShareEntry *offer)
4031 {
4032     if (!offer) {
4033         return;
4034     }
4035     SECITEM_ZfreeItem(&offer->key_exchange, PR_FALSE);
4036     PORT_ZFree(offer, sizeof(*offer));
4037 }
4038 
4039 void
4040 tls13_DestroyKeyShares(PRCList *list)
4041 {
4042     PRCList *cur_p;
4043 
4044     /* The list must be initialized. */
4045     PORT_Assert(PR_LIST_HEAD(list));
4046 
4047     while (!PR_CLIST_IS_EMPTY(list)) {
4048         cur_p = PR_LIST_TAIL(list);
4049         PR_REMOVE_LINK(cur_p);
4050         tls13_DestroyKeyShareEntry((TLS13KeyShareEntry *)cur_p);
4051     }
4052 }
4053 
4054 void
4055 tls13_DestroyEarlyData(PRCList *list)
4056 {
4057     PRCList *cur_p;
4058 
4059     while (!PR_CLIST_IS_EMPTY(list)) {
4060         TLS13EarlyData *msg;
4061 
4062         cur_p = PR_LIST_TAIL(list);
4063         msg = (TLS13EarlyData *)cur_p;
4064 
4065         PR_REMOVE_LINK(cur_p);
4066         SECITEM_ZfreeItem(&msg->data, PR_FALSE);
4067         PORT_ZFree(msg, sizeof(*msg));
4068     }
4069 }
4070 
4071 /* draft-ietf-tls-tls13 Section 5.2.2 specifies the following
4072  * nonce algorithm:
4073  *
4074  * The length of the per-record nonce (iv_length) is set to max(8 bytes,
4075  * N_MIN) for the AEAD algorithm (see [RFC5116] Section 4).  An AEAD
4076  * algorithm where N_MAX is less than 8 bytes MUST NOT be used with TLS.
4077  * The per-record nonce for the AEAD construction is formed as follows:
4078  *
4079  * 1.  The 64-bit record sequence number is padded to the left with
4080  *     zeroes to iv_length.
4081  *
4082  * 2.  The padded sequence number is XORed with the static
4083  *     client_write_iv or server_write_iv, depending on the role.
4084  *
4085  * The resulting quantity (of length iv_length) is used as the per-
4086  * record nonce.
4087  *
4088  * Existing suites have the same nonce size: N_MIN = N_MAX = 12 bytes
4089  *
4090  * See RFC 5288 and https://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305-04#section-2
4091  */
4092 static void
4093 tls13_WriteNonce(const unsigned char *ivIn, unsigned int ivInLen,
4094                  const unsigned char *nonce, unsigned int nonceLen,
4095                  unsigned char *ivOut, unsigned int ivOutLen)
4096 {
4097     size_t i;
4098     unsigned int offset = ivOutLen - nonceLen;
4099 
4100     PORT_Assert(ivInLen <= ivOutLen);
4101     PORT_Assert(nonceLen <= ivOutLen);
4102     PORT_Memset(ivOut, 0, ivOutLen);
4103     PORT_Memcpy(ivOut, ivIn, ivInLen);
4104 
4105     /* XOR the last n bytes of the IV with the nonce (should be a counter). */
4106     for (i = 0; i < nonceLen; ++i) {
4107         ivOut[offset + i] ^= nonce[i];
4108     }
4109     PRINT_BUF(50, (NULL, "Nonce", ivOut, ivOutLen));
4110 }
4111 
4112 /* Setup the IV for AEAD encrypt. The PKCS #11 module will add the
4113  * counter, but it doesn't know about the DTLS epic, so we add it here.
4114  */
4115 unsigned int
4116 tls13_SetupAeadIv(PRBool isDTLS, unsigned char *ivOut, unsigned char *ivIn,
4117                   unsigned int offset, unsigned int ivLen, DTLSEpoch epoch)
4118 {
4119     PORT_Memcpy(ivOut, ivIn, ivLen);
4120     if (isDTLS) {
4121         /* handle the tls 1.2 counter mode case, the epoc is copied
4122          * instead of xored. We accomplish this by clearing ivOut
4123          * before running xor. */
4124         if (offset >= ivLen) {
4125             ivOut[offset] = ivOut[offset + 1] = 0;
4126         }
4127         ivOut[offset] ^= (unsigned char)(epoch >> BPB) & 0xff;
4128         ivOut[offset + 1] ^= (unsigned char)(epoch)&0xff;
4129         offset += 2;
4130     }
4131     return offset;
4132 }
4133 
4134 /*
4135  * Do a single AEAD for TLS. This differs from PK11_AEADOp in the following
4136  * ways.
4137  *   1) If context is not supplied, it treats the operation as a single shot
4138  *   and creates a context from symKey and mech.
4139  *   2) It always assumes the tag will be at the end of the buffer
4140  *   (in on decrypt, out on encrypt) just like the old single shot.
4141  *   3) If we aren't generating an IV, it uses tls13_WriteNonce to create the
4142  *   nonce.
4143  * NOTE is context is supplied, symKey and mech are ignored
4144  */
4145 SECStatus
4146 tls13_AEAD(PK11Context *context, PRBool decrypt,
4147            CK_GENERATOR_FUNCTION ivGen, unsigned int fixedbits,
4148            const unsigned char *ivIn, unsigned char *ivOut, unsigned int ivLen,
4149            const unsigned char *nonceIn, unsigned int nonceLen,
4150            const unsigned char *aad, unsigned int aadLen,
4151            unsigned char *out, unsigned int *outLen, unsigned int maxout,
4152            unsigned int tagLen, const unsigned char *in, unsigned int inLen)
4153 {
4154     unsigned char *tag;
4155     unsigned char iv[MAX_IV_LENGTH];
4156     unsigned char tagbuf[HASH_LENGTH_MAX];
4157     SECStatus rv;
4158 
4159     /* must have either context or the symKey set */
4160     if (!context) {
4161         PORT_SetError(SEC_ERROR_INVALID_ARGS);
4162         return SECFailure;
4163     }
4164 
4165     PORT_Assert(ivLen <= MAX_IV_LENGTH);
4166     PORT_Assert(tagLen <= HASH_LENGTH_MAX);
4167     if (!ivOut) {
4168         ivOut = iv; /* caller doesn't need a returned, iv */
4169     }
4170 
4171     if (ivGen == CKG_NO_GENERATE) {
4172         tls13_WriteNonce(ivIn, ivLen, nonceIn, nonceLen, ivOut, ivLen);
4173     } else if (ivIn != ivOut) {
4174         PORT_Memcpy(ivOut, ivIn, ivLen);
4175     }
4176     if (decrypt) {
4177         inLen = inLen - tagLen;
4178         tag = (unsigned char *)in + inLen;
4179         /* tag is const on decrypt, but returned on encrypt */
4180     } else {
4181         /* tag is written to a separate buffer, then added to the end
4182          * of the actual output buffer. This allows output buffer to be larger
4183          * than the input buffer and everything still work */
4184         tag = tagbuf;
4185     }
4186     rv = PK11_AEADOp(context, ivGen, fixedbits, ivOut, ivLen, aad, aadLen,
4187                      out, (int *)outLen, maxout, tag, tagLen, in, inLen);
4188     /* on encrypt SSL always puts the tag at the end of the buffer */
4189     if ((rv == SECSuccess) && !(decrypt)) {
4190         unsigned int len = *outLen;
4191         /* make sure there is still space */
4192         if (len + tagLen > maxout) {
4193             PORT_SetError(SEC_ERROR_OUTPUT_LEN);
4194             return SECFailure;
4195         }
4196         PORT_Memcpy(out + len, tag, tagLen);
4197         *outLen += tagLen;
4198     }
4199     return rv;
4200 }
4201 
4202 static SECStatus
4203 tls13_HandleEncryptedExtensions(sslSocket *ss, PRUint8 *b, PRUint32 length)
4204 {
4205     SECStatus rv;
4206     PRUint32 innerLength;
4207     SECItem oldAlpn = { siBuffer, NULL, 0 };
4208 
4209     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4210     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4211 
4212     SSL_TRC(3, ("%d: TLS13[%d]: handle encrypted extensions",
4213                 SSL_GETPID(), ss->fd));
4214 
4215     rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS,
4216                               wait_encrypted_extensions);
4217     if (rv != SECSuccess) {
4218         return SECFailure;
4219     }
4220 
4221     rv = ssl3_ConsumeHandshakeNumber(ss, &innerLength, 2, &b, &length);
4222     if (rv != SECSuccess) {
4223         return SECFailure; /* Alert already sent. */
4224     }
4225     if (innerLength != length) {
4226         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
4227                     illegal_parameter);
4228         return SECFailure;
4229     }
4230 
4231     /* If we are doing 0-RTT, then we already have an ALPN value. Stash
4232      * it for comparison. */
4233     if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent &&
4234         ss->xtnData.nextProtoState == SSL_NEXT_PROTO_EARLY_VALUE) {
4235         oldAlpn = ss->xtnData.nextProto;
4236         ss->xtnData.nextProto.data = NULL;
4237         ss->xtnData.nextProtoState = SSL_NEXT_PROTO_NO_SUPPORT;
4238     }
4239 
4240     rv = ssl3_ParseExtensions(ss, &b, &length);
4241     if (rv != SECSuccess) {
4242         return SECFailure; /* Error code set below */
4243     }
4244 
4245     /* Handle the rest of the extensions. */
4246     rv = ssl3_HandleParsedExtensions(ss, ssl_hs_encrypted_extensions);
4247     if (rv != SECSuccess) {
4248         return SECFailure; /* Error code set below */
4249     }
4250 
4251     /* We can only get here if we offered 0-RTT. */
4252     if (ssl3_ExtensionNegotiated(ss, ssl_tls13_early_data_xtn)) {
4253         PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_sent);
4254         if (!ss->xtnData.selectedPsk) {
4255             /* Illegal to accept 0-RTT without also accepting PSK. */
4256             FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
4257                         illegal_parameter);
4258         }
4259         ss->ssl3.hs.zeroRttState = ssl_0rtt_accepted;
4260 
4261         /* Check that the server negotiated the same ALPN (if any). */
4262         if (SECITEM_CompareItem(&oldAlpn, &ss->xtnData.nextProto)) {
4263             SECITEM_FreeItem(&oldAlpn, PR_FALSE);
4264             FATAL_ERROR(ss, SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID,
4265                         illegal_parameter);
4266             return SECFailure;
4267         }
4268         /* Check that the server negotiated the same cipher suite. */
4269         if (ss->ssl3.hs.cipher_suite != ss->ssl3.hs.zeroRttSuite) {
4270             FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
4271                         illegal_parameter);
4272             return SECFailure;
4273         }
4274     } else if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
4275         /* Though we sent 0-RTT, the early_data extension wasn't present so the
4276          * state is unmodified; the server must have rejected 0-RTT. */
4277         ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
4278         ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
4279     } else {
4280         PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none ||
4281                     (ss->ssl3.hs.helloRetry &&
4282                      ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored));
4283     }
4284 
4285     SECITEM_FreeItem(&oldAlpn, PR_FALSE);
4286     if (ss->ssl3.hs.kea_def->authKeyType == ssl_auth_psk) {
4287         TLS13_SET_HS_STATE(ss, wait_finished);
4288     } else {
4289         TLS13_SET_HS_STATE(ss, wait_cert_request);
4290     }
4291 
4292     /* Client is done with any PSKs */
4293     tls13_DestroyPskList(&ss->ssl3.hs.psks);
4294     ss->xtnData.selectedPsk = NULL;
4295 
4296     return SECSuccess;
4297 }
4298 
4299 static SECStatus
4300 tls13_SendEncryptedExtensions(sslSocket *ss)
4301 {
4302     sslBuffer extensions = SSL_BUFFER_EMPTY;
4303     SECStatus rv;
4304 
4305     SSL_TRC(3, ("%d: TLS13[%d]: send encrypted extensions handshake",
4306                 SSL_GETPID(), ss->fd));
4307 
4308     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4309     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
4310 
4311     rv = ssl_ConstructExtensions(ss, &extensions, ssl_hs_encrypted_extensions);
4312     if (rv != SECSuccess) {
4313         return SECFailure;
4314     }
4315 
4316     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_encrypted_extensions,
4317                                     SSL_BUFFER_LEN(&extensions) + 2);
4318     if (rv != SECSuccess) {
4319         LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
4320         goto loser;
4321     }
4322     rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensions, 2);
4323     if (rv != SECSuccess) {
4324         LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
4325         goto loser;
4326     }
4327     sslBuffer_Clear(&extensions);
4328     return SECSuccess;
4329 
4330 loser:
4331     sslBuffer_Clear(&extensions);
4332     return SECFailure;
4333 }
4334 
4335 SECStatus
4336 tls13_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
4337 {
4338     SECStatus rv = SECFailure;
4339     SECItem buf = { siBuffer, NULL, 0 };
4340     unsigned int len;
4341     SSLHashType hashAlg;
4342     SSL3Hashes hash;
4343     SSL3Hashes tbsHash; /* The hash "to be signed". */
4344 
4345     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
4346     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4347 
4348     SSL_TRC(3, ("%d: TLS13[%d]: send certificate_verify handshake",
4349                 SSL_GETPID(), ss->fd));
4350 
4351     PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single);
4352     rv = tls13_ComputeHandshakeHashes(ss, &hash);
4353     if (rv != SECSuccess) {
4354         return SECFailure;
4355     }
4356 
4357     /* We should have picked a signature scheme when we received a
4358      * CertificateRequest, or when we picked a server certificate. */
4359     PORT_Assert(ss->ssl3.hs.signatureScheme != ssl_sig_none);
4360     if (ss->ssl3.hs.signatureScheme == ssl_sig_none) {
4361         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4362         return SECFailure;
4363     }
4364     hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
4365     rv = tls13_AddContextToHashes(ss, &hash, hashAlg,
4366                                   PR_TRUE, &tbsHash);
4367     if (rv != SECSuccess) {
4368         return SECFailure;
4369     }
4370 
4371     rv = ssl3_SignHashes(ss, &tbsHash, privKey, &buf);
4372     if (rv == SECSuccess && !ss->sec.isServer) {
4373         /* Remember the info about the slot that did the signing.
4374          * Later, when doing an SSL restart handshake, verify this.
4375          * These calls are mere accessors, and can't fail.
4376          */
4377         PK11SlotInfo *slot;
4378         sslSessionID *sid = ss->sec.ci.sid;
4379 
4380         slot = PK11_GetSlotFromPrivateKey(privKey);
4381         sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
4382         sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
4383         sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
4384         sid->u.ssl3.clAuthValid = PR_TRUE;
4385         PK11_FreeSlot(slot);
4386     }
4387     if (rv != SECSuccess) {
4388         goto done; /* err code was set by ssl3_SignHashes */
4389     }
4390 
4391     len = buf.len + 2 + 2;
4392 
4393     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len);
4394     if (rv != SECSuccess) {
4395         goto done; /* error code set by AppendHandshake */
4396     }
4397 
4398     rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
4399     if (rv != SECSuccess) {
4400         goto done; /* err set by AppendHandshakeNumber */
4401     }
4402 
4403     rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
4404     if (rv != SECSuccess) {
4405         goto done; /* error code set by AppendHandshake */
4406     }
4407 
4408 done:
4409     /* For parity with the allocation functions, which don't use
4410      * SECITEM_AllocItem(). */
4411     if (buf.data)
4412         PORT_Free(buf.data);
4413     return rv;
4414 }
4415 
4416 /* Called from tls13_CompleteHandleHandshakeMessage() when it has deciphered a complete
4417  * tls13 CertificateVerify message
4418  * Caller must hold Handshake and RecvBuf locks.
4419  */
4420 SECStatus
4421 tls13_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
4422 {
4423     sslDelegatedCredential *dc = ss->xtnData.peerDelegCred;
4424     CERTSubjectPublicKeyInfo *spki;
4425     SECKEYPublicKey *pubKey = NULL;
4426     SECItem signed_hash = { siBuffer, NULL, 0 };
4427     SECStatus rv;
4428     SSLSignatureScheme sigScheme;
4429     SSLHashType hashAlg;
4430     SSL3Hashes tbsHash;
4431     SSL3Hashes hashes;
4432 
4433     SSL_TRC(3, ("%d: TLS13[%d]: handle certificate_verify handshake",
4434                 SSL_GETPID(), ss->fd));
4435     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4436     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4437 
4438     rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY,
4439                               wait_cert_verify);
4440     if (rv != SECSuccess) {
4441         return SECFailure;
4442     }
4443 
4444     rv = tls13_ComputeHandshakeHashes(ss, &hashes);
4445     if (rv != SECSuccess) {
4446         return SECFailure;
4447     }
4448 
4449     if (ss->firstHsDone) {
4450         rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate_verify, b, length);
4451     } else {
4452         rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify, b, length);
4453     }
4454     if (rv != SECSuccess) {
4455         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4456         return SECFailure;
4457     }
4458 
4459     rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
4460     if (rv != SECSuccess) {
4461         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY, illegal_parameter);
4462         return SECFailure;
4463     }
4464 
4465     /* Set the |spki| used to verify the handshake. When verifying with a
4466      * delegated credential (DC), this corresponds to the DC public key;
4467      * otherwise it correspond to the public key of the peer's end-entity
4468      * certificate.
4469      */
4470     if (tls13_IsVerifyingWithDelegatedCredential(ss)) {
4471         /* DelegatedCredential.cred.expected_cert_verify_algorithm is expected
4472          * to match CertificateVerify.scheme.
4473          * DelegatedCredential.cred.expected_cert_verify_algorithm must also be
4474          * the same as was reported in ssl3_AuthCertificate.
4475          */
4476         if (sigScheme != dc->expectedCertVerifyAlg || sigScheme != ss->sec.signatureScheme) {
4477             FATAL_ERROR(ss, SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH, illegal_parameter);
4478             return SECFailure;
4479         }
4480 
4481         /* Verify the DC has three steps: (1) use the peer's end-entity
4482          * certificate to verify DelegatedCredential.signature, (2) check that
4483          * the certificate has the correct key usage, and (3) check that the DC
4484          * hasn't expired.
4485          */
4486         rv = tls13_VerifyDelegatedCredential(ss, dc);
4487         if (rv != SECSuccess) { /* Calls FATAL_ERROR() */
4488             return SECFailure;
4489         }
4490 
4491         SSL_TRC(3, ("%d: TLS13[%d]: Verifying with delegated credential",
4492                     SSL_GETPID(), ss->fd));
4493         spki = dc->spki;
4494     } else {
4495         spki = &ss->sec.peerCert->subjectPublicKeyInfo;
4496     }
4497 
4498     rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme, spki);
4499     if (rv != SECSuccess) {
4500         /* Error set already */
4501         FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
4502         return SECFailure;
4503     }
4504     hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
4505 
4506     rv = tls13_AddContextToHashes(ss, &hashes, hashAlg, PR_FALSE, &tbsHash);
4507     if (rv != SECSuccess) {
4508         FATAL_ERROR(ss, SSL_ERROR_DIGEST_FAILURE, internal_error);
4509         return SECFailure;
4510     }
4511 
4512     rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
4513     if (rv != SECSuccess) {
4514         PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_VERIFY);
4515         return SECFailure;
4516     }
4517 
4518     if (length != 0) {
4519         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY, decode_error);
4520         return SECFailure;
4521     }
4522 
4523     pubKey = SECKEY_ExtractPublicKey(spki);
4524     if (pubKey == NULL) {
4525         ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
4526         return SECFailure;
4527     }
4528 
4529     rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, sigScheme,
4530                                           &tbsHash, &signed_hash);
4531     if (rv != SECSuccess) {
4532         FATAL_ERROR(ss, PORT_GetError(), decrypt_error);
4533         goto loser;
4534     }
4535 
4536     /* Set the auth type and verify it is what we captured in ssl3_AuthCertificate */
4537     if (!ss->sec.isServer) {
4538         ss->sec.authType = ssl_SignatureSchemeToAuthType(sigScheme);
4539 
4540         uint32_t prelimAuthKeyBits = ss->sec.authKeyBits;
4541         rv = ssl_SetAuthKeyBits(ss, pubKey);
4542         if (rv != SECSuccess) {
4543             goto loser; /* Alert sent and code set. */
4544         }
4545 
4546         if (prelimAuthKeyBits != ss->sec.authKeyBits) {
4547             FATAL_ERROR(ss, SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH, illegal_parameter);
4548             goto loser;
4549         }
4550     }
4551 
4552     /* Request a client certificate now if one was requested. */
4553     if (ss->ssl3.hs.clientCertRequested) {
4554         PORT_Assert(!ss->sec.isServer);
4555         rv = ssl3_CompleteHandleCertificateRequest(
4556             ss, ss->xtnData.sigSchemes, ss->xtnData.numSigSchemes,
4557             &ss->xtnData.certReqAuthorities);
4558         if (rv != SECSuccess) {
4559             FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
4560             goto loser;
4561         }
4562     }
4563 
4564     SECKEY_DestroyPublicKey(pubKey);
4565     TLS13_SET_HS_STATE(ss, wait_finished);
4566     return SECSuccess;
4567 
4568 loser:
4569     SECKEY_DestroyPublicKey(pubKey);
4570     return SECFailure;
4571 }
4572 
4573 /* Compute the PSK binder hash over:
4574  * Client HRR prefix, if present in ss->ssl3.hs.messages or ss->ssl3.hs.echInnerMessages,
4575  * |len| bytes of |buf| */
4576 static SECStatus
4577 tls13_ComputePskBinderHash(sslSocket *ss, PRUint8 *b, size_t length,
4578                            SSL3Hashes *hashes, SSLHashType hashType)
4579 {
4580     SECStatus rv;
4581     PK11Context *ctx = NULL;
4582     sslBuffer *clientResidual = NULL;
4583     if (!ss->sec.isServer) {
4584         /* On the server, HRR residual is already buffered. */
4585         clientResidual = ss->ssl3.hs.echHpkeCtx ? &ss->ssl3.hs.echInnerMessages : &ss->ssl3.hs.messages;
4586     }
4587     PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
4588     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4589 
4590     PRINT_BUF(10, (NULL, "Binder computed over ClientHello",
4591                    b, length));
4592 
4593     ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(hashType));
4594     if (!ctx) {
4595         goto loser;
4596     }
4597     rv = PK11_DigestBegin(ctx);
4598     if (rv != SECSuccess) {
4599         ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4600         goto loser;
4601     }
4602 
4603     if (clientResidual && clientResidual->len) {
4604         PRINT_BUF(10, (NULL, " with HRR prefix", clientResidual->buf,
4605                        clientResidual->len));
4606         rv = PK11_DigestOp(ctx, clientResidual->buf, clientResidual->len);
4607         if (rv != SECSuccess) {
4608             ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4609             goto loser;
4610         }
4611     }
4612 
4613     rv = PK11_DigestOp(ctx, b, length);
4614     if (rv != SECSuccess) {
4615         ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4616         goto loser;
4617     }
4618     rv = PK11_DigestFinal(ctx, hashes->u.raw, &hashes->len, sizeof(hashes->u.raw));
4619     if (rv != SECSuccess) {
4620         ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4621         goto loser;
4622     }
4623 
4624     PK11_DestroyContext(ctx, PR_TRUE);
4625     PRINT_BUF(10, (NULL, "PSK Binder hash", hashes->u.raw, hashes->len));
4626     return SECSuccess;
4627 
4628 loser:
4629     if (ctx) {
4630         PK11_DestroyContext(ctx, PR_TRUE);
4631     }
4632     return SECFailure;
4633 }
4634 
4635 /* Compute and inject the PSK Binder for sending.
4636  *
4637  * When sending a ClientHello, we construct all the extensions with a dummy
4638  * value for the binder.  To construct the binder, we commit the entire message
4639  * up to the point where the binders start.  Then we calculate the hash using
4640  * the saved message (in ss->ssl3.hs.messages).  This is written over the dummy
4641  * binder, after which we write the remainder of the binder extension. */
4642 SECStatus
4643 tls13_WriteExtensionsWithBinder(sslSocket *ss, sslBuffer *extensions, sslBuffer *chBuf)
4644 {
4645     SSL3Hashes hashes;
4646     SECStatus rv;
4647 
4648     PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
4649     sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
4650     unsigned int size = tls13_GetHashSizeForHash(psk->hash);
4651     unsigned int prefixLen = extensions->len - size - 3;
4652     unsigned int finishedLen;
4653 
4654     PORT_Assert(extensions->len >= size + 3);
4655 
4656     rv = sslBuffer_AppendNumber(chBuf, extensions->len, 2);
4657     if (rv != SECSuccess) {
4658         return SECFailure;
4659     }
4660 
4661     /* Only write the extension up to the point before the binders.  Assume that
4662      * the pre_shared_key extension is at the end of the buffer.  Don't write
4663      * the binder, or the lengths that precede it (a 2 octet length for the list
4664      * of all binders, plus a 1 octet length for the binder length). */
4665     rv = sslBuffer_Append(chBuf, extensions->buf, prefixLen);
4666     if (rv != SECSuccess) {
4667         return SECFailure;
4668     }
4669 
4670     /* Calculate the binder based on what has been written out. */
4671     rv = tls13_ComputePskBinderHash(ss, chBuf->buf, chBuf->len, &hashes, psk->hash);
4672     if (rv != SECSuccess) {
4673         return SECFailure;
4674     }
4675 
4676     /* Write the binder into the extensions buffer, over the zeros we reserved
4677      * previously. This avoids an allocation and means that we don't need a
4678      * separate write for the extra bits that precede the binder. */
4679     PORT_Assert(psk->binderKey);
4680     rv = tls13_ComputeFinished(ss, psk->binderKey,
4681                                psk->hash, &hashes, PR_TRUE,
4682                                extensions->buf + extensions->len - size,
4683                                &finishedLen, size);
4684     if (rv != SECSuccess) {
4685         return SECFailure;
4686     }
4687     PORT_Assert(finishedLen == size);
4688 
4689     /* Write out the remainder of the extension. */
4690     rv = sslBuffer_Append(chBuf, extensions->buf + prefixLen,
4691                           extensions->len - prefixLen);
4692     if (rv != SECSuccess) {
4693         return SECFailure;
4694     }
4695 
4696     return SECSuccess;
4697 }
4698 
4699 static SECStatus
4700 tls13_ComputeFinished(sslSocket *ss, PK11SymKey *baseKey,
4701                       SSLHashType hashType, const SSL3Hashes *hashes,
4702                       PRBool sending, PRUint8 *output, unsigned int *outputLen,
4703                       unsigned int maxOutputLen)
4704 {
4705     SECStatus rv;
4706     PK11Context *hmacCtx = NULL;
4707     CK_MECHANISM_TYPE macAlg = tls13_GetHmacMechanismFromHash(hashType);
4708     SECItem param = { siBuffer, NULL, 0 };
4709     unsigned int outputLenUint;
4710     const char *label = kHkdfLabelFinishedSecret;
4711     PK11SymKey *secret = NULL;
4712 
4713     PORT_Assert(baseKey);
4714     SSL_TRC(3, ("%d: TLS13[%d]: %s calculate finished",
4715                 SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
4716     PRINT_BUF(50, (ss, "Handshake hash", hashes->u.raw, hashes->len));
4717 
4718     /* Now derive the appropriate finished secret from the base secret. */
4719     rv = tls13_HkdfExpandLabel(baseKey, hashType,
4720                                NULL, 0, label, strlen(label),
4721                                tls13_GetHmacMechanismFromHash(hashType),
4722                                tls13_GetHashSizeForHash(hashType),
4723                                ss->protocolVariant, &secret);
4724     if (rv != SECSuccess) {
4725         goto abort;
4726     }
4727 
4728     PORT_Assert(hashes->len == tls13_GetHashSizeForHash(hashType));
4729     hmacCtx = PK11_CreateContextBySymKey(macAlg, CKA_SIGN,
4730                                          secret, &param);
4731     if (!hmacCtx) {
4732         goto abort;
4733     }
4734 
4735     rv = PK11_DigestBegin(hmacCtx);
4736     if (rv != SECSuccess)
4737         goto abort;
4738 
4739     rv = PK11_DigestOp(hmacCtx, hashes->u.raw, hashes->len);
4740     if (rv != SECSuccess)
4741         goto abort;
4742 
4743     PORT_Assert(maxOutputLen >= tls13_GetHashSizeForHash(hashType));
4744     rv = PK11_DigestFinal(hmacCtx, output, &outputLenUint, maxOutputLen);
4745     if (rv != SECSuccess)
4746         goto abort;
4747     *outputLen = outputLenUint;
4748 
4749     PK11_FreeSymKey(secret);
4750     PK11_DestroyContext(hmacCtx, PR_TRUE);
4751     PRINT_BUF(50, (ss, "finished value", output, outputLenUint));
4752     return SECSuccess;
4753 
4754 abort:
4755     if (secret) {
4756         PK11_FreeSymKey(secret);
4757     }
4758 
4759     if (hmacCtx) {
4760         PK11_DestroyContext(hmacCtx, PR_TRUE);
4761     }
4762 
4763     PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4764     return SECFailure;
4765 }
4766 
4767 static SECStatus
4768 tls13_SendFinished(sslSocket *ss, PK11SymKey *baseKey)
4769 {
4770     SECStatus rv;
4771     PRUint8 finishedBuf[TLS13_MAX_FINISHED_SIZE];
4772     unsigned int finishedLen;
4773     SSL3Hashes hashes;
4774 
4775     SSL_TRC(3, ("%d: TLS13[%d]: send finished handshake", SSL_GETPID(), ss->fd));
4776 
4777     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
4778     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4779 
4780     rv = tls13_ComputeHandshakeHashes(ss, &hashes);
4781     if (rv != SECSuccess) {
4782         LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
4783         return SECFailure;
4784     }
4785 
4786     ssl_GetSpecReadLock(ss);
4787     rv = tls13_ComputeFinished(ss, baseKey, tls13_GetHash(ss), &hashes, PR_TRUE,
4788                                finishedBuf, &finishedLen, sizeof(finishedBuf));
4789     ssl_ReleaseSpecReadLock(ss);
4790     if (rv != SECSuccess) {
4791         LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
4792         return SECFailure;
4793     }
4794 
4795     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, finishedLen);
4796     if (rv != SECSuccess) {
4797         return SECFailure; /* Error code already set. */
4798     }
4799 
4800     rv = ssl3_AppendHandshake(ss, finishedBuf, finishedLen);
4801     if (rv != SECSuccess) {
4802         return SECFailure; /* Error code already set. */
4803     }
4804 
4805     /* TODO(ekr@rtfm.com): Record key log */
4806     return SECSuccess;
4807 }
4808 
4809 static SECStatus
4810 tls13_VerifyFinished(sslSocket *ss, SSLHandshakeType message,
4811                      PK11SymKey *secret,
4812                      PRUint8 *b, PRUint32 length,
4813                      const SSL3Hashes *hashes)
4814 {
4815     SECStatus rv;
4816     PRUint8 finishedBuf[TLS13_MAX_FINISHED_SIZE];
4817     unsigned int finishedLen;
4818 
4819     if (!hashes) {
4820         FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
4821         return SECFailure;
4822     }
4823 
4824     rv = tls13_ComputeFinished(ss, secret, tls13_GetHash(ss), hashes, PR_FALSE,
4825                                finishedBuf, &finishedLen, sizeof(finishedBuf));
4826     if (rv != SECSuccess) {
4827         FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
4828         return SECFailure;
4829     }
4830 
4831     if (length != finishedLen) {
4832 #ifndef UNSAFE_FUZZER_MODE
4833         FATAL_ERROR(ss, message == ssl_hs_finished ? SSL_ERROR_RX_MALFORMED_FINISHED : SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
4834         return SECFailure;
4835 #endif
4836     }
4837 
4838     if (NSS_SecureMemcmp(b, finishedBuf, finishedLen) != 0) {
4839 #ifndef UNSAFE_FUZZER_MODE
4840         FATAL_ERROR(ss, SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE,
4841                     decrypt_error);
4842         return SECFailure;
4843 #endif
4844     }
4845 
4846     return SECSuccess;
4847 }
4848 
4849 static SECStatus
4850 tls13_CommonHandleFinished(sslSocket *ss, PK11SymKey *key,
4851                            PRUint8 *b, PRUint32 length)
4852 {
4853     SECStatus rv;
4854     SSL3Hashes hashes;
4855 
4856     rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_FINISHED,
4857                               wait_finished);
4858     if (rv != SECSuccess) {
4859         return SECFailure;
4860     }
4861     ss->ssl3.hs.endOfFlight = PR_TRUE;
4862 
4863     rv = tls13_ComputeHandshakeHashes(ss, &hashes);
4864     if (rv != SECSuccess) {
4865         LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
4866         return SECFailure;
4867     }
4868 
4869     if (ss->firstHsDone) {
4870         rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_finished, b, length);
4871     } else {
4872         rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
4873     }
4874     if (rv != SECSuccess) {
4875         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4876         return SECFailure;
4877     }
4878 
4879     return tls13_VerifyFinished(ss, ssl_hs_finished,
4880                                 key, b, length, &hashes);
4881 }
4882 
4883 static SECStatus
4884 tls13_ClientHandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
4885 {
4886     SECStatus rv;
4887 
4888     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4889     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4890 
4891     SSL_TRC(3, ("%d: TLS13[%d]: client handle finished handshake",
4892                 SSL_GETPID(), ss->fd));
4893 
4894     rv = tls13_CommonHandleFinished(ss, ss->ssl3.hs.serverHsTrafficSecret,
4895                                     b, length);
4896     if (rv != SECSuccess) {
4897         return SECFailure;
4898     }
4899 
4900     return tls13_SendClientSecondRound(ss);
4901 }
4902 
4903 static SECStatus
4904 tls13_ServerHandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
4905 {
4906     SECStatus rv;
4907 
4908     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4909     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4910 
4911     SSL_TRC(3, ("%d: TLS13[%d]: server handle finished handshake",
4912                 SSL_GETPID(), ss->fd));
4913 
4914     if (!tls13_ShouldRequestClientAuth(ss)) {
4915         /* Receiving this message might be the first sign we have that
4916          * early data is over, so pretend we received EOED. */
4917         rv = tls13_MaybeHandleSuppressedEndOfEarlyData(ss);
4918         if (rv != SECSuccess) {
4919             return SECFailure; /* Code already set. */
4920         }
4921 
4922         if (!tls13_IsPostHandshake(ss)) {
4923             /* Finalize the RTT estimate. */
4924             ss->ssl3.hs.rttEstimate = ssl_Time(ss) - ss->ssl3.hs.rttEstimate;
4925         }
4926     }
4927 
4928     rv = tls13_CommonHandleFinished(ss,
4929                                     ss->firstHsDone ? ss->ssl3.hs.clientTrafficSecret : ss->ssl3.hs.clientHsTrafficSecret,
4930                                     b, length);
4931     if (rv != SECSuccess) {
4932         return SECFailure;
4933     }
4934 
4935     if (ss->firstHsDone) {
4936         TLS13_SET_HS_STATE(ss, idle_handshake);
4937 
4938         PORT_Assert(ss->ssl3.hs.shaPostHandshake != NULL);
4939         PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
4940         ss->ssl3.hs.shaPostHandshake = NULL;
4941 
4942         ss->ssl3.clientCertRequested = PR_FALSE;
4943 
4944         if (ss->ssl3.keyUpdateDeferred) {
4945             rv = tls13_SendKeyUpdate(ss, ss->ssl3.deferredKeyUpdateRequest,
4946                                      PR_FALSE);
4947             if (rv != SECSuccess) {
4948                 return SECFailure; /* error is set. */
4949             }
4950             ss->ssl3.keyUpdateDeferred = PR_FALSE;
4951         }
4952 
4953         return SECSuccess;
4954     }
4955 
4956     if (!tls13_ShouldRequestClientAuth(ss) &&
4957         (ss->ssl3.hs.zeroRttState != ssl_0rtt_done)) {
4958         dtls_ReceivedFirstMessageInFlight(ss);
4959     }
4960 
4961     rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
4962                              ssl_secret_read, PR_FALSE);
4963     if (rv != SECSuccess) {
4964         FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
4965         return SECFailure;
4966     }
4967 
4968     if (IS_DTLS(ss)) {
4969         ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read, TrafficKeyClearText);
4970         /* We need to keep the handshake cipher spec so we can
4971          * read re-transmitted client Finished. */
4972         rv = dtls_StartTimer(ss, ss->ssl3.hs.hdTimer,
4973                              DTLS_RETRANSMIT_FINISHED_MS,
4974                              dtls13_HolddownTimerCb);
4975         if (rv != SECSuccess) {
4976             return SECFailure;
4977         }
4978     }
4979 
4980     rv = tls13_ComputeFinalSecrets(ss);
4981     if (rv != SECSuccess) {
4982         return SECFailure;
4983     }
4984 
4985     rv = tls13_FinishHandshake(ss);
4986     if (rv != SECSuccess) {
4987         return SECFailure;
4988     }
4989 
4990     ssl_GetXmitBufLock(ss);
4991     /* If resumption, authType is the original value and not ssl_auth_psk. */
4992     if (ss->opt.enableSessionTickets && ss->sec.authType != ssl_auth_psk) {
4993         rv = tls13_SendNewSessionTicket(ss, NULL, 0);
4994         if (rv != SECSuccess) {
4995             goto loser;
4996         }
4997         rv = ssl3_FlushHandshake(ss, 0);
4998         if (rv != SECSuccess) {
4999             goto loser;
5000         }
5001     }
5002     ssl_ReleaseXmitBufLock(ss);
5003     return SECSuccess;
5004 
5005 loser:
5006     ssl_ReleaseXmitBufLock(ss);
5007     return SECFailure;
5008 }
5009 
5010 static SECStatus
5011 tls13_FinishHandshake(sslSocket *ss)
5012 {
5013     /* If |!echHpkeCtx|, any advertised ECH was GREASE ECH. */
5014     PRBool offeredEch = !ss->sec.isServer && ss->ssl3.hs.echHpkeCtx;
5015     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
5016     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5017     PORT_Assert(ss->ssl3.hs.restartTarget == NULL);
5018 
5019     /* The first handshake is now completed. */
5020     ss->handshake = NULL;
5021 
5022     /* Don't need this. */
5023     PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
5024     ss->ssl3.hs.clientHsTrafficSecret = NULL;
5025     PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
5026     ss->ssl3.hs.serverHsTrafficSecret = NULL;
5027 
5028     TLS13_SET_HS_STATE(ss, idle_handshake);
5029 
5030     PORT_Assert(ss->ssl3.hs.echAccepted ==
5031                 ssl3_ExtensionNegotiated(ss, ssl_tls13_encrypted_client_hello_xtn));
5032     if (offeredEch && !ss->ssl3.hs.echAccepted) {
5033         SSL3_SendAlert(ss, alert_fatal, ech_required);
5034 
5035         /* "If [one, none] of the retry_configs contains a supported version, the client can
5036          * regard ECH as securely [replaced, disabled] by the server." */
5037         if (ss->xtnData.ech && ss->xtnData.ech->retryConfigs.len) {
5038             PORT_SetError(SSL_ERROR_ECH_RETRY_WITH_ECH);
5039             ss->xtnData.ech->retryConfigsValid = PR_TRUE;
5040         } else {
5041             PORT_SetError(SSL_ERROR_ECH_RETRY_WITHOUT_ECH);
5042         }
5043         return SECFailure;
5044     }
5045 
5046     ssl_FinishHandshake(ss);
5047 
5048     return SECSuccess;
5049 }
5050 
5051 /* Do the parts of sending the client's second round that require
5052  * the XmitBuf lock. */
5053 static SECStatus
5054 tls13_SendClientSecondFlight(sslSocket *ss, PRBool sendClientCert,
5055                              SSL3AlertDescription *sendAlert)
5056 {
5057     SECStatus rv;
5058     unsigned int offset = 0;
5059 
5060     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5061 
5062     *sendAlert = internal_error;
5063 
5064     if (ss->firstHsDone) {
5065         offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf);
5066     }
5067 
5068     if (ss->ssl3.sendEmptyCert) {
5069         ss->ssl3.sendEmptyCert = PR_FALSE;
5070         rv = ssl3_SendEmptyCertificate(ss);
5071         /* Don't send verify */
5072         if (rv != SECSuccess) {
5073             return SECFailure; /* error code is set. */
5074         }
5075     } else if (sendClientCert) {
5076         rv = tls13_SendCertificate(ss);
5077         if (rv != SECSuccess) {
5078             return SECFailure; /* error code is set. */
5079         }
5080     }
5081 
5082     if (ss->firstHsDone) {
5083         rv = ssl3_UpdatePostHandshakeHashes(ss,
5084                                             SSL_BUFFER_BASE(&ss->sec.ci.sendBuf) + offset,
5085                                             SSL_BUFFER_LEN(&ss->sec.ci.sendBuf) - offset);
5086         if (rv != SECSuccess) {
5087             return SECFailure; /* error code is set. */
5088         }
5089     }
5090 
5091     if (ss->ssl3.hs.clientCertRequested) {
5092         SECITEM_FreeItem(&ss->xtnData.certReqContext, PR_FALSE);
5093         if (ss->xtnData.certReqAuthorities.arena) {
5094             PORT_FreeArena(ss->xtnData.certReqAuthorities.arena, PR_FALSE);
5095             ss->xtnData.certReqAuthorities.arena = NULL;
5096         }
5097         PORT_Memset(&ss->xtnData.certReqAuthorities, 0,
5098                     sizeof(ss->xtnData.certReqAuthorities));
5099         ss->ssl3.hs.clientCertRequested = PR_FALSE;
5100     }
5101 
5102     if (sendClientCert) {
5103         if (ss->firstHsDone) {
5104             offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf);
5105         }
5106 
5107         rv = tls13_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
5108         SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
5109         ss->ssl3.clientPrivateKey = NULL;
5110         if (rv != SECSuccess) {
5111             return SECFailure; /* err is set. */
5112         }
5113 
5114         if (ss->firstHsDone) {
5115             rv = ssl3_UpdatePostHandshakeHashes(ss,
5116                                                 SSL_BUFFER_BASE(&ss->sec.ci.sendBuf) + offset,
5117                                                 SSL_BUFFER_LEN(&ss->sec.ci.sendBuf) - offset);
5118             if (rv != SECSuccess) {
5119                 return SECFailure; /* error is set. */
5120             }
5121         }
5122     }
5123 
5124     rv = tls13_SendFinished(ss, ss->firstHsDone ? ss->ssl3.hs.clientTrafficSecret : ss->ssl3.hs.clientHsTrafficSecret);
5125     if (rv != SECSuccess) {
5126         return SECFailure; /* err code was set. */
5127     }
5128     rv = ssl3_FlushHandshake(ss, 0);
5129     if (rv != SECSuccess) {
5130         /* No point in sending an alert here because we're not going to
5131          * be able to send it if we couldn't flush the handshake. */
5132         *sendAlert = no_alert;
5133         return SECFailure;
5134     }
5135 
5136     return SECSuccess;
5137 }
5138 
5139 static SECStatus
5140 tls13_SendClientSecondRound(sslSocket *ss)
5141 {
5142     SECStatus rv;
5143     PRBool sendClientCert;
5144     SSL3AlertDescription sendAlert = no_alert;
5145 
5146     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
5147     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5148 
5149     sendClientCert = !ss->ssl3.sendEmptyCert &&
5150                      ss->ssl3.clientCertChain != NULL &&
5151                      ss->ssl3.clientPrivateKey != NULL;
5152 
5153     /* Defer client authentication sending if we are still waiting for server
5154      * authentication.  This avoids unnecessary disclosure of client credentials
5155      * to an unauthenticated server.
5156      */
5157     if (ss->ssl3.hs.restartTarget) {
5158         PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
5159         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5160         return SECFailure;
5161     }
5162     if (ss->ssl3.hs.authCertificatePending) {
5163         SSL_TRC(3, ("%d: TLS13[%d]: deferring ssl3_SendClientSecondRound because"
5164                     " certificate authentication is still pending.",
5165                     SSL_GETPID(), ss->fd));
5166         ss->ssl3.hs.restartTarget = tls13_SendClientSecondRound;
5167         PORT_SetError(PR_WOULD_BLOCK_ERROR);
5168         return SECFailure;
5169     }
5170 
5171     rv = tls13_ComputeApplicationSecrets(ss);
5172     if (rv != SECSuccess) {
5173         FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
5174         return SECFailure;
5175     }
5176 
5177     if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
5178         ssl_GetXmitBufLock(ss); /*******************************/
5179         rv = tls13_SendEndOfEarlyData(ss);
5180         ssl_ReleaseXmitBufLock(ss); /*******************************/
5181         if (rv != SECSuccess) {
5182             return SECFailure; /* Error code already set. */
5183         }
5184     } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss) &&
5185                ss->ssl3.hs.zeroRttState == ssl_0rtt_none &&
5186                !ss->ssl3.hs.helloRetry) {
5187         ssl_GetXmitBufLock(ss); /*******************************/
5188         rv = ssl3_SendChangeCipherSpecsInt(ss);
5189         ssl_ReleaseXmitBufLock(ss); /*******************************/
5190         if (rv != SECSuccess) {
5191             return rv;
5192         }
5193     }
5194 
5195     rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
5196                              ssl_secret_write, PR_FALSE);
5197     if (rv != SECSuccess) {
5198         FATAL_ERROR(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, internal_error);
5199         return SECFailure;
5200     }
5201 
5202     rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
5203                              ssl_secret_read, PR_FALSE);
5204     if (rv != SECSuccess) {
5205         FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
5206         return SECFailure;
5207     }
5208 
5209     ssl_GetXmitBufLock(ss); /*******************************/
5210     rv = tls13_SendClientSecondFlight(ss, sendClientCert, &sendAlert);
5211     ssl_ReleaseXmitBufLock(ss); /*******************************/
5212     if (rv != SECSuccess) {
5213         if (sendAlert != no_alert) {
5214             FATAL_ERROR(ss, PORT_GetError(), sendAlert);
5215         } else {
5216             LOG_ERROR(ss, PORT_GetError());
5217         }
5218         return SECFailure;
5219     }
5220     rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
5221                              ssl_secret_write, PR_FALSE);
5222     if (rv != SECSuccess) {
5223         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5224         return SECFailure;
5225     }
5226 
5227     rv = tls13_ComputeFinalSecrets(ss);
5228     if (rv != SECSuccess) {
5229         return SECFailure;
5230     }
5231 
5232     /* The handshake is now finished */
5233     return tls13_FinishHandshake(ss);
5234 }
5235 
5236 /*
5237  *  enum { (65535) } TicketExtensionType;
5238  *
5239  *  struct {
5240  *      TicketExtensionType extension_type;
5241  *      opaque extension_data<0..2^16-1>;
5242  *  } TicketExtension;
5243  *
5244  *   struct {
5245  *       uint32 ticket_lifetime;
5246  *       uint32 ticket_age_add;
5247  *       opaque ticket_nonce<1..255>;
5248  *       opaque ticket<1..2^16-1>;
5249  *       TicketExtension extensions<0..2^16-2>;
5250  *   } NewSessionTicket;
5251  */
5252 
5253 static SECStatus
5254 tls13_SendNewSessionTicket(sslSocket *ss, const PRUint8 *appToken,
5255                            unsigned int appTokenLen)
5256 {
5257     PRUint16 message_length;
5258     PK11SymKey *secret;
5259     SECItem ticket_data = { 0, NULL, 0 };
5260     SECStatus rv;
5261     NewSessionTicket ticket = { 0 };
5262     PRUint32 max_early_data_size_len = 0;
5263     PRUint8 ticketNonce[sizeof(ss->ssl3.hs.ticketNonce)];
5264     sslBuffer ticketNonceBuf = SSL_BUFFER(ticketNonce);
5265 
5266     SSL_TRC(3, ("%d: TLS13[%d]: send new session ticket message %d",
5267                 SSL_GETPID(), ss->fd, ss->ssl3.hs.ticketNonce));
5268 
5269     ticket.flags = 0;
5270     if (ss->opt.enable0RttData) {
5271         ticket.flags |= ticket_allow_early_data;
5272         max_early_data_size_len = 8; /* type + len + value. */
5273     }
5274     ticket.ticket_lifetime_hint = ssl_ticket_lifetime;
5275 
5276     /* The ticket age obfuscator. */
5277     rv = PK11_GenerateRandom((PRUint8 *)&ticket.ticket_age_add,
5278                              sizeof(ticket.ticket_age_add));
5279     if (rv != SECSuccess)
5280         goto loser;
5281 
5282     rv = sslBuffer_AppendNumber(&ticketNonceBuf, ss->ssl3.hs.ticketNonce,
5283                                 sizeof(ticketNonce));
5284     if (rv != SECSuccess) {
5285         goto loser;
5286     }
5287     ++ss->ssl3.hs.ticketNonce;
5288     rv = tls13_HkdfExpandLabel(ss->ssl3.hs.resumptionMasterSecret,
5289                                tls13_GetHash(ss),
5290                                ticketNonce, sizeof(ticketNonce),
5291                                kHkdfLabelResumption,
5292                                strlen(kHkdfLabelResumption),
5293                                CKM_HKDF_DERIVE,
5294                                tls13_GetHashSize(ss),
5295                                ss->protocolVariant, &secret);
5296     if (rv != SECSuccess) {
5297         goto loser;
5298     }
5299 
5300     rv = ssl3_EncodeSessionTicket(ss, &ticket, appToken, appTokenLen,
5301                                   secret, &ticket_data);
5302     PK11_FreeSymKey(secret);
5303     if (rv != SECSuccess)
5304         goto loser;
5305 
5306     message_length =
5307         4 +                           /* lifetime */
5308         4 +                           /* ticket_age_add */
5309         1 + sizeof(ticketNonce) +     /* ticket_nonce */
5310         2 + max_early_data_size_len + /* max_early_data_size_len */
5311         2 +                           /* ticket length */
5312         ticket_data.len;
5313 
5314     rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
5315                                     message_length);
5316     if (rv != SECSuccess)
5317         goto loser;
5318 
5319     /* This is a fixed value. */
5320     rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
5321     if (rv != SECSuccess)
5322         goto loser;
5323 
5324     rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_age_add, 4);
5325     if (rv != SECSuccess)
5326         goto loser;
5327 
5328     /* The ticket nonce. */
5329     rv = ssl3_AppendHandshakeVariable(ss, ticketNonce, sizeof(ticketNonce), 1);
5330     if (rv != SECSuccess)
5331         goto loser;
5332 
5333     /* Encode the ticket. */
5334     rv = ssl3_AppendHandshakeVariable(
5335         ss, ticket_data.data, ticket_data.len, 2);
5336     if (rv != SECSuccess)
5337         goto loser;
5338 
5339     /* Extensions. */
5340     rv = ssl3_AppendHandshakeNumber(ss, max_early_data_size_len, 2);
5341     if (rv != SECSuccess)
5342         goto loser;
5343 
5344     if (max_early_data_size_len) {
5345         rv = ssl3_AppendHandshakeNumber(
5346             ss, ssl_tls13_early_data_xtn, 2);
5347         if (rv != SECSuccess)
5348             goto loser;
5349 
5350         /* Length */
5351         rv = ssl3_AppendHandshakeNumber(ss, 4, 2);
5352         if (rv != SECSuccess)
5353             goto loser;
5354 
5355         rv = ssl3_AppendHandshakeNumber(ss, ss->opt.maxEarlyDataSize, 4);
5356         if (rv != SECSuccess)
5357             goto loser;
5358     }
5359 
5360     SECITEM_FreeItem(&ticket_data, PR_FALSE);
5361     return SECSuccess;
5362 
5363 loser:
5364     if (ticket_data.data) {
5365         SECITEM_FreeItem(&ticket_data, PR_FALSE);
5366     }
5367     return SECFailure;
5368 }
5369 
5370 SECStatus
5371 SSLExp_SendSessionTicket(PRFileDesc *fd, const PRUint8 *token,
5372                          unsigned int tokenLen)
5373 {
5374     sslSocket *ss;
5375     SECStatus rv;
5376 
5377     ss = ssl_FindSocket(fd);
5378     if (!ss) {
5379         return SECFailure;
5380     }
5381 
5382     if (IS_DTLS(ss)) {
5383         PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION);
5384         return SECFailure;
5385     }
5386 
5387     if (!ss->sec.isServer || !tls13_IsPostHandshake(ss) ||
5388         tokenLen > 0xffff) {
5389         PORT_SetError(SEC_ERROR_INVALID_ARGS);
5390         return SECFailure;
5391     }
5392 
5393     /* Disable tickets if we can trace this connection back to a PSK.
5394      * We aren't able to issue tickets (currently) without a certificate.
5395      * As PSK =~ resumption, there is no reason to do this. */
5396     if (ss->sec.authType == ssl_auth_psk) {
5397         PORT_SetError(SSL_ERROR_FEATURE_DISABLED);
5398         return SECFailure;
5399     }
5400 
5401     ssl_GetSSL3HandshakeLock(ss);
5402     ssl_GetXmitBufLock(ss);
5403     rv = tls13_SendNewSessionTicket(ss, token, tokenLen);
5404     if (rv == SECSuccess) {
5405         rv = ssl3_FlushHandshake(ss, 0);
5406     }
5407     ssl_ReleaseXmitBufLock(ss);
5408     ssl_ReleaseSSL3HandshakeLock(ss);
5409 
5410     return rv;
5411 }
5412 
5413 static SECStatus
5414 tls13_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
5415 {
5416     SECStatus rv;
5417     PRUint32 utmp;
5418     NewSessionTicket ticket = { 0 };
5419     SECItem data;
5420     SECItem ticket_nonce;
5421     SECItem ticket_data;
5422 
5423     SSL_TRC(3, ("%d: TLS13[%d]: handle new session ticket message",
5424                 SSL_GETPID(), ss->fd));
5425 
5426     rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET,
5427                               idle_handshake);
5428     if (rv != SECSuccess) {
5429         return SECFailure;
5430     }
5431     if (!tls13_IsPostHandshake(ss) || ss->sec.isServer) {
5432         FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET,
5433                     unexpected_message);
5434         return SECFailure;
5435     }
5436 
5437     ticket.received_timestamp = ssl_Time(ss);
5438     rv = ssl3_ConsumeHandshakeNumber(ss, &ticket.ticket_lifetime_hint, 4, &b,
5439                                      &length);
5440     if (rv != SECSuccess) {
5441         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
5442                     decode_error);
5443         return SECFailure;
5444     }
5445     ticket.ticket.type = siBuffer;
5446 
5447     rv = ssl3_ConsumeHandshake(ss, &utmp, sizeof(utmp),
5448                                &b, &length);
5449     if (rv != SECSuccess) {
5450         PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
5451         return SECFailure;
5452     }
5453     ticket.ticket_age_add = PR_ntohl(utmp);
5454 
5455     /* The nonce. */
5456     rv = ssl3_ConsumeHandshakeVariable(ss, &ticket_nonce, 1, &b, &length);
5457     if (rv != SECSuccess) {
5458         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
5459                     decode_error);
5460         return SECFailure;
5461     }
5462 
5463     /* Get the ticket value. */
5464     rv = ssl3_ConsumeHandshakeVariable(ss, &ticket_data, 2, &b, &length);
5465     if (rv != SECSuccess || !ticket_data.len) {
5466         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
5467                     decode_error);
5468         return SECFailure;
5469     }
5470 
5471     /* Parse extensions. */
5472     rv = ssl3_ConsumeHandshakeVariable(ss, &data, 2, &b, &length);
5473     if (rv != SECSuccess || length) {
5474         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
5475                     decode_error);
5476         return SECFailure;
5477     }
5478 
5479     rv = ssl3_HandleExtensions(ss, &data.data,
5480                                &data.len, ssl_hs_new_session_ticket);
5481     if (rv != SECSuccess) {
5482         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
5483                     decode_error);
5484         return SECFailure;
5485     }
5486     if (ss->xtnData.max_early_data_size) {
5487         ticket.flags |= ticket_allow_early_data;
5488         ticket.max_early_data_size = ss->xtnData.max_early_data_size;
5489     }
5490 
5491     if (!ss->opt.noCache) {
5492         PK11SymKey *secret;
5493 
5494         PORT_Assert(ss->sec.ci.sid);
5495         rv = SECITEM_CopyItem(NULL, &ticket.ticket, &ticket_data);
5496         if (rv != SECSuccess) {
5497             FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
5498             return SECFailure;
5499         }
5500         PRINT_BUF(50, (ss, "Caching session ticket",
5501                        ticket.ticket.data,
5502                        ticket.ticket.len));
5503 
5504         /* Replace a previous session ticket when
5505          * we receive a second NewSessionTicket message. */
5506         if (ss->sec.ci.sid->cached == in_client_cache ||
5507             ss->sec.ci.sid->cached == in_external_cache) {
5508             /* Create a new session ID. */
5509             sslSessionID *sid = ssl3_NewSessionID(ss, PR_FALSE);
5510             if (!sid) {
5511                 return SECFailure;
5512             }
5513 
5514             /* Copy over the peerCert. */
5515             PORT_Assert(ss->sec.ci.sid->peerCert);
5516             sid->peerCert = CERT_DupCertificate(ss->sec.ci.sid->peerCert);
5517             if (!sid->peerCert) {
5518                 ssl_FreeSID(sid);
5519                 return SECFailure;
5520             }
5521 
5522             /* Destroy the old SID. */
5523             ssl_UncacheSessionID(ss);
5524             ssl_FreeSID(ss->sec.ci.sid);
5525             ss->sec.ci.sid = sid;
5526         }
5527 
5528         ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ticket);
5529         PORT_Assert(!ticket.ticket.data);
5530 
5531         rv = tls13_HkdfExpandLabel(ss->ssl3.hs.resumptionMasterSecret,
5532                                    tls13_GetHash(ss),
5533                                    ticket_nonce.data, ticket_nonce.len,
5534                                    kHkdfLabelResumption,
5535                                    strlen(kHkdfLabelResumption),
5536                                    CKM_HKDF_DERIVE,
5537                                    tls13_GetHashSize(ss),
5538                                    ss->protocolVariant, &secret);
5539         if (rv != SECSuccess) {
5540             return SECFailure;
5541         }
5542 
5543         rv = ssl3_FillInCachedSID(ss, ss->sec.ci.sid, secret);
5544         PK11_FreeSymKey(secret);
5545         if (rv != SECSuccess) {
5546             return SECFailure;
5547         }
5548 
5549         /* Cache the session. */
5550         ssl_CacheSessionID(ss);
5551     }
5552 
5553     return SECSuccess;
5554 }
5555 
5556 #define _M_NONE 0
5557 #define _M(a) (1 << PR_MIN(a, 31))
5558 #define _M1(a) (_M(ssl_hs_##a))
5559 #define _M2(a, b) (_M1(a) | _M1(b))
5560 #define _M3(a, b, c) (_M1(a) | _M2(b, c))
5561 
5562 static const struct {
5563     PRUint16 ex_value;
5564     PRUint32 messages;
5565 } KnownExtensions[] = {
5566     { ssl_server_name_xtn, _M2(client_hello, encrypted_extensions) },
5567     { ssl_supported_groups_xtn, _M2(client_hello, encrypted_extensions) },
5568     { ssl_signature_algorithms_xtn, _M2(client_hello, certificate_request) },
5569     { ssl_signature_algorithms_cert_xtn, _M2(client_hello,
5570                                              certificate_request) },
5571     { ssl_use_srtp_xtn, _M2(client_hello, encrypted_extensions) },
5572     { ssl_app_layer_protocol_xtn, _M2(client_hello, encrypted_extensions) },
5573     { ssl_padding_xtn, _M1(client_hello) },
5574     { ssl_tls13_key_share_xtn, _M3(client_hello, server_hello,
5575                                    hello_retry_request) },
5576     { ssl_tls13_pre_shared_key_xtn, _M2(client_hello, server_hello) },
5577     { ssl_tls13_psk_key_exchange_modes_xtn, _M1(client_hello) },
5578     { ssl_tls13_early_data_xtn, _M3(client_hello, encrypted_extensions,
5579                                     new_session_ticket) },
5580     { ssl_signed_cert_timestamp_xtn, _M3(client_hello, certificate_request,
5581                                          certificate) },
5582     { ssl_cert_status_xtn, _M3(client_hello, certificate_request,
5583                                certificate) },
5584     { ssl_delegated_credentials_xtn, _M2(client_hello, certificate) },
5585     { ssl_tls13_cookie_xtn, _M2(client_hello, hello_retry_request) },
5586     { ssl_tls13_certificate_authorities_xtn, _M1(certificate_request) },
5587     { ssl_tls13_supported_versions_xtn, _M3(client_hello, server_hello,
5588                                             hello_retry_request) },
5589     { ssl_record_size_limit_xtn, _M2(client_hello, encrypted_extensions) },
5590     { ssl_tls13_encrypted_client_hello_xtn, _M3(client_hello, encrypted_extensions, hello_retry_request) },
5591     { ssl_tls13_outer_extensions_xtn, _M_NONE /* Encoding/decoding only */ },
5592     { ssl_tls13_post_handshake_auth_xtn, _M1(client_hello) }
5593 };
5594 
5595 tls13ExtensionStatus
5596 tls13_ExtensionStatus(PRUint16 extension, SSLHandshakeType message)
5597 {
5598     unsigned int i;
5599 
5600     PORT_Assert((message == ssl_hs_client_hello) ||
5601                 (message == ssl_hs_server_hello) ||
5602                 (message == ssl_hs_hello_retry_request) ||
5603                 (message == ssl_hs_encrypted_extensions) ||
5604                 (message == ssl_hs_new_session_ticket) ||
5605                 (message == ssl_hs_certificate) ||
5606                 (message == ssl_hs_certificate_request));
5607 
5608     for (i = 0; i < PR_ARRAY_SIZE(KnownExtensions); i++) {
5609         /* Hacky check for message numbers > 30. */
5610         PORT_Assert(!(KnownExtensions[i].messages & (1U << 31)));
5611         if (KnownExtensions[i].ex_value == extension) {
5612             break;
5613         }
5614     }
5615     if (i >= PR_ARRAY_SIZE(KnownExtensions)) {
5616         return tls13_extension_unknown;
5617     }
5618 
5619     /* Return "disallowed" if the message mask bit isn't set. */
5620     if (!(_M(message) & KnownExtensions[i].messages)) {
5621         return tls13_extension_disallowed;
5622     }
5623 
5624     return tls13_extension_allowed;
5625 }
5626 
5627 #undef _M
5628 #undef _M1
5629 #undef _M2
5630 #undef _M3
5631 
5632 /* We cheat a bit on additional data because the AEAD interface
5633  * which doesn't have room for the record number. The AAD we
5634  * format is serialized record number followed by the true AD
5635  * (i.e., the record header) plus the serialized record number. */
5636 static SECStatus
5637 tls13_FormatAdditionalData(
5638     sslSocket *ss,
5639     const PRUint8 *header, unsigned int headerLen,
5640     DTLSEpoch epoch, sslSequenceNumber seqNum,
5641     PRUint8 *aad, unsigned int *aadLength, unsigned int maxLength)
5642 {
5643     SECStatus rv;
5644     sslBuffer buf = SSL_BUFFER_FIXED(aad, maxLength);
5645 
5646     if (IS_DTLS(ss)) {
5647         rv = sslBuffer_AppendNumber(&buf, epoch, 2);
5648         if (rv != SECSuccess) {
5649             return SECFailure;
5650         }
5651     }
5652     rv = sslBuffer_AppendNumber(&buf, seqNum, IS_DTLS(ss) ? 6 : 8);
5653     if (rv != SECSuccess) {
5654         return SECFailure;
5655     }
5656 
5657     rv = sslBuffer_Append(&buf, header, headerLen);
5658     if (rv != SECSuccess) {
5659         return SECFailure;
5660     }
5661 
5662     *aadLength = buf.len;
5663 
5664     return SECSuccess;
5665 }
5666 
5667 PRInt32
5668 tls13_LimitEarlyData(sslSocket *ss, SSLContentType type, PRInt32 toSend)
5669 {
5670     PRInt32 reduced;
5671 
5672     PORT_Assert(type == ssl_ct_application_data);
5673     PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
5674     PORT_Assert(!ss->firstHsDone);
5675     if (ss->ssl3.cwSpec->epoch != TrafficKeyEarlyApplicationData) {
5676         return toSend;
5677     }
5678 
5679     if (IS_DTLS(ss) && toSend > ss->ssl3.cwSpec->earlyDataRemaining) {
5680         /* Don't split application data records in DTLS. */
5681         return 0;
5682     }
5683 
5684     reduced = PR_MIN(toSend, ss->ssl3.cwSpec->earlyDataRemaining);
5685     ss->ssl3.cwSpec->earlyDataRemaining -= reduced;
5686     return reduced;
5687 }
5688 
5689 SECStatus
5690 tls13_ProtectRecord(sslSocket *ss,
5691                     ssl3CipherSpec *cwSpec,
5692                     SSLContentType type,
5693                     const PRUint8 *pIn,
5694                     PRUint32 contentLen,
5695                     sslBuffer *wrBuf)
5696 {
5697     const ssl3BulkCipherDef *cipher_def = cwSpec->cipherDef;
5698     const int tagLen = cipher_def->tag_size;
5699     SECStatus rv;
5700 
5701     PORT_Assert(cwSpec->direction == ssl_secret_write);
5702     SSL_TRC(3, ("%d: TLS13[%d]: spec=%d epoch=%d (%s) protect 0x%0llx len=%u",
5703                 SSL_GETPID(), ss->fd, cwSpec, cwSpec->epoch, cwSpec->phase,
5704                 cwSpec->nextSeqNum, contentLen));
5705 
5706     if (contentLen + 1 + tagLen > SSL_BUFFER_SPACE(wrBuf)) {
5707         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5708         return SECFailure;
5709     }
5710 
5711     /* Copy the data into the wrBuf. We're going to encrypt in-place
5712      * in the AEAD branch anyway */
5713     PORT_Memcpy(SSL_BUFFER_NEXT(wrBuf), pIn, contentLen);
5714 
5715     if (cipher_def->calg == ssl_calg_null) {
5716         /* Shortcut for plaintext */
5717         rv = sslBuffer_Skip(wrBuf, contentLen, NULL);
5718         PORT_Assert(rv == SECSuccess);
5719     } else {
5720         PRUint8 hdr[13];
5721         sslBuffer buf = SSL_BUFFER_FIXED(hdr, sizeof(hdr));
5722         PRBool needsLength;
5723         PRUint8 aad[21];
5724         const int ivLen = cipher_def->iv_size + cipher_def->explicit_nonce_size;
5725         unsigned int ivOffset = ivLen - sizeof(sslSequenceNumber);
5726         unsigned char ivOut[MAX_IV_LENGTH];
5727 
5728         unsigned int aadLen;
5729         unsigned int len;
5730 
5731         PORT_Assert(cipher_def->type == type_aead);
5732 
5733         /* If the following condition holds, we can skip the padding logic for
5734          * DTLS 1.3 (4.2.3). This will be the case until we support a cipher
5735          * with tag length < 15B. */
5736         PORT_Assert(tagLen + 1 /* cType */ >= 16);
5737 
5738         /* Add the content type at the end. */
5739         *(SSL_BUFFER_NEXT(wrBuf) + contentLen) = type;
5740 
5741         /* Create the header (ugly that we have to do it twice). */
5742         rv = ssl_InsertRecordHeader(ss, cwSpec, ssl_ct_application_data,
5743                                     &buf, &needsLength);
5744         if (rv != SECSuccess) {
5745             return SECFailure;
5746         }
5747         if (needsLength) {
5748             rv = sslBuffer_AppendNumber(&buf, contentLen + 1 + tagLen, 2);
5749             if (rv != SECSuccess) {
5750                 return SECFailure;
5751             }
5752         }
5753         rv = tls13_FormatAdditionalData(ss, SSL_BUFFER_BASE(&buf), SSL_BUFFER_LEN(&buf),
5754                                         cwSpec->epoch, cwSpec->nextSeqNum,
5755                                         aad, &aadLen, sizeof(aad));
5756         if (rv != SECSuccess) {
5757             return SECFailure;
5758         }
5759         /* set up initial IV value */
5760         ivOffset = tls13_SetupAeadIv(IS_DTLS(ss), ivOut, cwSpec->keyMaterial.iv,
5761                                      ivOffset, ivLen, cwSpec->epoch);
5762 
5763         rv = tls13_AEAD(cwSpec->cipherContext, PR_FALSE,
5764                         CKG_GENERATE_COUNTER_XOR, ivOffset * BPB,
5765                         ivOut, ivOut, ivLen,             /* iv */
5766                         NULL, 0,                         /* nonce */
5767                         aad + sizeof(sslSequenceNumber), /* aad */
5768                         aadLen - sizeof(sslSequenceNumber),
5769                         SSL_BUFFER_NEXT(wrBuf),  /* output  */
5770                         &len,                    /* out len */
5771                         SSL_BUFFER_SPACE(wrBuf), /* max out */
5772                         tagLen,
5773                         SSL_BUFFER_NEXT(wrBuf), /* input */
5774                         contentLen + 1);        /* input len */
5775         if (rv != SECSuccess) {
5776             PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
5777             return SECFailure;
5778         }
5779         rv = sslBuffer_Skip(wrBuf, len, NULL);
5780         PORT_Assert(rv == SECSuccess);
5781     }
5782 
5783     return SECSuccess;
5784 }
5785 
5786 /* Unprotect a TLS 1.3 record and leave the result in plaintext.
5787  *
5788  * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
5789  * Therefore, we MUST not call SSL3_SendAlert().
5790  *
5791  * If SECFailure is returned, we:
5792  * 1. Set |*alert| to the alert to be sent.
5793  * 2. Call PORT_SetError() witn an appropriate code.
5794  */
5795 SECStatus
5796 tls13_UnprotectRecord(sslSocket *ss,
5797                       ssl3CipherSpec *spec,
5798                       SSL3Ciphertext *cText,
5799                       sslBuffer *plaintext,
5800                       SSLContentType *innerType,
5801                       SSL3AlertDescription *alert)
5802 {
5803     const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
5804     const int ivLen = cipher_def->iv_size + cipher_def->explicit_nonce_size;
5805     const int tagLen = cipher_def->tag_size;
5806 
5807     PRUint8 aad[21];
5808     unsigned int aadLen;
5809     SECStatus rv;
5810 
5811     *alert = bad_record_mac; /* Default alert for most issues. */
5812 
5813     PORT_Assert(spec->direction == ssl_secret_read);
5814     SSL_TRC(3, ("%d: TLS13[%d]: spec=%d epoch=%d (%s) unprotect 0x%0llx len=%u",
5815                 SSL_GETPID(), ss->fd, spec, spec->epoch, spec->phase,
5816                 cText->seqNum, cText->buf->len));
5817 
5818     /* Verify that the content type is right, even though we overwrite it.
5819      * Also allow the DTLS short header in TLS 1.3. */
5820     if (!(cText->hdr[0] == ssl_ct_application_data ||
5821           (IS_DTLS(ss) &&
5822            ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
5823            (cText->hdr[0] & 0xe0) == 0x20))) {
5824         SSL_TRC(3,
5825                 ("%d: TLS13[%d]: record has invalid exterior type=%2.2x",
5826                  SSL_GETPID(), ss->fd, cText->hdr[0]));
5827         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_RECORD_TYPE);
5828         *alert = unexpected_message;
5829         return SECFailure;
5830     }
5831 
5832     /* We can perform this test in variable time because the record's total
5833      * length and the ciphersuite are both public knowledge. */
5834     if (cText->buf->len < tagLen) {
5835         SSL_TRC(3,
5836                 ("%d: TLS13[%d]: record too short to contain valid AEAD data",
5837                  SSL_GETPID(), ss->fd));
5838         PORT_SetError(SSL_ERROR_BAD_MAC_READ);
5839         return SECFailure;
5840     }
5841 
5842     /* Check the version number in the record. Stream only. */
5843     if (!IS_DTLS(ss)) {
5844         SSL3ProtocolVersion version =
5845             ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
5846             (SSL3ProtocolVersion)cText->hdr[2];
5847         if (version != spec->recordVersion) {
5848             /* Do we need a better error here? */
5849             SSL_TRC(3, ("%d: TLS13[%d]: record has bogus version",
5850                         SSL_GETPID(), ss->fd));
5851             return SECFailure;
5852         }
5853     }
5854 
5855     /* Decrypt */
5856     PORT_Assert(cipher_def->type == type_aead);
5857     rv = tls13_FormatAdditionalData(ss, cText->hdr, cText->hdrLen,
5858                                     spec->epoch, cText->seqNum,
5859                                     aad, &aadLen, sizeof(aad));
5860     if (rv != SECSuccess) {
5861 
5862         return SECFailure;
5863     }
5864     rv = tls13_AEAD(spec->cipherContext, PR_TRUE,
5865                     CKG_NO_GENERATE, 0,                /* ignored for decrypt */
5866                     spec->keyMaterial.iv, NULL, ivLen, /* iv */
5867                     aad, sizeof(sslSequenceNumber),    /* nonce */
5868                     aad + sizeof(sslSequenceNumber),   /* aad */
5869                     aadLen - sizeof(sslSequenceNumber),
5870                     plaintext->buf,   /* output  */
5871                     &plaintext->len,  /* outlen */
5872                     plaintext->space, /* maxout */
5873                     tagLen,
5874                     cText->buf->buf,  /* in */
5875                     cText->buf->len); /* inlen */
5876     if (rv != SECSuccess) {
5877         if (IS_DTLS(ss)) {
5878             spec->deprotectionFailures++;
5879         }
5880 
5881         SSL_TRC(3,
5882                 ("%d: TLS13[%d]: record has bogus MAC",
5883                  SSL_GETPID(), ss->fd));
5884         PORT_SetError(SSL_ERROR_BAD_MAC_READ);
5885         return SECFailure;
5886     }
5887 
5888     /* There is a similar test in ssl3_HandleRecord, but this test is needed to
5889      * account for padding.  It's safe to do this here (including the alert),
5890      * because it only confirms that the record exceeded the size limit, which
5891      * is apparent from the size of the ciphertext. */
5892     if (plaintext->len > spec->recordSizeLimit + 1) {
5893         SSL3_SendAlert(ss, alert_fatal, record_overflow);
5894         PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
5895         return SECFailure;
5896     }
5897 
5898     /* The record is right-padded with 0s, followed by the true
5899      * content type, so read from the right until we receive a
5900      * nonzero byte. */
5901     while (plaintext->len > 0 && !(plaintext->buf[plaintext->len - 1])) {
5902         --plaintext->len;
5903     }
5904 
5905     /* Bogus padding. */
5906     if (plaintext->len < 1) {
5907         SSL_TRC(3, ("%d: TLS13[%d]: empty record", SSL_GETPID(), ss->fd));
5908         /* It's safe to report this specifically because it happened
5909          * after the MAC has been verified. */
5910         *alert = unexpected_message;
5911         PORT_SetError(SSL_ERROR_BAD_BLOCK_PADDING);
5912         return SECFailure;
5913     }
5914 
5915     /* Record the type. */
5916     *innerType = (SSLContentType)plaintext->buf[plaintext->len - 1];
5917     --plaintext->len;
5918 
5919     /* Check that we haven't received too much 0-RTT data. */
5920     if (spec->epoch == TrafficKeyEarlyApplicationData &&
5921         *innerType == ssl_ct_application_data) {
5922         if (plaintext->len > spec->earlyDataRemaining) {
5923             *alert = unexpected_message;
5924             PORT_SetError(SSL_ERROR_TOO_MUCH_EARLY_DATA);
5925             return SECFailure;
5926         }
5927         spec->earlyDataRemaining -= plaintext->len;
5928     }
5929 
5930     SSL_TRC(10,
5931             ("%d: TLS13[%d]: %s received record of length=%d, type=%d",
5932              SSL_GETPID(), ss->fd, SSL_ROLE(ss), plaintext->len, *innerType));
5933 
5934     return SECSuccess;
5935 }
5936 
5937 /* 0-RTT is only permitted if:
5938  *
5939  * 1. We are doing TLS 1.3
5940  * 2. This isn't a second ClientHello (in response to HelloRetryRequest)
5941  * 3. The 0-RTT option is set.
5942  * 4. We have a valid ticket or an External PSK.
5943  * 5. If resuming:
5944  *    5a. The server is willing to accept 0-RTT.
5945  *    5b. We have not changed our ALPN settings to disallow the ALPN tag
5946  *    in the ticket.
5947  *
5948  * Called from tls13_ClientSendEarlyDataXtn().
5949  */
5950 PRBool
5951 tls13_ClientAllow0Rtt(const sslSocket *ss, const sslSessionID *sid)
5952 {
5953     /* We checked that the cipher suite was still allowed back in
5954      * ssl3_SendClientHello. */
5955     if (sid->version < SSL_LIBRARY_VERSION_TLS_1_3) {
5956         return PR_FALSE;
5957     }
5958     if (ss->ssl3.hs.helloRetry) {
5959         return PR_FALSE;
5960     }
5961     if (!ss->opt.enable0RttData) {
5962         return PR_FALSE;
5963     }
5964     if (PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)) {
5965         return PR_FALSE;
5966     }
5967     sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
5968 
5969     if (psk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL) {
5970         return PR_FALSE;
5971     }
5972     if (!psk->maxEarlyData) {
5973         return PR_FALSE;
5974     }
5975 
5976     if (psk->type == ssl_psk_external) {
5977         return psk->hash == tls13_GetHashForCipherSuite(psk->zeroRttSuite);
5978     }
5979     if (psk->type == ssl_psk_resume) {
5980         if (!ss->statelessResume)
5981             return PR_FALSE;
5982         if ((sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data) == 0)
5983             return PR_FALSE;
5984         return ssl_AlpnTagAllowed(ss, &sid->u.ssl3.alpnSelection);
5985     }
5986     PORT_Assert(0);
5987     return PR_FALSE;
5988 }
5989 
5990 SECStatus
5991 tls13_MaybeDo0RTTHandshake(sslSocket *ss)
5992 {
5993     SECStatus rv;
5994 
5995     /* Don't do anything if there is no early_data xtn, which means we're
5996      * not doing early data. */
5997     if (!ssl3_ExtensionAdvertised(ss, ssl_tls13_early_data_xtn)) {
5998         return SECSuccess;
5999     }
6000 
6001     ss->ssl3.hs.zeroRttState = ssl_0rtt_sent;
6002     ss->ssl3.hs.zeroRttSuite = ss->ssl3.hs.cipher_suite;
6003     /* Note: Reset the preliminary info here rather than just add 0-RTT.  We are
6004      * only guessing what might happen at this point.*/
6005     ss->ssl3.hs.preliminaryInfo = ssl_preinfo_0rtt_cipher_suite;
6006 
6007     SSL_TRC(3, ("%d: TLS13[%d]: in 0-RTT mode", SSL_GETPID(), ss->fd));
6008 
6009     /* Set the ALPN data as if it was negotiated. We check in the ServerHello
6010      * handler that the server negotiates the same value. */
6011     if (ss->sec.ci.sid->u.ssl3.alpnSelection.len) {
6012         ss->xtnData.nextProtoState = SSL_NEXT_PROTO_EARLY_VALUE;
6013         rv = SECITEM_CopyItem(NULL, &ss->xtnData.nextProto,
6014                               &ss->sec.ci.sid->u.ssl3.alpnSelection);
6015         if (rv != SECSuccess) {
6016             return SECFailure;
6017         }
6018     }
6019 
6020     if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) {
6021         /* Pretend that this is a proper ChangeCipherSpec even though it is sent
6022          * before receiving the ServerHello. */
6023         ssl_GetSpecWriteLock(ss);
6024         tls13_SetSpecRecordVersion(ss, ss->ssl3.cwSpec);
6025         ssl_ReleaseSpecWriteLock(ss);
6026         ssl_GetXmitBufLock(ss);
6027         rv = ssl3_SendChangeCipherSpecsInt(ss);
6028         ssl_ReleaseXmitBufLock(ss);
6029         if (rv != SECSuccess) {
6030             return SECFailure;
6031         }
6032     }
6033 
6034     /* If we're trying 0-RTT, derive from the first PSK */
6035     PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) && !ss->xtnData.selectedPsk);
6036     ss->xtnData.selectedPsk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
6037     rv = tls13_DeriveEarlySecrets(ss);
6038     if (rv != SECSuccess) {
6039         return SECFailure;
6040     }
6041 
6042     /* Save cwSpec in case we get a HelloRetryRequest and have to send another
6043      * ClientHello. */
6044     ssl_CipherSpecAddRef(ss->ssl3.cwSpec);
6045 
6046     rv = tls13_SetCipherSpec(ss, TrafficKeyEarlyApplicationData,
6047                              ssl_secret_write, PR_TRUE);
6048     ss->xtnData.selectedPsk = NULL;
6049     if (rv != SECSuccess) {
6050         return SECFailure;
6051     }
6052 
6053     return SECSuccess;
6054 }
6055 
6056 PRInt32
6057 tls13_Read0RttData(sslSocket *ss, PRUint8 *buf, PRInt32 len)
6058 {
6059     PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData));
6060     PRInt32 offset = 0;
6061     while (!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)) {
6062         TLS13EarlyData *msg =
6063             (TLS13EarlyData *)PR_NEXT_LINK(&ss->ssl3.hs.bufferedEarlyData);
6064         unsigned int tocpy = msg->data.len - msg->consumed;
6065 
6066         if (tocpy > (len - offset)) {
6067             if (IS_DTLS(ss)) {
6068                 /* In DTLS, we only return entire records.
6069                  * So offset and consumed are always zero. */
6070                 PORT_Assert(offset == 0);
6071                 PORT_Assert(msg->consumed == 0);
6072                 PORT_SetError(SSL_ERROR_RX_SHORT_DTLS_READ);
6073                 return -1;
6074             }
6075 
6076             tocpy = len - offset;
6077         }
6078 
6079         PORT_Memcpy(buf + offset, msg->data.data + msg->consumed, tocpy);
6080         offset += tocpy;
6081         msg->consumed += tocpy;
6082 
6083         if (msg->consumed == msg->data.len) {
6084             PR_REMOVE_LINK(&msg->link);
6085             SECITEM_ZfreeItem(&msg->data, PR_FALSE);
6086             PORT_ZFree(msg, sizeof(*msg));
6087         }
6088 
6089         /* We are done after one record for DTLS; otherwise, when the buffer fills up. */
6090         if (IS_DTLS(ss) || offset == len) {
6091             break;
6092         }
6093     }
6094 
6095     return offset;
6096 }
6097 
6098 static SECStatus
6099 tls13_SendEndOfEarlyData(sslSocket *ss)
6100 {
6101     SECStatus rv;
6102 
6103     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6104 
6105     if (!ss->opt.suppressEndOfEarlyData) {
6106         SSL_TRC(3, ("%d: TLS13[%d]: send EndOfEarlyData", SSL_GETPID(), ss->fd));
6107         rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_end_of_early_data, 0);
6108         if (rv != SECSuccess) {
6109             return rv; /* err set by AppendHandshake. */
6110         }
6111     }
6112 
6113     ss->ssl3.hs.zeroRttState = ssl_0rtt_done;
6114     return SECSuccess;
6115 }
6116 
6117 static SECStatus
6118 tls13_HandleEndOfEarlyData(sslSocket *ss, const PRUint8 *b, PRUint32 length)
6119 {
6120     SECStatus rv;
6121 
6122     PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
6123 
6124     rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_END_OF_EARLY_DATA,
6125                               wait_end_of_early_data);
6126     if (rv != SECSuccess) {
6127         return SECFailure;
6128     }
6129 
6130     /* We shouldn't be getting any more early data, and if we do,
6131      * it is because of reordering and we drop it. */
6132     if (IS_DTLS(ss)) {
6133         ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read,
6134                                      TrafficKeyEarlyApplicationData);
6135         dtls_ReceivedFirstMessageInFlight(ss);
6136     }
6137 
6138     PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted);
6139 
6140     if (length) {
6141         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_END_OF_EARLY_DATA, decode_error);
6142         return SECFailure;
6143     }
6144 
6145     rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
6146                              ssl_secret_read, PR_FALSE);
6147     if (rv != SECSuccess) {
6148         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6149         return SECFailure;
6150     }
6151 
6152     ss->ssl3.hs.zeroRttState = ssl_0rtt_done;
6153     if (tls13_ShouldRequestClientAuth(ss)) {
6154         TLS13_SET_HS_STATE(ss, wait_client_cert);
6155     } else {
6156         TLS13_SET_HS_STATE(ss, wait_finished);
6157     }
6158     return SECSuccess;
6159 }
6160 
6161 static SECStatus
6162 tls13_MaybeHandleSuppressedEndOfEarlyData(sslSocket *ss)
6163 {
6164     PORT_Assert(ss->sec.isServer);
6165     if (!ss->opt.suppressEndOfEarlyData ||
6166         ss->ssl3.hs.zeroRttState != ssl_0rtt_accepted) {
6167         return SECSuccess;
6168     }
6169 
6170     return tls13_HandleEndOfEarlyData(ss, NULL, 0);
6171 }
6172 
6173 SECStatus
6174 tls13_HandleEarlyApplicationData(sslSocket *ss, sslBuffer *origBuf)
6175 {
6176     TLS13EarlyData *ed;
6177     SECItem it = { siBuffer, NULL, 0 };
6178 
6179     PORT_Assert(ss->sec.isServer);
6180     PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted);
6181     if (ss->ssl3.hs.zeroRttState != ssl_0rtt_accepted) {
6182         /* Belt and suspenders. */
6183         FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
6184         return SECFailure;
6185     }
6186 
6187     PRINT_BUF(3, (NULL, "Received early application data",
6188                   origBuf->buf, origBuf->len));
6189     ed = PORT_ZNew(TLS13EarlyData);
6190     if (!ed) {
6191         FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
6192         return SECFailure;
6193     }
6194     it.data = origBuf->buf;
6195     it.len = origBuf->len;
6196     if (SECITEM_CopyItem(NULL, &ed->data, &it) != SECSuccess) {
6197         FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
6198         return SECFailure;
6199     }
6200     PR_APPEND_LINK(&ed->link, &ss->ssl3.hs.bufferedEarlyData);
6201 
6202     origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
6203 
6204     return SECSuccess;
6205 }
6206 
6207 PRUint16
6208 tls13_EncodeVersion(SSL3ProtocolVersion version, SSLProtocolVariant variant)
6209 {
6210     if (variant == ssl_variant_datagram) {
6211 #ifdef DTLS_1_3_DRAFT_VERSION
6212         switch (version) {
6213             case SSL_LIBRARY_VERSION_TLS_1_3:
6214                 return 0x7f00 | DTLS_1_3_DRAFT_VERSION;
6215             case SSL_LIBRARY_VERSION_TLS_1_2:
6216                 return SSL_LIBRARY_VERSION_DTLS_1_2_WIRE;
6217             case SSL_LIBRARY_VERSION_TLS_1_1:
6218                 /* TLS_1_1 maps to DTLS_1_0, see sslproto.h. */
6219                 return SSL_LIBRARY_VERSION_DTLS_1_0_WIRE;
6220             default:
6221                 PORT_Assert(0);
6222         }
6223 #else
6224         return dtls_TLSVersionToDTLSVersion();
6225 #endif
6226     }
6227     /* Stream-variant encodings do not change. */
6228     return (PRUint16)version;
6229 }
6230 
6231 SECStatus
6232 tls13_ClientReadSupportedVersion(sslSocket *ss)
6233 {
6234     PRUint32 temp;
6235     TLSExtension *versionExtension;
6236     SECItem it;
6237     SECStatus rv;
6238 
6239     /* Update the version based on the extension, as necessary. */
6240     versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
6241     if (!versionExtension) {
6242         return SECSuccess;
6243     }
6244 
6245     /* Struct copy so we don't damage the extension. */
6246     it = versionExtension->data;
6247 
6248     rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, &it.data, &it.len);
6249     if (rv != SECSuccess) {
6250         return SECFailure;
6251     }
6252     if (it.len) {
6253         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
6254         return SECFailure;
6255     }
6256 
6257     if (temp != tls13_EncodeVersion(SSL_LIBRARY_VERSION_TLS_1_3,
6258                                     ss->protocolVariant)) {
6259         /* You cannot negotiate < TLS 1.3 with supported_versions. */
6260         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
6261         return SECFailure;
6262     }
6263 
6264     ss->version = SSL_LIBRARY_VERSION_TLS_1_3;
6265     return SECSuccess;
6266 }
6267 
6268 /* Pick the highest version we support that is also advertised. */
6269 SECStatus
6270 tls13_NegotiateVersion(sslSocket *ss, const TLSExtension *supportedVersions)
6271 {
6272     PRUint16 version;
6273     /* Make a copy so we're nondestructive. */
6274     SECItem data = supportedVersions->data;
6275     SECItem versions;
6276     SECStatus rv;
6277 
6278     rv = ssl3_ConsumeHandshakeVariable(ss, &versions, 1,
6279                                        &data.data, &data.len);
6280     if (rv != SECSuccess) {
6281         return SECFailure;
6282     }
6283     if (data.len || !versions.len || (versions.len & 1)) {
6284         FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
6285         return SECFailure;
6286     }
6287     for (version = ss->vrange.max; version >= ss->vrange.min; --version) {
6288         if (version < SSL_LIBRARY_VERSION_TLS_1_3 &&
6289             (ss->ssl3.hs.helloRetry || ss->ssl3.hs.echAccepted)) {
6290             /* Prevent negotiating to a lower version after 1.3 HRR or ECH
6291              * When accepting ECH, a different alert is generated.
6292              */
6293             SSL3AlertDescription alert = ss->ssl3.hs.echAccepted ? illegal_parameter : protocol_version;
6294             PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
6295             FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, alert);
6296             return SECFailure;
6297         }
6298 
6299         PRUint16 wire = tls13_EncodeVersion(version, ss->protocolVariant);
6300         unsigned long offset;
6301 
6302         for (offset = 0; offset < versions.len; offset += 2) {
6303             PRUint16 supported =
6304                 (versions.data[offset] << 8) | versions.data[offset + 1];
6305             if (supported == wire) {
6306                 ss->version = version;
6307                 return SECSuccess;
6308             }
6309         }
6310     }
6311 
6312     FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, protocol_version);
6313     return SECFailure;
6314 }
6315 
6316 /* This is TLS 1.3 or might negotiate to it. */
6317 PRBool
6318 tls13_MaybeTls13(sslSocket *ss)
6319 {
6320     if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
6321         return PR_TRUE;
6322     }
6323 
6324     if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
6325         return PR_FALSE;
6326     }
6327 
6328     if (!(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version)) {
6329         return PR_TRUE;
6330     }
6331 
6332     return PR_FALSE;
6333 }
6334