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