1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "nssrenam.h"
8 #include "nss.h"
9 #include "ssl.h"
10 #include "sslproto.h"
11 #include "sslimpl.h"
12 #include "pk11pub.h"
13 #include "ssl3ext.h"
14 #include "ssl3exthandle.h"
15 #include "tls13ech.h"
16 #include "tls13exthandle.h"
17 #include "tls13psk.h"
18 #include "tls13subcerts.h"
19 
20 SECStatus
tls13_ServerSendStatusRequestXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)21 tls13_ServerSendStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData,
22                                  sslBuffer *buf, PRBool *added)
23 {
24     const sslServerCert *serverCert = ss->sec.serverCert;
25     const SECItem *item;
26     SECStatus rv;
27 
28     if (!serverCert->certStatusArray ||
29         !serverCert->certStatusArray->len) {
30         return SECSuccess;
31     }
32 
33     item = &serverCert->certStatusArray->items[0];
34 
35     /* Only send the first entry. */
36     /* status_type == ocsp */
37     rv = sslBuffer_AppendNumber(buf, 1 /*ocsp*/, 1);
38     if (rv != SECSuccess) {
39         return SECFailure;
40     }
41     /* opaque OCSPResponse<1..2^24-1> */
42     rv = sslBuffer_AppendVariable(buf, item->data, item->len, 3);
43     if (rv != SECSuccess) {
44         return SECFailure;
45     }
46 
47     *added = PR_TRUE;
48     return SECSuccess;
49 }
50 
51 /*
52  *     [draft-ietf-tls-tls13-11] Section 6.3.2.3.
53  *
54  *     struct {
55  *         NamedGroup group;
56  *         opaque key_exchange<1..2^16-1>;
57  *     } KeyShareEntry;
58  *
59  *     struct {
60  *         select (role) {
61  *             case client:
62  *                 KeyShareEntry client_shares<4..2^16-1>;
63  *
64  *             case server:
65  *                 KeyShareEntry server_share;
66  *         }
67  *     } KeyShare;
68  *
69  * DH is Section 6.3.2.3.1.
70  *
71  *     opaque dh_Y<1..2^16-1>;
72  *
73  * ECDH is Section 6.3.2.3.2.
74  *
75  *     opaque point <1..2^8-1>;
76  */
77 PRUint32
tls13_SizeOfKeyShareEntry(const SECKEYPublicKey * pubKey)78 tls13_SizeOfKeyShareEntry(const SECKEYPublicKey *pubKey)
79 {
80     /* Size = NamedGroup(2) + length(2) + opaque<?> share */
81     switch (pubKey->keyType) {
82         case ecKey:
83             return 2 + 2 + pubKey->u.ec.publicValue.len;
84         case dhKey:
85             return 2 + 2 + pubKey->u.dh.prime.len;
86         default:
87             PORT_Assert(0);
88     }
89     return 0;
90 }
91 
92 SECStatus
tls13_EncodeKeyShareEntry(sslBuffer * buf,SSLNamedGroup group,SECKEYPublicKey * pubKey)93 tls13_EncodeKeyShareEntry(sslBuffer *buf, SSLNamedGroup group,
94                           SECKEYPublicKey *pubKey)
95 {
96     SECStatus rv;
97     unsigned int size = tls13_SizeOfKeyShareEntry(pubKey);
98 
99     rv = sslBuffer_AppendNumber(buf, group, 2);
100     if (rv != SECSuccess)
101         return rv;
102     rv = sslBuffer_AppendNumber(buf, size - 4, 2);
103     if (rv != SECSuccess)
104         return rv;
105 
106     switch (pubKey->keyType) {
107         case ecKey:
108             rv = sslBuffer_Append(buf, pubKey->u.ec.publicValue.data,
109                                   pubKey->u.ec.publicValue.len);
110             break;
111         case dhKey:
112             rv = ssl_AppendPaddedDHKeyShare(buf, pubKey, PR_FALSE);
113             break;
114         default:
115             PORT_Assert(0);
116             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
117             break;
118     }
119 
120     return rv;
121 }
122 
123 SECStatus
tls13_ClientSendKeyShareXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)124 tls13_ClientSendKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData,
125                             sslBuffer *buf, PRBool *added)
126 {
127     SECStatus rv;
128     PRCList *cursor;
129     unsigned int lengthOffset;
130 
131     if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
132         return SECSuccess;
133     }
134 
135     /* Optimistically try to send an ECDHE key using the
136      * preexisting key (in future will be keys) */
137     SSL_TRC(3, ("%d: TLS13[%d]: send client key share xtn",
138                 SSL_GETPID(), ss->fd));
139 
140     /* Save the offset to the length. */
141     rv = sslBuffer_Skip(buf, 2, &lengthOffset);
142     if (rv != SECSuccess) {
143         return SECFailure;
144     }
145 
146     for (cursor = PR_NEXT_LINK(&ss->ephemeralKeyPairs);
147          cursor != &ss->ephemeralKeyPairs;
148          cursor = PR_NEXT_LINK(cursor)) {
149         sslEphemeralKeyPair *keyPair = (sslEphemeralKeyPair *)cursor;
150         rv = tls13_EncodeKeyShareEntry(buf,
151                                        keyPair->group->name,
152                                        keyPair->keys->pubKey);
153         if (rv != SECSuccess) {
154             return SECFailure;
155         }
156     }
157     rv = sslBuffer_InsertLength(buf, lengthOffset, 2);
158     if (rv != SECSuccess) {
159         return SECFailure;
160     }
161 
162     *added = PR_TRUE;
163     return SECSuccess;
164 }
165 
166 SECStatus
tls13_DecodeKeyShareEntry(sslReader * rdr,TLS13KeyShareEntry ** ksp)167 tls13_DecodeKeyShareEntry(sslReader *rdr, TLS13KeyShareEntry **ksp)
168 {
169     SECStatus rv;
170     PRUint64 group;
171     const sslNamedGroupDef *groupDef;
172     TLS13KeyShareEntry *ks = NULL;
173     sslReadBuffer share;
174 
175     rv = sslRead_ReadNumber(rdr, 2, &group);
176     if (rv != SECSuccess) {
177         goto loser;
178     }
179     groupDef = ssl_LookupNamedGroup(group);
180     rv = sslRead_ReadVariable(rdr, 2, &share);
181     if (rv != SECSuccess) {
182         goto loser;
183     }
184 
185     /* This has to happen here because we want to consume
186      * the entire entry even if the group is unknown
187      * or disabled. */
188     /* If the group is disabled, continue. */
189     if (!groupDef) {
190         return SECSuccess;
191     }
192 
193     ks = PORT_ZNew(TLS13KeyShareEntry);
194     if (!ks) {
195         goto loser;
196     }
197     ks->group = groupDef;
198 
199     rv = SECITEM_MakeItem(NULL, &ks->key_exchange,
200                           share.buf, share.len);
201     if (rv != SECSuccess) {
202         goto loser;
203     }
204 
205     *ksp = ks;
206     return SECSuccess;
207 
208 loser:
209     tls13_DestroyKeyShareEntry(ks);
210 
211     return SECFailure;
212 }
213 /* Handle an incoming KeyShare extension at the client and copy to
214  * |xtnData->remoteKeyShares| for future use. The key
215  * share is processed in tls13_HandleServerKeyShare(). */
216 SECStatus
tls13_ClientHandleKeyShareXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)217 tls13_ClientHandleKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData,
218                               SECItem *data)
219 {
220     SECStatus rv;
221     PORT_Assert(PR_CLIST_IS_EMPTY(&xtnData->remoteKeyShares));
222     TLS13KeyShareEntry *ks = NULL;
223 
224     PORT_Assert(!ss->sec.isServer);
225 
226     /* The server must not send this extension when negotiating < TLS 1.3. */
227     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
228         PORT_SetError(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION);
229         return SECFailure;
230     }
231 
232     SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension",
233                 SSL_GETPID(), ss->fd));
234 
235     sslReader rdr = SSL_READER(data->data, data->len);
236     rv = tls13_DecodeKeyShareEntry(&rdr, &ks);
237     if ((rv != SECSuccess) || !ks) {
238         ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
239         PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
240         return SECFailure;
241     }
242 
243     if (SSL_READER_REMAINING(&rdr)) {
244         tls13_DestroyKeyShareEntry(ks);
245         PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
246         return SECFailure;
247     }
248     PR_APPEND_LINK(&ks->link, &xtnData->remoteKeyShares);
249 
250     return SECSuccess;
251 }
252 
253 SECStatus
tls13_ClientHandleKeyShareXtnHrr(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)254 tls13_ClientHandleKeyShareXtnHrr(const sslSocket *ss, TLSExtensionData *xtnData,
255                                  SECItem *data)
256 {
257     SECStatus rv;
258     PRUint32 tmp;
259     const sslNamedGroupDef *group;
260 
261     PORT_Assert(!ss->sec.isServer);
262     PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
263 
264     SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension in HRR",
265                 SSL_GETPID(), ss->fd));
266 
267     rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2, &data->data, &data->len);
268     if (rv != SECSuccess) {
269         return SECFailure; /* error code already set */
270     }
271     if (data->len) {
272         ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
273         PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST);
274         return SECFailure;
275     }
276 
277     group = ssl_LookupNamedGroup((SSLNamedGroup)tmp);
278     /* If the group is not enabled, or we already have a share for the
279      * requested group, abort. */
280     if (!ssl_NamedGroupEnabled(ss, group) ||
281         ssl_HaveEphemeralKeyPair(ss, group)) {
282         ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
283         PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST);
284         return SECFailure;
285     }
286 
287     /* Now delete all the key shares per [draft-ietf-tls-tls13 S 4.1.2] */
288     ssl_FreeEphemeralKeyPairs(CONST_CAST(sslSocket, ss));
289 
290     /* And replace with our new share. */
291     rv = tls13_AddKeyShare(CONST_CAST(sslSocket, ss), group);
292     if (rv != SECSuccess) {
293         ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
294         PORT_SetError(SEC_ERROR_KEYGEN_FAIL);
295         return SECFailure;
296     }
297 
298     return SECSuccess;
299 }
300 
301 /* Handle an incoming KeyShare extension at the server and copy to
302  * |xtnData->remoteKeyShares| for future use. The key
303  * share is processed in tls13_HandleClientKeyShare(). */
304 SECStatus
tls13_ServerHandleKeyShareXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)305 tls13_ServerHandleKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData,
306                               SECItem *data)
307 {
308     SECStatus rv;
309     PRUint32 length;
310 
311     PORT_Assert(ss->sec.isServer);
312     PORT_Assert(PR_CLIST_IS_EMPTY(&xtnData->remoteKeyShares));
313 
314     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
315         return SECSuccess;
316     }
317 
318     SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension",
319                 SSL_GETPID(), ss->fd));
320 
321     /* Redundant length because of TLS encoding (this vector consumes
322      * the entire extension.) */
323     rv = ssl3_ExtConsumeHandshakeNumber(ss, &length, 2, &data->data,
324                                         &data->len);
325     if (rv != SECSuccess)
326         goto loser;
327     if (length != data->len) {
328         /* Check for consistency */
329         PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
330         goto loser;
331     }
332 
333     sslReader rdr = SSL_READER(data->data, data->len);
334     while (SSL_READER_REMAINING(&rdr)) {
335         TLS13KeyShareEntry *ks = NULL;
336         rv = tls13_DecodeKeyShareEntry(&rdr, &ks);
337         if (rv != SECSuccess) {
338             PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
339             goto loser;
340         }
341         if (ks) {
342             /* |ks| == NULL if this is an unknown group. */
343             PR_APPEND_LINK(&ks->link, &xtnData->remoteKeyShares);
344         }
345     }
346 
347     /* Keep track of negotiated extensions. */
348     xtnData->negotiated[xtnData->numNegotiated++] =
349         ssl_tls13_key_share_xtn;
350 
351     return SECSuccess;
352 
353 loser:
354     tls13_DestroyKeyShares(&xtnData->remoteKeyShares);
355     return SECFailure;
356 }
357 
358 SECStatus
tls13_ServerSendKeyShareXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)359 tls13_ServerSendKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData,
360                             sslBuffer *buf, PRBool *added)
361 {
362     SECStatus rv;
363     sslEphemeralKeyPair *keyPair;
364 
365     /* There should be exactly one key share. */
366     PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
367     PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==
368                 PR_NEXT_LINK(&ss->ephemeralKeyPairs));
369 
370     keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs);
371 
372     rv = tls13_EncodeKeyShareEntry(buf, keyPair->group->name,
373                                    keyPair->keys->pubKey);
374     if (rv != SECSuccess) {
375         return SECFailure;
376     }
377 
378     *added = PR_TRUE;
379     return SECSuccess;
380 }
381 
382 /* Called by clients.
383  *
384  *      struct {
385  *         opaque identity<0..2^16-1>;
386  *         uint32 obfuscated_ticket_age;
387  *     } PskIdentity;
388  *
389  *     opaque PskBinderEntry<32..255>;
390  *
391  *     struct {
392  *         select (Handshake.msg_type) {
393  *             case client_hello:
394  *                 PskIdentity identities<6..2^16-1>;
395  *                 PskBinderEntry binders<33..2^16-1>;
396  *
397  *             case server_hello:
398  *                 uint16 selected_identity;
399  *         };
400  *
401  *     } PreSharedKeyExtension;
402  */
403 SECStatus
tls13_ClientSendPreSharedKeyXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)404 tls13_ClientSendPreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData,
405                                 sslBuffer *buf, PRBool *added)
406 {
407     const static PRUint8 binder[TLS13_MAX_FINISHED_SIZE] = { 0 };
408     unsigned int binderLen;
409     unsigned int identityLen = 0;
410     const PRUint8 *identity = NULL;
411     PRTime age;
412     SECStatus rv;
413 
414     /* Exit early if no PSKs or max version < 1.3. */
415     if (PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) ||
416         ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
417         return SECSuccess;
418     }
419 
420     /* ...or if PSK type is resumption, but we're not resuming. */
421     sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
422     if (psk->type == ssl_psk_resume && !ss->statelessResume) {
423         return SECSuccess;
424     }
425 
426     /* Save where this extension starts so that if we have to add padding, it
427     * can be inserted before this extension. */
428     PORT_Assert(buf->len >= 4);
429     xtnData->lastXtnOffset = buf->len - 4;
430     PORT_Assert(psk->type == ssl_psk_resume || psk->type == ssl_psk_external);
431     binderLen = tls13_GetHashSizeForHash(psk->hash);
432     if (psk->type == ssl_psk_resume) {
433         /* Send a single ticket identity. */
434         NewSessionTicket *session_ticket = &ss->sec.ci.sid->u.ssl3.locked.sessionTicket;
435         identityLen = session_ticket->ticket.len;
436         identity = session_ticket->ticket.data;
437 
438         /* Obfuscated age. */
439         age = ssl_Time(ss) - session_ticket->received_timestamp;
440         age /= PR_USEC_PER_MSEC;
441         age += session_ticket->ticket_age_add;
442         PRINT_BUF(50, (ss, "Sending Resumption PSK with identity", identity, identityLen));
443     } else if (psk->type == ssl_psk_external) {
444         identityLen = psk->label.len;
445         identity = psk->label.data;
446         age = 0;
447         PRINT_BUF(50, (ss, "Sending External PSK with label", identity, identityLen));
448     } else {
449         PORT_Assert(0);
450         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
451         return SECFailure;
452     }
453 
454     /* Length is len(identityLen) + identityLen + len(age) */
455     rv = sslBuffer_AppendNumber(buf, 2 + identityLen + 4, 2);
456     if (rv != SECSuccess) {
457         goto loser;
458     }
459 
460     rv = sslBuffer_AppendVariable(buf, identity,
461                                   identityLen, 2);
462     if (rv != SECSuccess) {
463         goto loser;
464     }
465 
466     rv = sslBuffer_AppendNumber(buf, age, 4);
467     if (rv != SECSuccess) {
468         goto loser;
469     }
470 
471     /* Write out the binder list length. */
472     rv = sslBuffer_AppendNumber(buf, binderLen + 1, 2);
473     if (rv != SECSuccess) {
474         goto loser;
475     }
476 
477     /* Write zeroes for the binder for the moment. These
478      * are overwritten in tls13_WriteExtensionsWithBinder. */
479     rv = sslBuffer_AppendVariable(buf, binder, binderLen, 1);
480     if (rv != SECSuccess) {
481         goto loser;
482     }
483 
484     if (psk->type == ssl_psk_resume) {
485         xtnData->sentSessionTicketInClientHello = PR_TRUE;
486     }
487 
488     *added = PR_TRUE;
489     return SECSuccess;
490 
491 loser:
492     xtnData->ticketTimestampVerified = PR_FALSE;
493     return SECFailure;
494 }
495 
496 /* Handle a TLS 1.3 PreSharedKey Extension. */
497 SECStatus
tls13_ServerHandlePreSharedKeyXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)498 tls13_ServerHandlePreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData,
499                                   SECItem *data)
500 {
501     SECItem inner;
502     SECStatus rv;
503     unsigned int numIdentities = 0;
504     unsigned int numBinders = 0;
505     SECItem *appToken;
506 
507     SSL_TRC(3, ("%d: SSL3[%d]: handle pre_shared_key extension",
508                 SSL_GETPID(), ss->fd));
509 
510     /* If we are doing < TLS 1.3, then ignore this. */
511     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
512         return SECSuccess;
513     }
514 
515     /* The application token is set via the cookie extension if this is the
516      * second ClientHello.  Don't set it twice.  The cookie extension handler
517      * sets |helloRetry| and that will have been called already because this
518      * extension always comes last. */
519     if (!ss->ssl3.hs.helloRetry) {
520         appToken = &xtnData->applicationToken;
521     } else {
522         appToken = NULL;
523     }
524 
525     /* Parse the identities list. */
526     rv = ssl3_ExtConsumeHandshakeVariable(ss, &inner, 2,
527                                           &data->data, &data->len);
528     if (rv != SECSuccess) {
529         return SECFailure;
530     }
531 
532     while (inner.len) {
533         SECItem label;
534         PRUint32 obfuscatedAge;
535 
536         rv = ssl3_ExtConsumeHandshakeVariable(ss, &label, 2,
537                                               &inner.data, &inner.len);
538         if (rv != SECSuccess)
539             return rv;
540         if (!label.len) {
541             goto alert_loser;
542         }
543 
544         rv = ssl3_ExtConsumeHandshakeNumber(ss, &obfuscatedAge, 4,
545                                             &inner.data, &inner.len);
546         if (rv != SECSuccess)
547             return rv;
548 
549         if (!numIdentities) {
550             /* Check any configured external PSK for a matching label.
551              * If none exists, try to parse it as a ticket. */
552             PORT_Assert(!xtnData->selectedPsk);
553             for (PRCList *cur_p = PR_LIST_HEAD(&ss->ssl3.hs.psks);
554                  cur_p != &ss->ssl3.hs.psks;
555                  cur_p = PR_NEXT_LINK(cur_p)) {
556                 sslPsk *psk = (sslPsk *)cur_p;
557                 if (psk->type != ssl_psk_external ||
558                     SECITEM_CompareItem(&psk->label, &label) != SECEqual) {
559                     continue;
560                 }
561                 PRINT_BUF(50, (ss, "Using External PSK with label",
562                                psk->label.data, psk->label.len));
563                 xtnData->selectedPsk = psk;
564             }
565 
566             if (!xtnData->selectedPsk) {
567                 PRINT_BUF(50, (ss, "Handling PreSharedKey value",
568                                label.data, label.len));
569                 rv = ssl3_ProcessSessionTicketCommon(
570                     CONST_CAST(sslSocket, ss), &label, appToken);
571                 /* This only happens if we have an internal error, not
572                 * a malformed ticket. Bogus tickets just don't resume
573                 * and return SECSuccess. */
574                 if (rv != SECSuccess) {
575                     return SECFailure;
576                 }
577 
578                 if (ss->sec.ci.sid) {
579                     /* xtnData->ticketAge contains the baseline we use for
580                     * calculating the ticket age (i.e., our RTT estimate less the
581                     * value of ticket_age_add).
582                     *
583                     * Add that to the obfuscated ticket age to recover the client's
584                     * view of the ticket age plus the estimated RTT.
585                     *
586                     * See ssl3_EncodeSessionTicket() for details. */
587                     xtnData->ticketAge += obfuscatedAge;
588 
589                     /* We are not committed to resumption until after unwrapping the
590                     * RMS in tls13_HandleClientHelloPart2. The RPSK will be stored
591                     * in ss->xtnData.selectedPsk at that point, so continue. */
592                 }
593             }
594         }
595 
596         ++numIdentities;
597     }
598 
599     xtnData->pskBindersLen = data->len;
600 
601     /* Parse the binders list. */
602     rv = ssl3_ExtConsumeHandshakeVariable(ss,
603                                           &inner, 2, &data->data, &data->len);
604     if (rv != SECSuccess)
605         return SECFailure;
606     if (data->len) {
607         goto alert_loser;
608     }
609 
610     while (inner.len) {
611         SECItem binder;
612         rv = ssl3_ExtConsumeHandshakeVariable(ss, &binder, 1,
613                                               &inner.data, &inner.len);
614         if (rv != SECSuccess)
615             return rv;
616         if (binder.len < 32) {
617             goto alert_loser;
618         }
619 
620         if (!numBinders) {
621             xtnData->pskBinder = binder;
622         }
623         ++numBinders;
624     }
625 
626     if (numBinders != numIdentities)
627         goto alert_loser;
628 
629     if (ss->statelessResume) {
630         PORT_Assert(!ss->xtnData.selectedPsk);
631     } else if (!xtnData->selectedPsk) {
632         /* No matching EPSK. */
633         return SECSuccess;
634     }
635 
636     xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_pre_shared_key_xtn;
637     return SECSuccess;
638 
639 alert_loser:
640     ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
641     PORT_SetError(SSL_ERROR_MALFORMED_PRE_SHARED_KEY);
642     return SECFailure;
643 }
644 
645 SECStatus
tls13_ServerSendPreSharedKeyXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)646 tls13_ServerSendPreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData,
647                                 sslBuffer *buf, PRBool *added)
648 {
649     SECStatus rv;
650 
651     /* We only process the first session ticket the client sends,
652      * so the index is always 0. */
653     rv = sslBuffer_AppendNumber(buf, 0, 2);
654     if (rv != SECSuccess) {
655         return SECFailure;
656     }
657 
658     *added = PR_TRUE;
659     return SECSuccess;
660 }
661 
662 /* Handle a TLS 1.3 PreSharedKey Extension. */
663 SECStatus
tls13_ClientHandlePreSharedKeyXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)664 tls13_ClientHandlePreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData,
665                                   SECItem *data)
666 {
667     PRUint32 index;
668     SECStatus rv;
669 
670     SSL_TRC(3, ("%d: SSL3[%d]: handle pre_shared_key extension",
671                 SSL_GETPID(), ss->fd));
672 
673     /* The server must not send this extension when negotiating < TLS 1.3. */
674     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
675         PORT_SetError(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION);
676         return SECFailure;
677     }
678 
679     rv = ssl3_ExtConsumeHandshakeNumber(ss, &index, 2, &data->data, &data->len);
680     if (rv != SECSuccess)
681         return SECFailure;
682 
683     /* This should be the end of the extension. */
684     if (data->len) {
685         PORT_SetError(SSL_ERROR_MALFORMED_PRE_SHARED_KEY);
686         return SECFailure;
687     }
688 
689     /* We only sent one PSK label so index must be equal to 0 */
690     if (index) {
691         ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
692         PORT_SetError(SSL_ERROR_MALFORMED_PRE_SHARED_KEY);
693         return SECFailure;
694     }
695 
696     PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
697     sslPsk *candidate = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
698 
699     /* Check that the server-selected ciphersuite hash and PSK hash match. */
700     if (candidate->hash != tls13_GetHashForCipherSuite(ss->ssl3.hs.cipher_suite)) {
701         ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
702         return SECFailure;
703     }
704 
705     /* Keep track of negotiated extensions. */
706     xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_pre_shared_key_xtn;
707     xtnData->selectedPsk = candidate;
708 
709     return SECSuccess;
710 }
711 
712 /*
713  *  struct { } EarlyDataIndication;
714  */
715 SECStatus
tls13_ClientSendEarlyDataXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)716 tls13_ClientSendEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData,
717                              sslBuffer *buf, PRBool *added)
718 {
719     if (!tls13_ClientAllow0Rtt(ss, ss->sec.ci.sid)) {
720         return SECSuccess;
721     }
722 
723     *added = PR_TRUE;
724     return SECSuccess;
725 }
726 
727 SECStatus
tls13_ServerHandleEarlyDataXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)728 tls13_ServerHandleEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData,
729                                SECItem *data)
730 {
731     SSL_TRC(3, ("%d: TLS13[%d]: handle early_data extension",
732                 SSL_GETPID(), ss->fd));
733 
734     /* If we are doing < TLS 1.3, then ignore this. */
735     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
736         return SECSuccess;
737     }
738 
739     if (ss->ssl3.hs.helloRetry) {
740         ssl3_ExtSendAlert(ss, alert_fatal, unsupported_extension);
741         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
742         return SECFailure;
743     }
744 
745     if (data->len) {
746         PORT_SetError(SSL_ERROR_MALFORMED_EARLY_DATA);
747         return SECFailure;
748     }
749 
750     xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_early_data_xtn;
751 
752     return SECSuccess;
753 }
754 
755 /* This will only be called if we also offered the extension. */
756 SECStatus
tls13_ClientHandleEarlyDataXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)757 tls13_ClientHandleEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData,
758                                SECItem *data)
759 {
760     SSL_TRC(3, ("%d: TLS13[%d]: handle early_data extension",
761                 SSL_GETPID(), ss->fd));
762 
763     /* The server must not send this extension when negotiating < TLS 1.3. */
764     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
765         PORT_SetError(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION);
766         return SECFailure;
767     }
768 
769     if (data->len) {
770         PORT_SetError(SSL_ERROR_MALFORMED_EARLY_DATA);
771         return SECFailure;
772     }
773 
774     /* Keep track of negotiated extensions. */
775     xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_early_data_xtn;
776 
777     return SECSuccess;
778 }
779 
780 SECStatus
tls13_ClientHandleTicketEarlyDataXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)781 tls13_ClientHandleTicketEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData,
782                                      SECItem *data)
783 {
784     PRUint32 utmp;
785     SECStatus rv;
786 
787     SSL_TRC(3, ("%d: TLS13[%d]: handle ticket early_data extension",
788                 SSL_GETPID(), ss->fd));
789 
790     /* The server must not send this extension when negotiating < TLS 1.3. */
791     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
792         PORT_SetError(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION);
793         return SECFailure;
794     }
795 
796     rv = ssl3_ExtConsumeHandshake(ss, &utmp, sizeof(utmp),
797                                   &data->data, &data->len);
798     if (rv != SECSuccess) {
799         PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
800         return SECFailure;
801     }
802     if (data->len) {
803         PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
804         return SECFailure;
805     }
806 
807     xtnData->max_early_data_size = PR_ntohl(utmp);
808 
809     return SECSuccess;
810 }
811 
812 /*
813  *     struct {
814  *       select (Handshake.msg_type) {
815  *       case client_hello:
816  *          ProtocolVersion versions<2..254>;
817  *       case server_hello:
818  *          ProtocolVersion version;
819  *       };
820  *     } SupportedVersions;
821  */
822 SECStatus
tls13_ClientSendSupportedVersionsXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)823 tls13_ClientSendSupportedVersionsXtn(const sslSocket *ss, TLSExtensionData *xtnData,
824                                      sslBuffer *buf, PRBool *added)
825 {
826     PRUint16 version;
827     unsigned int lengthOffset;
828     SECStatus rv;
829 
830     if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
831         return SECSuccess;
832     }
833 
834     SSL_TRC(3, ("%d: TLS13[%d]: client send supported_versions extension",
835                 SSL_GETPID(), ss->fd));
836 
837     rv = sslBuffer_Skip(buf, 1, &lengthOffset);
838     if (rv != SECSuccess) {
839         return SECFailure;
840     }
841 
842     PORT_Assert(!ss->ssl3.hs.echHpkeCtx || ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
843     for (version = ss->vrange.max; version >= ss->vrange.min; --version) {
844         PRUint16 wire = tls13_EncodeVersion(version,
845                                             ss->protocolVariant);
846         rv = sslBuffer_AppendNumber(buf, wire, 2);
847         if (rv != SECSuccess) {
848             return SECFailure;
849         }
850 
851         if (ss->opt.enableDtls13VersionCompat &&
852             ss->protocolVariant == ssl_variant_datagram) {
853             switch (version) {
854                 case SSL_LIBRARY_VERSION_TLS_1_2:
855                 case SSL_LIBRARY_VERSION_TLS_1_1:
856                     rv = sslBuffer_AppendNumber(buf, (PRUint16)version, 2);
857                     break;
858                 default:
859                     continue;
860             }
861             if (rv != SECSuccess) {
862                 return SECFailure;
863             }
864         }
865     }
866 
867     rv = sslBuffer_InsertLength(buf, lengthOffset, 1);
868     if (rv != SECSuccess) {
869         return SECFailure;
870     }
871 
872     *added = PR_TRUE;
873     return SECSuccess;
874 }
875 
876 SECStatus
tls13_ServerSendSupportedVersionsXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)877 tls13_ServerSendSupportedVersionsXtn(const sslSocket *ss, TLSExtensionData *xtnData,
878                                      sslBuffer *buf, PRBool *added)
879 {
880     SECStatus rv;
881 
882     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
883         return SECSuccess;
884     }
885 
886     SSL_TRC(3, ("%d: TLS13[%d]: server send supported_versions extension",
887                 SSL_GETPID(), ss->fd));
888 
889     PRUint16 ver = tls13_EncodeVersion(SSL_LIBRARY_VERSION_TLS_1_3,
890                                        ss->protocolVariant);
891     rv = sslBuffer_AppendNumber(buf, ver, 2);
892     if (rv != SECSuccess) {
893         return SECFailure;
894     }
895 
896     *added = PR_TRUE;
897     return SECSuccess;
898 }
899 
900 /*
901  *    struct {
902  *        opaque cookie<1..2^16-1>;
903  *    } Cookie;
904  */
905 SECStatus
tls13_ClientHandleHrrCookie(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)906 tls13_ClientHandleHrrCookie(const sslSocket *ss, TLSExtensionData *xtnData,
907                             SECItem *data)
908 {
909     SECStatus rv;
910 
911     SSL_TRC(3, ("%d: TLS13[%d]: handle cookie extension",
912                 SSL_GETPID(), ss->fd));
913 
914     PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
915 
916     /* IMPORTANT: this is only valid while the HelloRetryRequest is still valid. */
917     rv = ssl3_ExtConsumeHandshakeVariable(
918         ss, &CONST_CAST(sslSocket, ss)->ssl3.hs.cookie, 2,
919         &data->data, &data->len);
920     if (rv != SECSuccess) {
921         PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST);
922         return SECFailure;
923     }
924     if (!ss->ssl3.hs.cookie.len || data->len) {
925         ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
926         PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST);
927         return SECFailure;
928     }
929 
930     return SECSuccess;
931 }
932 
933 SECStatus
tls13_ClientSendHrrCookieXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)934 tls13_ClientSendHrrCookieXtn(const sslSocket *ss, TLSExtensionData *xtnData,
935                              sslBuffer *buf, PRBool *added)
936 {
937     SECStatus rv;
938 
939     if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3 ||
940         !ss->ssl3.hs.cookie.len) {
941         return SECSuccess;
942     }
943 
944     SSL_TRC(3, ("%d: TLS13[%d]: send cookie extension", SSL_GETPID(), ss->fd));
945     rv = sslBuffer_AppendVariable(buf, ss->ssl3.hs.cookie.data,
946                                   ss->ssl3.hs.cookie.len, 2);
947     if (rv != SECSuccess) {
948         return SECFailure;
949     }
950 
951     *added = PR_TRUE;
952     return SECSuccess;
953 }
954 
955 SECStatus
tls13_ServerHandleCookieXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)956 tls13_ServerHandleCookieXtn(const sslSocket *ss, TLSExtensionData *xtnData,
957                             SECItem *data)
958 {
959     SECStatus rv;
960 
961     SSL_TRC(3, ("%d: TLS13[%d]: handle cookie extension",
962                 SSL_GETPID(), ss->fd));
963 
964     rv = ssl3_ExtConsumeHandshakeVariable(ss, &xtnData->cookie, 2,
965                                           &data->data, &data->len);
966     if (rv != SECSuccess) {
967         return SECFailure;
968     }
969 
970     if (xtnData->cookie.len == 0) {
971         PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
972         return SECFailure;
973     }
974 
975     if (data->len) {
976         PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
977         return SECFailure;
978     }
979 
980     /* Keep track of negotiated extensions. */
981     xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_cookie_xtn;
982 
983     return SECSuccess;
984 }
985 
986 SECStatus
tls13_ClientSendPostHandshakeAuthXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)987 tls13_ClientSendPostHandshakeAuthXtn(const sslSocket *ss,
988                                      TLSExtensionData *xtnData,
989                                      sslBuffer *buf, PRBool *added)
990 {
991     /* Only one post-handshake message is supported: a single
992      * NST immediately following the client Finished. */
993     if (!IS_DTLS(ss)) {
994         SSL_TRC(3, ("%d: TLS13[%d]: send post_handshake_auth extension",
995                     SSL_GETPID(), ss->fd));
996         *added = ss->opt.enablePostHandshakeAuth;
997     }
998     return SECSuccess;
999 }
1000 
1001 SECStatus
tls13_ServerHandlePostHandshakeAuthXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)1002 tls13_ServerHandlePostHandshakeAuthXtn(const sslSocket *ss,
1003                                        TLSExtensionData *xtnData,
1004                                        SECItem *data)
1005 {
1006     SSL_TRC(3, ("%d: TLS13[%d]: handle post_handshake_auth extension",
1007                 SSL_GETPID(), ss->fd));
1008 
1009     if (data->len) {
1010         PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
1011         return SECFailure;
1012     }
1013 
1014     /* Only one post-handshake message is supported: a single
1015      * NST immediately following the client Finished. */
1016     if (!IS_DTLS(ss)) {
1017         /* Keep track of negotiated extensions. */
1018         xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_post_handshake_auth_xtn;
1019     }
1020 
1021     return SECSuccess;
1022 }
1023 
1024 /*
1025  *     enum { psk_ke(0), psk_dhe_ke(1), (255) } PskKeyExchangeMode;
1026  *
1027  *     struct {
1028  *         PskKeyExchangeMode ke_modes<1..255>;
1029  *     } PskKeyExchangeModes;
1030  */
1031 SECStatus
tls13_ClientSendPskModesXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)1032 tls13_ClientSendPskModesXtn(const sslSocket *ss, TLSExtensionData *xtnData,
1033                             sslBuffer *buf, PRBool *added)
1034 {
1035     static const PRUint8 ke_modes[] = { tls13_psk_dh_ke };
1036     SECStatus rv;
1037 
1038     if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3 ||
1039         ss->opt.noCache) {
1040         return SECSuccess;
1041     }
1042 
1043     SSL_TRC(3, ("%d: TLS13[%d]: send psk key exchange modes extension",
1044                 SSL_GETPID(), ss->fd));
1045 
1046     rv = sslBuffer_AppendVariable(buf, ke_modes, sizeof(ke_modes), 1);
1047     if (rv != SECSuccess) {
1048         return SECFailure;
1049     }
1050 
1051     *added = PR_TRUE;
1052     return SECSuccess;
1053 }
1054 
1055 SECStatus
tls13_ServerHandlePskModesXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)1056 tls13_ServerHandlePskModesXtn(const sslSocket *ss, TLSExtensionData *xtnData,
1057                               SECItem *data)
1058 {
1059     SECStatus rv;
1060 
1061     /* If we are doing < TLS 1.3, then ignore this. */
1062     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
1063         return SECSuccess;
1064     }
1065 
1066     SSL_TRC(3, ("%d: TLS13[%d]: handle PSK key exchange modes extension",
1067                 SSL_GETPID(), ss->fd));
1068 
1069     /* IMPORTANT: We aren't copying these values, just setting pointers.
1070      * They will only be valid as long as the ClientHello is in memory. */
1071     rv = ssl3_ExtConsumeHandshakeVariable(ss,
1072                                           &xtnData->psk_ke_modes, 1,
1073                                           &data->data, &data->len);
1074     if (rv != SECSuccess)
1075         return rv;
1076     if (!xtnData->psk_ke_modes.len || data->len) {
1077         PORT_SetError(SSL_ERROR_MALFORMED_PSK_KEY_EXCHANGE_MODES);
1078         return SECFailure;
1079     }
1080 
1081     /* Keep track of negotiated extensions. */
1082     xtnData->negotiated[xtnData->numNegotiated++] =
1083         ssl_tls13_psk_key_exchange_modes_xtn;
1084 
1085     return SECSuccess;
1086 }
1087 
1088 SECStatus
tls13_SendCertAuthoritiesXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)1089 tls13_SendCertAuthoritiesXtn(const sslSocket *ss, TLSExtensionData *xtnData,
1090                              sslBuffer *buf, PRBool *added)
1091 {
1092     unsigned int calen;
1093     const SECItem *name;
1094     unsigned int nnames;
1095     SECStatus rv;
1096 
1097     PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
1098 
1099     rv = ssl_GetCertificateRequestCAs(ss, &calen, &name, &nnames);
1100     if (rv != SECSuccess) {
1101         return SECFailure;
1102     }
1103 
1104     if (!calen) {
1105         return SECSuccess;
1106     }
1107 
1108     rv = sslBuffer_AppendNumber(buf, calen, 2);
1109     if (rv != SECSuccess) {
1110         return SECFailure;
1111     }
1112 
1113     while (nnames) {
1114         rv = sslBuffer_AppendVariable(buf, name->data, name->len, 2);
1115         if (rv != SECSuccess) {
1116             return SECFailure;
1117         }
1118         ++name;
1119         --nnames;
1120     }
1121 
1122     *added = PR_TRUE;
1123     return SECSuccess;
1124 }
1125 
1126 SECStatus
tls13_ClientHandleCertAuthoritiesXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)1127 tls13_ClientHandleCertAuthoritiesXtn(const sslSocket *ss,
1128                                      TLSExtensionData *xtnData,
1129                                      SECItem *data)
1130 {
1131     SECStatus rv;
1132     PLArenaPool *arena;
1133 
1134     if (!data->len) {
1135         ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
1136         PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
1137         return SECFailure;
1138     }
1139 
1140     arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
1141     if (!arena) {
1142         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1143         return SECFailure;
1144     }
1145 
1146     xtnData->certReqAuthorities.arena = arena;
1147     rv = ssl3_ParseCertificateRequestCAs((sslSocket *)ss,
1148                                          &data->data, &data->len,
1149                                          &xtnData->certReqAuthorities);
1150     if (rv != SECSuccess) {
1151         goto loser;
1152     }
1153     if (data->len) {
1154         ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
1155         PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
1156         goto loser;
1157     }
1158     return SECSuccess;
1159 
1160 loser:
1161     PORT_FreeArena(arena, PR_FALSE);
1162     xtnData->certReqAuthorities.arena = NULL;
1163     return SECFailure;
1164 }
1165 
1166 SECStatus
tls13_ServerSendHrrKeyShareXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)1167 tls13_ServerSendHrrKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData,
1168                                sslBuffer *buf, PRBool *added)
1169 {
1170     SECStatus rv;
1171 
1172     PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
1173 
1174     if (!xtnData->selectedGroup) {
1175         return SECSuccess;
1176     }
1177 
1178     rv = sslBuffer_AppendNumber(buf, xtnData->selectedGroup->name, 2);
1179     if (rv != SECSuccess) {
1180         return SECFailure;
1181     }
1182 
1183     *added = PR_TRUE;
1184     return SECSuccess;
1185 }
1186 
1187 SECStatus
tls13_ServerSendHrrCookieXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)1188 tls13_ServerSendHrrCookieXtn(const sslSocket *ss, TLSExtensionData *xtnData,
1189                              sslBuffer *buf, PRBool *added)
1190 {
1191     SECStatus rv;
1192 
1193     PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
1194     PORT_Assert(xtnData->cookie.len > 0);
1195 
1196     rv = sslBuffer_AppendVariable(buf,
1197                                   xtnData->cookie.data, xtnData->cookie.len, 2);
1198     if (rv != SECSuccess) {
1199         return SECFailure;
1200     }
1201 
1202     *added = PR_TRUE;
1203     return SECSuccess;
1204 }
1205 
1206 SECStatus
tls13_ClientHandleEchXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)1207 tls13_ClientHandleEchXtn(const sslSocket *ss, TLSExtensionData *xtnData,
1208                          SECItem *data)
1209 {
1210     SECStatus rv;
1211     PRCList parsedConfigs;
1212     PR_INIT_CLIST(&parsedConfigs);
1213 
1214     PORT_Assert(!xtnData->ech);
1215     xtnData->ech = PORT_ZNew(sslEchXtnState);
1216     if (!xtnData->ech) {
1217         return SECFailure;
1218     }
1219 
1220     /* Parse the list to determine 1) That the configs are valid
1221      * and properly encoded, and 2) If any are compatible. */
1222     rv = tls13_DecodeEchConfigs(data, &parsedConfigs);
1223     if (rv == SECFailure) {
1224         ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
1225         PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_CONFIG);
1226         return SECFailure;
1227     }
1228     /* Don't mark ECH negotiated on rejection with retry_config.
1229      * Save the the raw configs so the application can retry. If
1230      * we sent GREASE ECH (no echHpkeCtx), don't apply retry_configs. */
1231     if (ss->ssl3.hs.echHpkeCtx && !PR_CLIST_IS_EMPTY(&parsedConfigs)) {
1232         rv = SECITEM_CopyItem(NULL, &xtnData->ech->retryConfigs, data);
1233     }
1234     tls13_DestroyEchConfigs(&parsedConfigs);
1235 
1236     return rv;
1237 }
1238 
1239 /* Indicates support for the delegated credentials extension. This should be
1240  * hooked while processing the ClientHello. */
1241 SECStatus
tls13_ClientSendDelegatedCredentialsXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)1242 tls13_ClientSendDelegatedCredentialsXtn(const sslSocket *ss,
1243                                         TLSExtensionData *xtnData,
1244                                         sslBuffer *buf, PRBool *added)
1245 {
1246     /* Only send the extension if support is enabled and the client can
1247      * negotiate TLS 1.3. */
1248     if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3 ||
1249         !ss->opt.enableDelegatedCredentials) {
1250         return SECSuccess;
1251     }
1252 
1253     /* Filter the schemes that are enabled and acceptable. Save these in
1254      * the "advertised" list, then encode them to be sent. If we receive
1255      * a DC in response, validate that it matches one of the advertised
1256      * schemes. */
1257     SSLSignatureScheme filtered[MAX_SIGNATURE_SCHEMES] = { 0 };
1258     unsigned int filteredCount = 0;
1259     SECStatus rv = ssl3_FilterSigAlgs(ss, ss->vrange.max,
1260                                       PR_TRUE /* disableRsae */,
1261                                       PR_FALSE /* forCert */,
1262                                       MAX_SIGNATURE_SCHEMES,
1263                                       filtered,
1264                                       &filteredCount);
1265     if (rv != SECSuccess) {
1266         return SECFailure;
1267     }
1268 
1269     /* If no schemes available for the DC extension, don't send it. */
1270     if (!filteredCount) {
1271         return SECSuccess;
1272     }
1273 
1274     rv = ssl3_EncodeFilteredSigAlgs(ss, filtered, filteredCount, buf);
1275     if (rv != SECSuccess) {
1276         return SECFailure;
1277     }
1278 
1279     SSLSignatureScheme *dcSchemesAdvertised = PORT_ZNewArray(SSLSignatureScheme,
1280                                                              filteredCount);
1281     if (!dcSchemesAdvertised) {
1282         return SECFailure;
1283     }
1284     for (unsigned int i = 0; i < filteredCount; i++) {
1285         dcSchemesAdvertised[i] = filtered[i];
1286     }
1287 
1288     if (xtnData->delegCredSigSchemesAdvertised) {
1289         PORT_Free(xtnData->delegCredSigSchemesAdvertised);
1290     }
1291     xtnData->delegCredSigSchemesAdvertised = dcSchemesAdvertised;
1292     xtnData->numDelegCredSigSchemesAdvertised = filteredCount;
1293     *added = PR_TRUE;
1294     return SECSuccess;
1295 }
1296 
1297 /* Parses the delegated credential (DC) offered by the server. This should be
1298  * hooked while processing the server's CertificateVerify.
1299  *
1300  * Only the DC sent with the end-entity certificate is to be parsed. This is
1301  * ensured by |tls13_HandleCertificateEntry|, which only processes extensions
1302  * for the first certificate in the chain.
1303  */
1304 SECStatus
tls13_ClientHandleDelegatedCredentialsXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)1305 tls13_ClientHandleDelegatedCredentialsXtn(const sslSocket *ss,
1306                                           TLSExtensionData *xtnData,
1307                                           SECItem *data)
1308 {
1309     if (!ss->opt.enableDelegatedCredentials ||
1310         ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
1311         ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
1312         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
1313         return SECFailure;
1314     }
1315 
1316     sslDelegatedCredential *dc = NULL;
1317     SECStatus rv = tls13_ReadDelegatedCredential(data->data, data->len, &dc);
1318     if (rv != SECSuccess) {
1319         goto loser; /* code already set */
1320     }
1321 
1322     /* When using RSA, the public key MUST NOT use the rsaEncryption OID. */
1323     if (dc->expectedCertVerifyAlg == ssl_sig_rsa_pss_rsae_sha256 ||
1324         dc->expectedCertVerifyAlg == ssl_sig_rsa_pss_rsae_sha384 ||
1325         dc->expectedCertVerifyAlg == ssl_sig_rsa_pss_rsae_sha512) {
1326         goto alert_loser;
1327     }
1328 
1329     /* The algorithm and expected_cert_verify_algorithm fields MUST be of a
1330      * type advertised by the client in the SignatureSchemeList and are
1331      * considered invalid otherwise.  Clients that receive invalid delegated
1332      * credentials MUST terminate the connection with an "illegal_parameter"
1333      * alert. */
1334     PRBool found = PR_FALSE;
1335     for (unsigned int i = 0; i < ss->xtnData.numDelegCredSigSchemesAdvertised; ++i) {
1336         if (dc->expectedCertVerifyAlg == ss->xtnData.delegCredSigSchemesAdvertised[i]) {
1337             found = PR_TRUE;
1338             break;
1339         }
1340     }
1341     if (found == PR_FALSE) {
1342         goto alert_loser;
1343     }
1344 
1345     // Check the dc->alg, if necessary.
1346     if (dc->alg != dc->expectedCertVerifyAlg) {
1347         found = PR_FALSE;
1348         for (unsigned int i = 0; i < ss->xtnData.numDelegCredSigSchemesAdvertised; ++i) {
1349             if (dc->alg == ss->xtnData.delegCredSigSchemesAdvertised[i]) {
1350                 found = PR_TRUE;
1351                 break;
1352             }
1353         }
1354         if (found == PR_FALSE) {
1355             goto alert_loser;
1356         }
1357     }
1358 
1359     xtnData->peerDelegCred = dc;
1360     xtnData->negotiated[xtnData->numNegotiated++] =
1361         ssl_delegated_credentials_xtn;
1362     return SECSuccess;
1363 alert_loser:
1364     ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
1365     PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
1366 loser:
1367     tls13_DestroyDelegatedCredential(dc);
1368     return SECFailure;
1369 }
1370 
1371 /* Adds the DC extension if we're committed to authenticating with a DC. */
1372 static SECStatus
tls13_ServerSendDelegatedCredentialsXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)1373 tls13_ServerSendDelegatedCredentialsXtn(const sslSocket *ss,
1374                                         TLSExtensionData *xtnData,
1375                                         sslBuffer *buf, PRBool *added)
1376 {
1377     if (tls13_IsSigningWithDelegatedCredential(ss)) {
1378         const SECItem *dc = &ss->sec.serverCert->delegCred;
1379         SECStatus rv;
1380         rv = sslBuffer_Append(buf, dc->data, dc->len);
1381         if (rv != SECSuccess) {
1382             return SECFailure;
1383         }
1384         *added = PR_TRUE;
1385     }
1386     return SECSuccess;
1387 }
1388 
1389 /* The client has indicated support of DCs. We can't act on this information
1390  * until we've committed to signing with a DC, so just set a callback for
1391  * sending the DC extension later. */
1392 SECStatus
tls13_ServerHandleDelegatedCredentialsXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)1393 tls13_ServerHandleDelegatedCredentialsXtn(const sslSocket *ss,
1394                                           TLSExtensionData *xtnData,
1395                                           SECItem *data)
1396 {
1397     if (xtnData->delegCredSigSchemes) {
1398         PORT_Free(xtnData->delegCredSigSchemes);
1399         xtnData->delegCredSigSchemes = NULL;
1400         xtnData->numDelegCredSigSchemes = 0;
1401     }
1402     SECStatus rv = ssl_ParseSignatureSchemes(ss, NULL,
1403                                              &xtnData->delegCredSigSchemes,
1404                                              &xtnData->numDelegCredSigSchemes,
1405                                              &data->data, &data->len);
1406     if (rv != SECSuccess) {
1407         ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
1408         PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
1409         return SECFailure;
1410     }
1411     if (xtnData->numDelegCredSigSchemes == 0) {
1412         ssl3_ExtSendAlert(ss, alert_fatal, handshake_failure);
1413         PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
1414         return SECFailure;
1415     }
1416     /* Check for trailing data. */
1417     if (data->len != 0) {
1418         ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
1419         PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
1420         return SECFailure;
1421     }
1422 
1423     /* Keep track of negotiated extensions. */
1424     xtnData->peerRequestedDelegCred = PR_TRUE;
1425     xtnData->negotiated[xtnData->numNegotiated++] =
1426         ssl_delegated_credentials_xtn;
1427 
1428     return ssl3_RegisterExtensionSender(
1429         ss, xtnData, ssl_delegated_credentials_xtn,
1430         tls13_ServerSendDelegatedCredentialsXtn);
1431 }
1432 
1433 /* Adds the ECH extension containing server retry_configs */
1434 SECStatus
tls13_ServerSendEchXtn(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * added)1435 tls13_ServerSendEchXtn(const sslSocket *ss,
1436                        TLSExtensionData *xtnData,
1437                        sslBuffer *buf, PRBool *added)
1438 {
1439     SECStatus rv;
1440     PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
1441     if (PR_CLIST_IS_EMPTY(&ss->echConfigs)) {
1442         return SECSuccess;
1443     }
1444 
1445     const sslEchConfig *cfg = (sslEchConfig *)PR_LIST_HEAD(&ss->echConfigs);
1446     rv = sslBuffer_AppendVariable(buf, cfg->raw.data, cfg->raw.len, 2);
1447     if (rv != SECSuccess) {
1448         return SECFailure;
1449     }
1450 
1451     *added = PR_TRUE;
1452     return SECSuccess;
1453 }
1454 
1455 SECStatus
tls13_ServerHandleEchXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)1456 tls13_ServerHandleEchXtn(const sslSocket *ss, TLSExtensionData *xtnData,
1457                          SECItem *data)
1458 {
1459     SECStatus rv;
1460     HpkeKdfId kdf;
1461     HpkeAeadId aead;
1462     PRUint32 tmp;
1463     PRUint8 configId;
1464     SECItem senderPubKey;
1465     SECItem encryptedCh;
1466 
1467     /* Ignore it if not doing 1.3+. If we have no ECHConfigs,
1468      * proceed to save the config_id for HRR validation. */
1469     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3 ||
1470         IS_DTLS(ss)) {
1471         return SECSuccess;
1472     }
1473 
1474     if (ss->ssl3.hs.echAccepted) {
1475         ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
1476         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
1477         return SECFailure;
1478     }
1479 
1480     if (ssl3_FindExtension(CONST_CAST(sslSocket, ss), ssl_tls13_ech_is_inner_xtn)) {
1481         ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
1482         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
1483         return SECFailure;
1484     }
1485 
1486     PORT_Assert(!xtnData->ech);
1487     xtnData->ech = PORT_ZNew(sslEchXtnState);
1488     if (!xtnData->ech) {
1489         return SECFailure;
1490     }
1491 
1492     /* Parse the KDF and AEAD. */
1493     rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2,
1494                                         &data->data, &data->len);
1495     if (rv != SECSuccess) {
1496         goto alert_loser;
1497     }
1498     kdf = (HpkeKdfId)tmp;
1499     rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2,
1500                                         &data->data, &data->len);
1501     if (rv != SECSuccess) {
1502         goto alert_loser;
1503     }
1504     aead = (HpkeAeadId)tmp;
1505 
1506     /* config_id */
1507     rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 1,
1508                                         &data->data, &data->len);
1509     if (rv != SECSuccess) {
1510         goto alert_loser;
1511     }
1512     configId = tmp;
1513 
1514     /* enc */
1515     rv = ssl3_ExtConsumeHandshakeVariable(ss, &senderPubKey, 2,
1516                                           &data->data, &data->len);
1517     if (rv != SECSuccess) {
1518         goto alert_loser;
1519     }
1520 
1521     /* payload, which must be final and non-empty. */
1522     rv = ssl3_ExtConsumeHandshakeVariable(ss, &encryptedCh, 2,
1523                                           &data->data, &data->len);
1524     if (rv != SECSuccess) {
1525         goto alert_loser;
1526     }
1527     if (data->len || !encryptedCh.len) {
1528         goto alert_loser;
1529     }
1530 
1531     if (!ss->ssl3.hs.helloRetry) {
1532         /* In the real ECH HRR case, config_id and enc should be empty. This
1533          * is checked after acceptance, because it might be GREASE ECH. */
1534         if (!senderPubKey.len) {
1535             goto alert_loser;
1536         }
1537 
1538         rv = SECITEM_CopyItem(NULL, &xtnData->ech->senderPubKey, &senderPubKey);
1539         if (rv == SECFailure) {
1540             return SECFailure;
1541         }
1542     }
1543 
1544     rv = SECITEM_CopyItem(NULL, &xtnData->ech->innerCh, &encryptedCh);
1545     if (rv == SECFailure) {
1546         return SECFailure;
1547     }
1548     xtnData->ech->configId = configId;
1549     xtnData->ech->kdfId = kdf;
1550     xtnData->ech->aeadId = aead;
1551 
1552     /* Not negotiated until tls13_MaybeAcceptEch. */
1553     return SECSuccess;
1554 
1555 alert_loser:
1556     ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
1557     PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_EXTENSION);
1558     return SECFailure;
1559 }
1560 
1561 SECStatus
tls13_ServerHandleEchIsInnerXtn(const sslSocket * ss,TLSExtensionData * xtnData,SECItem * data)1562 tls13_ServerHandleEchIsInnerXtn(const sslSocket *ss,
1563                                 TLSExtensionData *xtnData,
1564                                 SECItem *data)
1565 {
1566     SSL_TRC(3, ("%d: TLS13[%d]: handle ech_is_inner extension",
1567                 SSL_GETPID(), ss->fd));
1568 
1569     if (data->len) {
1570         PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_EXTENSION);
1571         return SECFailure;
1572     }
1573 
1574     if (ssl3_FindExtension(CONST_CAST(sslSocket, ss), ssl_tls13_encrypted_client_hello_xtn)) {
1575         ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
1576         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
1577         return SECFailure;
1578     }
1579 
1580     /* Consider encrypted_client_hello_xtn negotiated if we performed the
1581      * CHOuter decryption. This is only supported in shared mode, so we'll also
1582      * handle ech_is_inner in that case. We might, however, receive a CHInner
1583      * that was forwarded by a different client-facing server. In this case,
1584      * mark ech_is_inner as negotiated, which triggers sending of the ECH
1585      * acceptance signal. ech_is_inner_xtn being negotiated does not imply
1586      * that any other ECH state actually exists. */
1587     if (ss->ssl3.hs.echAccepted) {
1588         xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_encrypted_client_hello_xtn;
1589     }
1590     xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_ech_is_inner_xtn;
1591     return SECSuccess;
1592 }
1593